@bonesofspring/ai-rules 0.2.73 → 0.2.74

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 (216) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +1 -1
  3. package/bin/lib/engine-scripts.js +8 -0
  4. package/docs/TEAM-DB.md +86 -5
  5. package/docs/openapi/team-db.v1.json +1164 -224
  6. package/package.json +1 -1
  7. package/presets/_shared/ai-local/scripts/action-signals.mjs +225 -0
  8. package/presets/_shared/ai-local/scripts/actions-report.mjs +210 -0
  9. package/presets/_shared/ai-local/scripts/processes.mjs +5 -4
  10. package/presets/_shared/ai-local/scripts/rr-scheduler-start.mjs +161 -0
  11. package/presets/_shared/ai-local/scripts/team-db-api.mjs +347 -9
  12. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +309 -4
  13. package/presets/_shared/ai-local/scripts/team-db-project.mjs +239 -25
  14. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +86 -1
  15. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +15 -1
  16. package/presets/claude/android-kotlin/commands/README.md +4 -0
  17. package/presets/claude/android-kotlin/commands/rr-scheduler-start.md +32 -0
  18. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +15 -1
  19. package/presets/claude/go/commands/README.md +4 -0
  20. package/presets/claude/go/commands/rr-scheduler-start.md +32 -0
  21. package/presets/claude/go/hooks/chain-team-phases.sh +15 -1
  22. package/presets/claude/ios-swift/commands/README.md +4 -0
  23. package/presets/claude/ios-swift/commands/rr-scheduler-start.md +32 -0
  24. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +15 -1
  25. package/presets/claude/java/commands/README.md +4 -0
  26. package/presets/claude/java/commands/rr-scheduler-start.md +32 -0
  27. package/presets/claude/java/hooks/chain-team-phases.sh +15 -1
  28. package/presets/claude/mcp-ts/commands/README.md +4 -0
  29. package/presets/claude/mcp-ts/commands/rr-scheduler-start.md +32 -0
  30. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +15 -1
  31. package/presets/claude/mol/commands/README.md +4 -0
  32. package/presets/claude/mol/commands/rr-scheduler-start.md +32 -0
  33. package/presets/claude/mol/hooks/chain-team-phases.sh +15 -1
  34. package/presets/claude/next/commands/README.md +4 -0
  35. package/presets/claude/next/commands/rr-scheduler-start.md +32 -0
  36. package/presets/claude/next/hooks/chain-team-phases.sh +15 -1
  37. package/presets/claude/nuxt/commands/README.md +4 -0
  38. package/presets/claude/nuxt/commands/rr-scheduler-start.md +32 -0
  39. package/presets/claude/nuxt/hooks/chain-team-phases.sh +15 -1
  40. package/presets/claude/php-hexagonal/commands/README.md +4 -0
  41. package/presets/claude/php-hexagonal/commands/rr-scheduler-start.md +32 -0
  42. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +15 -1
  43. package/presets/claude/php-laravel/commands/README.md +4 -0
  44. package/presets/claude/php-laravel/commands/rr-scheduler-start.md +32 -0
  45. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +15 -1
  46. package/presets/claude/svelte/commands/README.md +4 -0
  47. package/presets/claude/svelte/commands/rr-scheduler-start.md +32 -0
  48. package/presets/claude/svelte/hooks/chain-team-phases.sh +15 -1
  49. package/presets/cursor/android-kotlin/commands/README.md +4 -0
  50. package/presets/cursor/android-kotlin/commands/rr-scheduler-start.md +32 -0
  51. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +15 -1
  52. package/presets/cursor/go/commands/README.md +4 -0
  53. package/presets/cursor/go/commands/rr-scheduler-start.md +32 -0
  54. package/presets/cursor/go/hooks/chain-team-phases.sh +15 -1
  55. package/presets/cursor/ios-swift/commands/README.md +4 -0
  56. package/presets/cursor/ios-swift/commands/rr-scheduler-start.md +32 -0
  57. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +15 -1
  58. package/presets/cursor/java/commands/README.md +4 -0
  59. package/presets/cursor/java/commands/rr-scheduler-start.md +32 -0
  60. package/presets/cursor/java/hooks/chain-team-phases.sh +15 -1
  61. package/presets/cursor/mcp-ts/commands/README.md +4 -0
  62. package/presets/cursor/mcp-ts/commands/rr-scheduler-start.md +32 -0
  63. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +15 -1
  64. package/presets/cursor/mol/commands/README.md +4 -0
  65. package/presets/cursor/mol/commands/rr-scheduler-start.md +32 -0
  66. package/presets/cursor/mol/hooks/chain-team-phases.sh +15 -1
  67. package/presets/cursor/next/commands/README.md +4 -0
  68. package/presets/cursor/next/commands/rr-scheduler-start.md +32 -0
  69. package/presets/cursor/next/hooks/chain-team-phases.sh +15 -1
  70. package/presets/cursor/nuxt/commands/README.md +4 -0
  71. package/presets/cursor/nuxt/commands/rr-scheduler-start.md +32 -0
  72. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +15 -1
  73. package/presets/cursor/php-hexagonal/commands/README.md +4 -0
  74. package/presets/cursor/php-hexagonal/commands/rr-scheduler-start.md +32 -0
  75. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +15 -1
  76. package/presets/cursor/php-laravel/commands/README.md +4 -0
  77. package/presets/cursor/php-laravel/commands/rr-scheduler-start.md +32 -0
  78. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +15 -1
  79. package/presets/cursor/svelte/commands/README.md +4 -0
  80. package/presets/cursor/svelte/commands/rr-scheduler-start.md +32 -0
  81. package/presets/cursor/svelte/hooks/chain-team-phases.sh +15 -1
  82. package/presets/mavis/android-kotlin/adapter-map.json +9 -1
  83. package/presets/mavis/android-kotlin/commands/README.md +4 -0
  84. package/presets/mavis/android-kotlin/commands/rr-scheduler-start.md +27 -0
  85. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +15 -1
  86. package/presets/mavis/go/adapter-map.json +9 -1
  87. package/presets/mavis/go/commands/README.md +4 -0
  88. package/presets/mavis/go/commands/rr-scheduler-start.md +27 -0
  89. package/presets/mavis/go/hooks/chain-team-phases.sh +15 -1
  90. package/presets/mavis/ios-swift/adapter-map.json +9 -1
  91. package/presets/mavis/ios-swift/commands/README.md +4 -0
  92. package/presets/mavis/ios-swift/commands/rr-scheduler-start.md +27 -0
  93. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +15 -1
  94. package/presets/mavis/java/adapter-map.json +9 -1
  95. package/presets/mavis/java/commands/README.md +4 -0
  96. package/presets/mavis/java/commands/rr-scheduler-start.md +27 -0
  97. package/presets/mavis/java/hooks/chain-team-phases.sh +15 -1
  98. package/presets/mavis/mcp-ts/adapter-map.json +9 -1
  99. package/presets/mavis/mcp-ts/commands/README.md +4 -0
  100. package/presets/mavis/mcp-ts/commands/rr-scheduler-start.md +27 -0
  101. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +15 -1
  102. package/presets/mavis/mol/adapter-map.json +9 -1
  103. package/presets/mavis/mol/commands/README.md +4 -0
  104. package/presets/mavis/mol/commands/rr-scheduler-start.md +27 -0
  105. package/presets/mavis/mol/hooks/chain-team-phases.sh +15 -1
  106. package/presets/mavis/next/adapter-map.json +9 -1
  107. package/presets/mavis/next/commands/README.md +4 -0
  108. package/presets/mavis/next/commands/rr-scheduler-start.md +27 -0
  109. package/presets/mavis/next/hooks/chain-team-phases.sh +15 -1
  110. package/presets/mavis/nuxt/adapter-map.json +9 -1
  111. package/presets/mavis/nuxt/commands/README.md +4 -0
  112. package/presets/mavis/nuxt/commands/rr-scheduler-start.md +27 -0
  113. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +15 -1
  114. package/presets/mavis/php-hexagonal/adapter-map.json +9 -1
  115. package/presets/mavis/php-hexagonal/commands/README.md +4 -0
  116. package/presets/mavis/php-hexagonal/commands/rr-scheduler-start.md +27 -0
  117. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +15 -1
  118. package/presets/mavis/php-laravel/adapter-map.json +9 -1
  119. package/presets/mavis/php-laravel/commands/README.md +4 -0
  120. package/presets/mavis/php-laravel/commands/rr-scheduler-start.md +27 -0
  121. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +15 -1
  122. package/presets/mavis/svelte/adapter-map.json +9 -1
  123. package/presets/mavis/svelte/commands/README.md +4 -0
  124. package/presets/mavis/svelte/commands/rr-scheduler-start.md +27 -0
  125. package/presets/mavis/svelte/hooks/chain-team-phases.sh +15 -1
  126. package/presets/opencode/android-kotlin/adapter-map.json +9 -1
  127. package/presets/opencode/android-kotlin/commands/README.md +4 -0
  128. package/presets/opencode/android-kotlin/commands/rr-scheduler-start.md +35 -0
  129. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +15 -1
  130. package/presets/opencode/go/adapter-map.json +9 -1
  131. package/presets/opencode/go/commands/README.md +4 -0
  132. package/presets/opencode/go/commands/rr-scheduler-start.md +35 -0
  133. package/presets/opencode/go/hooks/chain-team-phases.sh +15 -1
  134. package/presets/opencode/ios-swift/adapter-map.json +9 -1
  135. package/presets/opencode/ios-swift/commands/README.md +4 -0
  136. package/presets/opencode/ios-swift/commands/rr-scheduler-start.md +35 -0
  137. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +15 -1
  138. package/presets/opencode/java/adapter-map.json +9 -1
  139. package/presets/opencode/java/commands/README.md +4 -0
  140. package/presets/opencode/java/commands/rr-scheduler-start.md +35 -0
  141. package/presets/opencode/java/hooks/chain-team-phases.sh +15 -1
  142. package/presets/opencode/mcp-ts/adapter-map.json +9 -1
  143. package/presets/opencode/mcp-ts/commands/README.md +4 -0
  144. package/presets/opencode/mcp-ts/commands/rr-scheduler-start.md +35 -0
  145. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +15 -1
  146. package/presets/opencode/mol/adapter-map.json +9 -1
  147. package/presets/opencode/mol/commands/README.md +4 -0
  148. package/presets/opencode/mol/commands/rr-scheduler-start.md +35 -0
  149. package/presets/opencode/mol/hooks/chain-team-phases.sh +15 -1
  150. package/presets/opencode/next/adapter-map.json +9 -1
  151. package/presets/opencode/next/commands/README.md +4 -0
  152. package/presets/opencode/next/commands/rr-scheduler-start.md +35 -0
  153. package/presets/opencode/next/hooks/chain-team-phases.sh +15 -1
  154. package/presets/opencode/nuxt/adapter-map.json +9 -1
  155. package/presets/opencode/nuxt/commands/README.md +4 -0
  156. package/presets/opencode/nuxt/commands/rr-scheduler-start.md +35 -0
  157. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +15 -1
  158. package/presets/opencode/php-hexagonal/adapter-map.json +9 -1
  159. package/presets/opencode/php-hexagonal/commands/README.md +4 -0
  160. package/presets/opencode/php-hexagonal/commands/rr-scheduler-start.md +35 -0
  161. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +15 -1
  162. package/presets/opencode/php-laravel/adapter-map.json +9 -1
  163. package/presets/opencode/php-laravel/commands/README.md +4 -0
  164. package/presets/opencode/php-laravel/commands/rr-scheduler-start.md +35 -0
  165. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +15 -1
  166. package/presets/opencode/plugins/output-guard/README.md +42 -1
  167. package/presets/opencode/plugins/output-guard/actions.ts +201 -0
  168. package/presets/opencode/plugins/output-guard/index.ts +147 -6
  169. package/presets/opencode/svelte/adapter-map.json +9 -1
  170. package/presets/opencode/svelte/commands/README.md +4 -0
  171. package/presets/opencode/svelte/commands/rr-scheduler-start.md +35 -0
  172. package/presets/opencode/svelte/hooks/chain-team-phases.sh +15 -1
  173. package/presets/zcode/android-kotlin/adapter-map.json +9 -1
  174. package/presets/zcode/android-kotlin/commands/README.md +4 -0
  175. package/presets/zcode/android-kotlin/commands/rr-scheduler-start.md +35 -0
  176. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +15 -1
  177. package/presets/zcode/go/adapter-map.json +9 -1
  178. package/presets/zcode/go/commands/README.md +4 -0
  179. package/presets/zcode/go/commands/rr-scheduler-start.md +35 -0
  180. package/presets/zcode/go/hooks/chain-team-phases.sh +15 -1
  181. package/presets/zcode/ios-swift/adapter-map.json +9 -1
  182. package/presets/zcode/ios-swift/commands/README.md +4 -0
  183. package/presets/zcode/ios-swift/commands/rr-scheduler-start.md +35 -0
  184. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +15 -1
  185. package/presets/zcode/java/adapter-map.json +9 -1
  186. package/presets/zcode/java/commands/README.md +4 -0
  187. package/presets/zcode/java/commands/rr-scheduler-start.md +35 -0
  188. package/presets/zcode/java/hooks/chain-team-phases.sh +15 -1
  189. package/presets/zcode/mcp-ts/adapter-map.json +9 -1
  190. package/presets/zcode/mcp-ts/commands/README.md +4 -0
  191. package/presets/zcode/mcp-ts/commands/rr-scheduler-start.md +35 -0
  192. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +15 -1
  193. package/presets/zcode/mol/adapter-map.json +9 -1
  194. package/presets/zcode/mol/commands/README.md +4 -0
  195. package/presets/zcode/mol/commands/rr-scheduler-start.md +35 -0
  196. package/presets/zcode/mol/hooks/chain-team-phases.sh +15 -1
  197. package/presets/zcode/next/adapter-map.json +9 -1
  198. package/presets/zcode/next/commands/README.md +4 -0
  199. package/presets/zcode/next/commands/rr-scheduler-start.md +35 -0
  200. package/presets/zcode/next/hooks/chain-team-phases.sh +15 -1
  201. package/presets/zcode/nuxt/adapter-map.json +9 -1
  202. package/presets/zcode/nuxt/commands/README.md +4 -0
  203. package/presets/zcode/nuxt/commands/rr-scheduler-start.md +35 -0
  204. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +15 -1
  205. package/presets/zcode/php-hexagonal/adapter-map.json +9 -1
  206. package/presets/zcode/php-hexagonal/commands/README.md +4 -0
  207. package/presets/zcode/php-hexagonal/commands/rr-scheduler-start.md +35 -0
  208. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +15 -1
  209. package/presets/zcode/php-laravel/adapter-map.json +9 -1
  210. package/presets/zcode/php-laravel/commands/README.md +4 -0
  211. package/presets/zcode/php-laravel/commands/rr-scheduler-start.md +35 -0
  212. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +15 -1
  213. package/presets/zcode/svelte/adapter-map.json +9 -1
  214. package/presets/zcode/svelte/commands/README.md +4 -0
  215. package/presets/zcode/svelte/commands/rr-scheduler-start.md +35 -0
  216. package/presets/zcode/svelte/hooks/chain-team-phases.sh +15 -1
@@ -32,6 +32,7 @@ import {
32
32
  readSearchMode,
33
33
  teamDbFail,
34
34
  } from './team-db-schema.mjs';
35
+ import { ACTION_ERROR_CLASSES } from './action-signals.mjs';
35
36
  import { projectScheduler, retainRuns } from './team-db-scheduler.mjs';
36
37
  import { validateEntrySchema, validateItemSchema, validateLinkIdentity, validateLinkSchema } from './team-db-tracker.mjs';
37
38
 
@@ -40,6 +41,10 @@ export const MAX_RAW_BYTES = 32 * 1024 * 1024;
40
41
  export const RETENTION_DAYS = 90;
41
42
  export const SYNC_RUN_RETENTION = 200;
42
43
  export const DEFAULT_SLUG_DEADLINE_MS = 4500;
44
+ /** The grace a lease window keeps after its last write, in milliseconds. */
45
+ export const LEASE_TTL_MS = 30 * 60 * 1000;
46
+ /** The fuzz around the last write of `tasks/<slug>` for the weakest rung. */
47
+ export const DIR_WINDOW_MS = 30 * 60 * 1000;
43
48
 
44
49
  const HASH_CHUNK = 64 * 1024;
45
50
  const MAX_KNOWN_BYTES = 8 * 1024 * 1024;
@@ -800,6 +805,54 @@ const numberOrNull = (value) =>
800
805
 
801
806
  const realOrNull = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null);
802
807
 
808
+ /** A counter the plugin reported: a non-negative integer, or nothing at all. */
809
+ const countOrNull = (value) =>
810
+ typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : null;
811
+
812
+ /** A hash the capture plane is allowed to store. */
813
+ const HASH_RE = /^[0-9a-f]{64}$/;
814
+ /** An agent name: a short identifier, never a path or a sentence. */
815
+ const AGENT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
816
+ /** A host session or call id. */
817
+ const HOST_ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;
818
+ /** The failure classes of `design.md` D-3; anything else is refused. */
819
+ export const ERROR_CLASSES = new Set(ACTION_ERROR_CLASSES);
820
+
821
+ /**
822
+ * The captured half of an action row.
823
+ *
824
+ * The projector never truncates text into the database: a value that is not a
825
+ * hash, an enum member or a bounded identifier is dropped to `null` and counted,
826
+ * so one line of `team-db-errors.log` names the refusal without ever carrying
827
+ * the value.
828
+ */
829
+ const captureFields = (row, onRefuse) => {
830
+ const refuse = () => onRefuse();
831
+ const hash = typeof row.targetKey === 'string' && HASH_RE.test(row.targetKey) ? row.targetKey : null;
832
+ if (row.targetKey !== undefined && row.targetKey !== null && hash === null) refuse();
833
+ const agent = typeof row.agent === 'string' && AGENT_RE.test(row.agent) ? row.agent : null;
834
+ if (row.agent !== undefined && row.agent !== null && row.agent !== '' && agent === null) refuse();
835
+ const parentSessionId =
836
+ typeof row.parentSessionID === 'string' && HOST_ID_RE.test(row.parentSessionID) ? row.parentSessionID : null;
837
+ if (row.parentSessionID !== undefined && row.parentSessionID !== null && parentSessionId === null) refuse();
838
+ const repeatOf = typeof row.repeatOf === 'string' && HOST_ID_RE.test(row.repeatOf) ? row.repeatOf : null;
839
+ if (row.repeatOf !== undefined && row.repeatOf !== null && repeatOf === null) refuse();
840
+ const errorClass =
841
+ typeof row.errorClass === 'string' && ERROR_CLASSES.has(row.errorClass) ? row.errorClass : null;
842
+ if (row.errorClass !== undefined && row.errorClass !== null && errorClass === null) refuse();
843
+ return {
844
+ agent,
845
+ parentSessionId,
846
+ durationMs: countOrNull(row.durationMs),
847
+ gapMs: countOrNull(row.gapMs),
848
+ targetKey: hash,
849
+ repeatOf,
850
+ repeatIndex: countOrNull(row.repeatIndex),
851
+ exitCode: countOrNull(row.exit),
852
+ errorClass,
853
+ };
854
+ };
855
+
803
856
  const usageModel = (value) => {
804
857
  if (typeof value === 'string' && value !== '') {
805
858
  const separator = value.indexOf('/');
@@ -2095,7 +2148,54 @@ const classifyToolCall = (row) => {
2095
2148
  return 'other';
2096
2149
  };
2097
2150
 
2098
- const normalizeToolCall = (row) => {
2151
+ /** The tool → intent map of `design.md` D-2; nothing outside it is a new value. */
2152
+ const INTENT_BY_TOOL = new Map([
2153
+ ['read', 'explore'],
2154
+ ['grep', 'explore'],
2155
+ ['glob', 'explore'],
2156
+ ['list', 'explore'],
2157
+ ['edit', 'mutate'],
2158
+ ['write', 'mutate'],
2159
+ ['patch', 'mutate'],
2160
+ ['shell', 'execute'],
2161
+ ['bash', 'execute'],
2162
+ ['execute', 'execute'],
2163
+ ['subagent', 'delegate'],
2164
+ ['task', 'delegate'],
2165
+ ['question', 'ask'],
2166
+ ['permission', 'ask'],
2167
+ ['skill', 'meta'],
2168
+ ['todowrite', 'meta'],
2169
+ ['todoread', 'meta'],
2170
+ ['plan', 'meta'],
2171
+ ['webfetch', 'web'],
2172
+ ['websearch', 'web'],
2173
+ ]);
2174
+
2175
+ /**
2176
+ * The seven-value intent of one tool call.
2177
+ * * A sibling of `classifyToolCall` rather than a rewrite: `category` is read by
2178
+ * `report-efficiency.mjs` and pinned against it by a drift test, so the two
2179
+ * classifiers stay independent. An unknown tool lands in `meta` with its name
2180
+ * kept in `tool` — never back in a bucket that hides it.
2181
+ */
2182
+ export const intentOf = (row) => {
2183
+ const tool = String(row?.tool ?? '').toLowerCase();
2184
+ if (INTENT_BY_TOOL.has(tool)) return INTENT_BY_TOOL.get(tool);
2185
+ // The legacy command shapes still mean what they meant; a tool outside the
2186
+ // map is read through its command before it falls to `meta`. A network fetch
2187
+ // is decided before the test/build shapes, so `curl https://host.test` stays
2188
+ // a `web` action.
2189
+ const command = String(row?.command ?? '');
2190
+ if (/\b(curl|wget|http)\b/i.test(command)) return 'web';
2191
+ if (/\b(git|test|lint|type-check|tsc|vitest|jest|playwright|eslint|build|compile|bundle)\b/i.test(command)) {
2192
+ return 'execute';
2193
+ }
2194
+ if (/\b(grep|rg|find|search)\b/i.test(command)) return 'explore';
2195
+ return 'meta';
2196
+ };
2197
+
2198
+ const normalizeToolCall = (row, onRefuse = () => {}) => {
2099
2199
  if (!isRecord(row)) return null;
2100
2200
  const sessionID = typeof row.sessionID === 'string' ? row.sessionID : '';
2101
2201
  const callID = typeof row.callID === 'string' ? row.callID : '';
@@ -2113,12 +2213,14 @@ const normalizeToolCall = (row) => {
2113
2213
  callID,
2114
2214
  tool,
2115
2215
  category: classifyToolCall({ tool, command: row.command }),
2216
+ intent: intentOf({ tool, command: row.command }),
2116
2217
  rawBytes,
2117
2218
  returnedBytes,
2118
2219
  keptOutBytes: Math.max(0, rawBytes - returnedBytes),
2119
2220
  replaced: booleanFlag(row.replaced),
2120
2221
  observedAt,
2121
2222
  day: observedAt.slice(0, 10),
2223
+ ...captureFields(row, onRefuse),
2122
2224
  };
2123
2225
  };
2124
2226
 
@@ -2148,14 +2250,22 @@ const normalizeUsageTurn = (row) => {
2148
2250
  observedAt,
2149
2251
  eventAt: null,
2150
2252
  day: observedAt.slice(0, 10),
2253
+ reasoningParts: countOrNull(row.reasoningParts),
2254
+ reasoningChars: countOrNull(row.reasoningChars),
2255
+ reasoningMs: countOrNull(row.reasoningMs),
2256
+ textChars: countOrNull(row.textChars),
2257
+ toolCalls: countOrNull(row.toolCalls),
2258
+ compactions: countOrNull(row.compactions),
2151
2259
  };
2152
2260
  };
2153
2261
 
2154
2262
  const UPSERT_TOOL_CALL_SQL = `
2155
2263
  INSERT INTO tool_calls (
2156
2264
  call_key, session_id, call_id, tool, category, raw_bytes, returned_bytes, kept_out_bytes,
2157
- replaced, origin, observed_at, day, task_slug, attribution
2158
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'measured', ?, ?, ?, ?)
2265
+ replaced, origin, observed_at, day, task_slug, attribution,
2266
+ intent, agent, parent_session_id, duration_ms, gap_ms, target_key, repeat_of, repeat_index,
2267
+ exit_code, error_class
2268
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'measured', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2159
2269
  ON CONFLICT(call_key) DO UPDATE SET
2160
2270
  session_id = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.session_id ELSE tool_calls.session_id END,
2161
2271
  call_id = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.call_id ELSE tool_calls.call_id END,
@@ -2165,6 +2275,16 @@ ON CONFLICT(call_key) DO UPDATE SET
2165
2275
  returned_bytes = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.returned_bytes ELSE tool_calls.returned_bytes END,
2166
2276
  kept_out_bytes = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.kept_out_bytes ELSE tool_calls.kept_out_bytes END,
2167
2277
  replaced = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.replaced ELSE tool_calls.replaced END,
2278
+ intent = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.intent ELSE tool_calls.intent END,
2279
+ agent = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.agent ELSE tool_calls.agent END,
2280
+ parent_session_id = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.parent_session_id ELSE tool_calls.parent_session_id END,
2281
+ duration_ms = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.duration_ms ELSE tool_calls.duration_ms END,
2282
+ gap_ms = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.gap_ms ELSE tool_calls.gap_ms END,
2283
+ target_key = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.target_key ELSE tool_calls.target_key END,
2284
+ repeat_of = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.repeat_of ELSE tool_calls.repeat_of END,
2285
+ repeat_index = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.repeat_index ELSE tool_calls.repeat_index END,
2286
+ exit_code = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.exit_code ELSE tool_calls.exit_code END,
2287
+ error_class = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.error_class ELSE tool_calls.error_class END,
2168
2288
  observed_at = MIN(tool_calls.observed_at, excluded.observed_at),
2169
2289
  day = MIN(tool_calls.day, excluded.day),
2170
2290
  task_slug = CASE WHEN excluded.observed_at < tool_calls.observed_at THEN excluded.task_slug ELSE tool_calls.task_slug END,
@@ -2175,8 +2295,9 @@ const UPSERT_USAGE_TURN_SQL = `
2175
2295
  INSERT INTO usage_turns (
2176
2296
  turn_key, session_id, message_id, agent, provider_id, model_id, model_variant,
2177
2297
  input_tokens, output_tokens, reasoning_tokens, cache_read_tokens, cache_write_tokens,
2178
- cost_usd, finish, origin, observed_at, event_at, day, task_slug, attribution
2179
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'measured', ?, ?, ?, ?, ?)
2298
+ cost_usd, finish, origin, observed_at, event_at, day, task_slug, attribution,
2299
+ reasoning_parts, reasoning_chars, reasoning_ms, text_chars, tool_calls, compactions
2300
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'measured', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2180
2301
  ON CONFLICT(turn_key) DO UPDATE SET
2181
2302
  session_id = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.session_id ELSE usage_turns.session_id END,
2182
2303
  message_id = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.message_id ELSE usage_turns.message_id END,
@@ -2191,6 +2312,12 @@ ON CONFLICT(turn_key) DO UPDATE SET
2191
2312
  cache_write_tokens = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.cache_write_tokens ELSE usage_turns.cache_write_tokens END,
2192
2313
  cost_usd = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.cost_usd ELSE usage_turns.cost_usd END,
2193
2314
  finish = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.finish ELSE usage_turns.finish END,
2315
+ reasoning_parts = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.reasoning_parts ELSE usage_turns.reasoning_parts END,
2316
+ reasoning_chars = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.reasoning_chars ELSE usage_turns.reasoning_chars END,
2317
+ reasoning_ms = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.reasoning_ms ELSE usage_turns.reasoning_ms END,
2318
+ text_chars = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.text_chars ELSE usage_turns.text_chars END,
2319
+ tool_calls = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.tool_calls ELSE usage_turns.tool_calls END,
2320
+ compactions = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.compactions ELSE usage_turns.compactions END,
2194
2321
  observed_at = MIN(usage_turns.observed_at, excluded.observed_at),
2195
2322
  day = MIN(usage_turns.day, excluded.day),
2196
2323
  task_slug = CASE WHEN excluded.observed_at < usage_turns.observed_at THEN excluded.task_slug ELSE usage_turns.task_slug END,
@@ -2235,34 +2362,97 @@ const projectSessionLeases = (db, teamRoot) => {
2235
2362
  const slug = typeof value.slug === 'string' ? value.slug : '';
2236
2363
  const at = isoTimestamp(value.updatedAt);
2237
2364
  if (sessionID === '' || slug === '' || at === null) continue;
2238
- statement.run(sessionID, slug, at, at);
2365
+ // A v5 lease carries one instant; the window then starts where it ends.
2366
+ const first = isoTimestamp(value.firstSeenAt) ?? at;
2367
+ statement.run(sessionID, slug, first < at ? first : at, at);
2239
2368
  projected += 1;
2240
2369
  }
2241
2370
  return projected;
2242
2371
  };
2243
2372
 
2373
+ /**
2374
+ * The attribution context: the lease windows of every session, the same
2375
+ * windows indexed by task, and the mtime of every task directory.
2376
+ *
2377
+ * A window is `[first, min(last + TTL, next lease first of that session))`, so
2378
+ * two leases of one session never claim the same instant and the later lease
2379
+ * owns the overlap.
2380
+ */
2244
2381
  const leaseWindows = (db) => {
2245
- const map = new Map();
2382
+ const bySession = new Map();
2383
+ const byTask = new Map();
2246
2384
  for (const row of db.prepare('SELECT session_id, task_slug, first_seen_at, last_seen_at FROM session_tasks').all()) {
2247
2385
  const first = Date.parse(row.first_seen_at);
2248
2386
  const last = Date.parse(row.last_seen_at);
2249
2387
  if (!Number.isFinite(first) || !Number.isFinite(last)) continue;
2250
- const list = map.get(row.session_id) ?? [];
2251
- list.push({ slug: row.task_slug, first, last });
2252
- map.set(row.session_id, list);
2388
+ const window = { slug: row.task_slug, first, last, end: last + LEASE_TTL_MS };
2389
+ const sessions = bySession.get(row.session_id) ?? [];
2390
+ sessions.push(window);
2391
+ bySession.set(row.session_id, sessions);
2392
+ const tasks = byTask.get(row.task_slug) ?? [];
2393
+ tasks.push(window);
2394
+ byTask.set(row.task_slug, tasks);
2395
+ }
2396
+ for (const sessions of bySession.values()) {
2397
+ sessions.sort((left, right) => left.first - right.first || (left.slug < right.slug ? -1 : left.slug > right.slug ? 1 : 0));
2398
+ for (let index = 0; index < sessions.length - 1; index += 1) {
2399
+ sessions[index].end = Math.min(sessions[index].end, sessions[index + 1].first);
2400
+ }
2401
+ }
2402
+ return { bySession, byTask };
2403
+ };
2404
+
2405
+ const taskDirectoryWindows = (teamRoot) => {
2406
+ const directory = path.join(teamRoot, 'tasks');
2407
+ let names;
2408
+ try {
2409
+ names = fs.readdirSync(directory).sort();
2410
+ } catch {
2411
+ return [];
2412
+ }
2413
+ const windows = [];
2414
+ for (const name of names) {
2415
+ try {
2416
+ const stats = fs.statSync(path.join(directory, name));
2417
+ if (stats.isDirectory()) windows.push({ slug: name, mtime: stats.mtimeMs });
2418
+ } catch {
2419
+ /* a directory that vanished between the read and the stat is no window */
2420
+ }
2253
2421
  }
2254
- return map;
2422
+ return windows;
2255
2423
  };
2256
2424
 
2257
- const resolveAttribution = (windows, sessionID, observedAt) => {
2258
- const list = windows.get(sessionID);
2425
+ /**
2426
+ * The ordered ladder `lease | window | dir-mtime | unmapped`. A `lease` hit is
2427
+ * final: a weaker rung never outranks it.
2428
+ */
2429
+ const resolveAttribution = (context, sessionID, observedAt) => {
2259
2430
  const at = Date.parse(observedAt);
2260
- if (!list || !Number.isFinite(at)) return { taskSlug: null, attribution: 'unmapped' };
2261
- let best = null;
2262
- for (const window of list) {
2263
- if (window.first <= at && at <= window.last && (!best || window.first >= best.first)) best = window;
2431
+ if (!Number.isFinite(at)) return { taskSlug: null, attribution: 'unmapped' };
2432
+ let lease = null;
2433
+ for (const window of context.bySession.get(sessionID) ?? []) {
2434
+ if (window.first <= at && at < window.end && (lease === null || window.first >= lease.first)) lease = window;
2435
+ }
2436
+ if (lease !== null) return { taskSlug: lease.slug, attribution: 'lease' };
2437
+ let taskLevel = null;
2438
+ for (const [slug, windows] of context.byTask) {
2439
+ for (const window of windows) {
2440
+ if (window.first <= at && at < window.end && (taskLevel === null || window.first > taskLevel.first)) {
2441
+ taskLevel = { slug, first: window.first };
2442
+ }
2443
+ }
2444
+ }
2445
+ if (taskLevel !== null) return { taskSlug: taskLevel.slug, attribution: 'window' };
2446
+ let nearest = null;
2447
+ for (const entry of context.dirs) {
2448
+ const distance = Math.abs(at - entry.mtime);
2449
+ if (distance > DIR_WINDOW_MS) continue;
2450
+ if (nearest === null || distance < nearest.distance || (distance === nearest.distance && entry.slug < nearest.slug)) {
2451
+ nearest = { slug: entry.slug, distance };
2452
+ }
2264
2453
  }
2265
- return best ? { taskSlug: best.slug, attribution: 'lease' } : { taskSlug: null, attribution: 'unmapped' };
2454
+ if (nearest !== null) return { taskSlug: nearest.slug, attribution: 'dir-mtime' };
2455
+ return { taskSlug: null, attribution: 'unmapped' };
2266
2456
  };
2267
2457
 
2268
2458
  const sourcePathFor = (teamRoot, file) => {
@@ -2286,7 +2476,7 @@ const listLedgerFiles = (directory, stem) => {
2286
2476
  });
2287
2477
  };
2288
2478
 
2289
- const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, windows, teamRoot }) => {
2479
+ const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, context, teamRoot }) => {
2290
2480
  let stats;
2291
2481
  try {
2292
2482
  stats = fs.statSync(file);
@@ -2314,6 +2504,7 @@ const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, windo
2314
2504
 
2315
2505
  const statement = db.prepare(kind === 'results' ? UPSERT_TOOL_CALL_SQL : UPSERT_USAGE_TURN_SQL);
2316
2506
  let invalid = 0;
2507
+ let refused = 0;
2317
2508
  let rows = 0;
2318
2509
  let lastKey = previous?.last_key ?? '';
2319
2510
  db.exec('BEGIN IMMEDIATE');
@@ -2335,13 +2526,13 @@ const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, windo
2335
2526
  lastKey = '';
2336
2527
  continue;
2337
2528
  }
2338
- const row = kind === 'results' ? normalizeToolCall(raw) : normalizeUsageTurn(raw);
2529
+ const row = kind === 'results' ? normalizeToolCall(raw, () => { refused += 1; }) : normalizeUsageTurn(raw);
2339
2530
  if (row === null) {
2340
2531
  invalid += 1;
2341
2532
  lastKey = '';
2342
2533
  continue;
2343
2534
  }
2344
- const { taskSlug, attribution } = resolveAttribution(windows, row.sessionID, row.observedAt);
2535
+ const { taskSlug, attribution } = resolveAttribution(context, row.sessionID, row.observedAt);
2345
2536
  if (kind === 'results') {
2346
2537
  statement.run(
2347
2538
  row.key,
@@ -2357,6 +2548,16 @@ const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, windo
2357
2548
  row.day,
2358
2549
  taskSlug,
2359
2550
  attribution,
2551
+ row.intent,
2552
+ row.agent,
2553
+ row.parentSessionId,
2554
+ row.durationMs,
2555
+ row.gapMs,
2556
+ row.targetKey,
2557
+ row.repeatOf,
2558
+ row.repeatIndex,
2559
+ row.exitCode,
2560
+ row.errorClass,
2360
2561
  );
2361
2562
  } else {
2362
2563
  statement.run(
@@ -2379,6 +2580,12 @@ const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, windo
2379
2580
  row.day,
2380
2581
  taskSlug,
2381
2582
  attribution,
2583
+ row.reasoningParts,
2584
+ row.reasoningChars,
2585
+ row.reasoningMs,
2586
+ row.textChars,
2587
+ row.toolCalls,
2588
+ row.compactions,
2382
2589
  );
2383
2590
  }
2384
2591
  rows += 1;
@@ -2394,7 +2601,7 @@ const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, windo
2394
2601
  }
2395
2602
  throw error;
2396
2603
  }
2397
- return { rows, invalid, ingested: true };
2604
+ return { rows, invalid, refused, ingested: true };
2398
2605
  };
2399
2606
 
2400
2607
  /**
@@ -2405,10 +2612,11 @@ const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, windo
2405
2612
  export function projectTelemetry({ db, teamRoot, now, deadlineAt = Number.POSITIVE_INFINITY, env = process.env }) {
2406
2613
  const ingestedAt = isoTimestamp(now) ?? new Date().toISOString();
2407
2614
  projectSessionLeases(db, teamRoot);
2408
- const windows = leaseWindows(db);
2615
+ const context = { ...leaseWindows(db), dirs: taskDirectoryWindows(teamRoot) };
2409
2616
  const directory = telemetryDirectory(teamRoot, env);
2410
2617
  let rows = 0;
2411
2618
  let invalid = 0;
2619
+ let refused = 0;
2412
2620
  let sources = 0;
2413
2621
  let expired = false;
2414
2622
  for (const [stem, kind, keyOf] of [
@@ -2420,14 +2628,20 @@ export function projectTelemetry({ db, teamRoot, now, deadlineAt = Number.POSITI
2420
2628
  expired = true;
2421
2629
  break;
2422
2630
  }
2423
- const outcome = ingestLedgerFile({ db, file, kind, keyOf, ingestedAt, deadlineAt, windows, teamRoot });
2631
+ const outcome = ingestLedgerFile({ db, file, kind, keyOf, ingestedAt, deadlineAt, context, teamRoot });
2424
2632
  rows += outcome.rows;
2425
2633
  invalid += outcome.invalid;
2634
+ refused += outcome.refused ?? 0;
2426
2635
  if (outcome.ingested) sources += 1;
2427
2636
  }
2428
2637
  if (expired) break;
2429
2638
  }
2430
- return { rows, invalid, sources, expired };
2639
+ // One line per run, never one per row: a refused value is dropped, and the
2640
+ // error log names the count without carrying the value.
2641
+ if (refused > 0) {
2642
+ logProjectionFailure('E_CAPTURE_REFUSED', `${refused} captured value(s) dropped as text, absolute or out of range`, env);
2643
+ }
2644
+ return { rows, invalid, refused, sources, expired };
2431
2645
  }
2432
2646
 
2433
2647
  const logProjectionFailure = (code, message, env = process.env) => {
@@ -711,8 +711,87 @@ CREATE TABLE context_cost_hosts (
711
711
  ) STRICT;
712
712
  `;
713
713
 
714
- const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
714
+ /**
715
+ * Migration 6: the action plane. Ten `tool_calls` columns, six `usage_turns`
716
+ * columns, one index and the two read-time views.
717
+ *
718
+ * Every column is nullable so a version-5 file migrates in place with no row
719
+ * copy. The views stay thin on purpose: a ratio whose denominator can be zero
720
+ * is left to the reader, because a threshold or a `NULLIF` literal in the view
721
+ * would need a new migration to recalibrate.
722
+ */
723
+ export const ACTION_TELEMETRY_SQL = SQL`-- The action row: identity, timing and outcome, no text and no absolute path.
724
+ ALTER TABLE tool_calls ADD COLUMN intent TEXT; -- explore|mutate|execute|delegate|ask|meta|web
725
+ ALTER TABLE tool_calls ADD COLUMN agent TEXT;
726
+ ALTER TABLE tool_calls ADD COLUMN parent_session_id TEXT;
727
+ ALTER TABLE tool_calls ADD COLUMN duration_ms INTEGER;
728
+ ALTER TABLE tool_calls ADD COLUMN gap_ms INTEGER;
729
+ ALTER TABLE tool_calls ADD COLUMN target_key TEXT; -- sha256 of the normalised target
730
+ ALTER TABLE tool_calls ADD COLUMN repeat_of TEXT; -- the call id of the first hit on the key
731
+ ALTER TABLE tool_calls ADD COLUMN repeat_index INTEGER;
732
+ ALTER TABLE tool_calls ADD COLUMN exit_code INTEGER;
733
+ ALTER TABLE tool_calls ADD COLUMN error_class TEXT; -- validation|notfound|permission|timeout|upstream
734
+
735
+ ALTER TABLE usage_turns ADD COLUMN reasoning_parts INTEGER;
736
+ ALTER TABLE usage_turns ADD COLUMN reasoning_chars INTEGER;
737
+ ALTER TABLE usage_turns ADD COLUMN reasoning_ms INTEGER;
738
+ ALTER TABLE usage_turns ADD COLUMN text_chars INTEGER;
739
+ ALTER TABLE usage_turns ADD COLUMN tool_calls INTEGER;
740
+ ALTER TABLE usage_turns ADD COLUMN compactions INTEGER;
741
+
742
+ CREATE INDEX idx_tool_calls_task_observed ON tool_calls(task_slug, observed_at);
743
+
744
+ -- One row per task with actions. Counts, numerators and the two window edges;
745
+ -- every ratio is derived by the reader (D-6).
746
+ CREATE VIEW task_action_summary AS
747
+ SELECT
748
+ c.task_slug,
749
+ count(*) AS actions,
750
+ COALESCE(SUM(CASE WHEN c.intent = 'explore' THEN 1 ELSE 0 END), 0) AS explore,
751
+ COALESCE(SUM(CASE WHEN c.intent = 'mutate' THEN 1 ELSE 0 END), 0) AS mutate,
752
+ COALESCE(SUM(CASE WHEN c.intent = 'execute' THEN 1 ELSE 0 END), 0) AS execute,
753
+ COALESCE(SUM(CASE WHEN c.intent = 'delegate' THEN 1 ELSE 0 END), 0) AS delegate,
754
+ COALESCE(SUM(CASE WHEN c.intent = 'ask' THEN 1 ELSE 0 END), 0) AS ask,
755
+ COALESCE(SUM(CASE WHEN c.intent = 'meta' THEN 1 ELSE 0 END), 0) AS meta,
756
+ COALESCE(SUM(CASE WHEN c.intent = 'web' THEN 1 ELSE 0 END), 0) AS web,
757
+ COALESCE(SUM(CASE WHEN c.error_class IS NOT NULL THEN 1 ELSE 0 END), 0) AS error_actions,
758
+ COALESCE(SUM(CASE WHEN c.repeat_index IS NOT NULL THEN 1 ELSE 0 END), 0) AS repeat_actions,
759
+ COALESCE(SUM(c.replaced), 0) AS guard_hits,
760
+ COALESCE(SUM(CASE WHEN c.duration_ms IS NOT NULL THEN c.duration_ms ELSE 0 END), 0) AS busy_ms,
761
+ COALESCE(SUM(CASE WHEN c.duration_ms IS NOT NULL THEN 1 ELSE 0 END), 0) AS measured_actions,
762
+ COUNT(DISTINCT CASE WHEN c.intent = 'mutate' THEN c.target_key END) AS changed_files,
763
+ MIN(c.observed_at) AS first_at,
764
+ MAX(c.observed_at) AS last_at,
765
+ COALESCE(SUM(CASE WHEN c.attribution = 'lease' THEN 1 ELSE 0 END), 0) AS rung_lease,
766
+ COALESCE(SUM(CASE WHEN c.attribution = 'window' THEN 1 ELSE 0 END), 0) AS rung_window,
767
+ COALESCE(SUM(CASE WHEN c.attribution = 'dir-mtime' THEN 1 ELSE 0 END), 0) AS rung_dir_mtime,
768
+ COALESCE(SUM(CASE WHEN c.attribution = 'unmapped' THEN 1 ELSE 0 END), 0) AS rung_unmapped,
769
+ (SELECT count(*) FROM usage_turns u WHERE u.task_slug = c.task_slug) AS turns,
770
+ (SELECT COALESCE(SUM(u.input_tokens + u.output_tokens + u.reasoning_tokens), 0)
771
+ FROM usage_turns u WHERE u.task_slug = c.task_slug) AS tokens,
772
+ (SELECT COALESCE(SUM(u.reasoning_parts), 0) FROM usage_turns u WHERE u.task_slug = c.task_slug) AS reasoning_parts,
773
+ (SELECT COALESCE(SUM(u.compactions), 0) FROM usage_turns u WHERE u.task_slug = c.task_slug) AS compactions,
774
+ (SELECT COALESCE(SUM(u.tool_calls), 0) FROM usage_turns u WHERE u.task_slug = c.task_slug) AS turn_tool_calls
775
+ FROM tool_calls c
776
+ WHERE c.task_slug IS NOT NULL AND c.task_slug <> ''
777
+ GROUP BY c.task_slug;
778
+
779
+ -- One row per signal with a non-zero numerator. No threshold, no severity and no
780
+ -- rule text live here: the reader pins all three, so recalibrating a signal is a
781
+ -- code change with no migration and no backfill.
782
+ CREATE VIEW action_signals AS
783
+ SELECT task_slug, signal, value FROM (
784
+ SELECT task_slug, 'error_rate' AS signal, error_actions AS value FROM task_action_summary
785
+ UNION ALL SELECT task_slug, 'repeat_churn', repeat_actions FROM task_action_summary
786
+ UNION ALL SELECT task_slug, 'guard_pressure', guard_hits FROM task_action_summary
787
+ UNION ALL SELECT task_slug, 'context_thrash', compactions FROM task_action_summary
788
+ UNION ALL SELECT task_slug, 'weak_attribution', rung_window + rung_dir_mtime FROM task_action_summary
789
+ UNION ALL SELECT task_slug, 'noop_actions', CASE WHEN changed_files = 0 THEN actions ELSE 0 END FROM task_action_summary
790
+ UNION ALL SELECT task_slug, 'explore_without_mutate', CASE WHEN mutate = 0 THEN explore ELSE 0 END FROM task_action_summary
791
+ ) WHERE value > 0;
792
+ `;
715
793
 
794
+ const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
716
795
  /**
717
796
  * Ordered, immutable migrations. The literal checksum is verified before any
718
797
  * DDL runs; a mismatch means the SQL changed without a new migration.
@@ -748,6 +827,12 @@ export const MIGRATIONS = [
748
827
  sql: EFFICIENCY_SQL,
749
828
  checksum: '7ae3d8509a88c77bc0ed225601b83d9a0a26748551b3e420167ea6d038ec14b1',
750
829
  },
830
+ {
831
+ version: 6,
832
+ name: '0006-action-telemetry',
833
+ sql: ACTION_TELEMETRY_SQL,
834
+ checksum: 'f250814d462f1d6085ff56a1cc233179002dd5b5d97c200ed28104e4e42fbbfe',
835
+ },
751
836
  ];
752
837
 
753
838
  /** Highest migration version shipped by this module. */
@@ -59,12 +59,26 @@ function readSessionLease(id) {
59
59
  return null;
60
60
  }
61
61
  }
62
+ // The lease carries the window the projector attributes rows with — never one
63
+ // instant. `firstSeenAt` survives every later write of the same (session, slug)
64
+ // pair; a different slug starts a new window, and a lease older than the TTL
65
+ // starts over instead of claiming an ancient first sighting.
66
+ function firstSeenAtOf(file, value, now) {
67
+ try {
68
+ if (Date.now() - fs.statSync(file).mtimeMs > LEASE_TTL_MS) return now;
69
+ const previous = JSON.parse(fs.readFileSync(file, 'utf8'));
70
+ if (previous && previous.slug === value && typeof previous.firstSeenAt === 'string') return previous.firstSeenAt;
71
+ } catch {}
72
+ return now;
73
+ }
62
74
  function writeSessionLease(id, value) {
63
75
  try {
64
76
  fs.mkdirSync(LEASE_ROOT, { recursive: true });
65
77
  const file = sessionLeasePath(id);
66
78
  const temporary = `${file}.${process.pid}.tmp`;
67
- fs.writeFileSync(temporary, `${JSON.stringify({ slug: value, sessionId: id, updatedAt: new Date().toISOString() })}\n`);
79
+ const now = new Date().toISOString();
80
+ const firstSeenAt = firstSeenAtOf(file, value, now);
81
+ fs.writeFileSync(temporary, `${JSON.stringify({ slug: value, sessionId: id, firstSeenAt, updatedAt: now })}\n`);
68
82
  fs.renameSync(temporary, file);
69
83
  for (const name of fs.readdirSync(LEASE_ROOT)) {
70
84
  if (!name.endsWith('.json')) continue;
@@ -49,3 +49,7 @@ Slash commands are copied to `.claude/commands/` on `ai-rules init claude --pres
49
49
  - Hooks: `../hooks/chain-team-phases.sh` (no `hooks.json` on Claude)
50
50
 
51
51
  Create and edit commands in this preset folder (Claude Code slash commands).
52
+
53
+ ## Scheduler
54
+
55
+ - **`/rr-scheduler-start`** — start the team-db scheduler, or restart it when one already holds the lease. `init` seeds `.ai.local/scripts/rr-scheduler-start.mjs`.
@@ -0,0 +1,32 @@
1
+ ---
2
+ name: rr-scheduler-start
3
+ description: Start the team-db scheduler, or restart it when one is already running.
4
+ ---
5
+
6
+ # Start or restart the scheduler
7
+
8
+ Bring up `team-db.mjs schedule` for this repository. When a scheduler already holds the lease, stop that process and start a new one.
9
+
10
+ ## What to do
11
+
12
+ 1. From the repository root, run:
13
+
14
+ ```bash
15
+ node .ai.local/scripts/rr-scheduler-start.mjs
16
+ ```
17
+
18
+ 2. Quote the stdout verbatim. A start prints `scheduler: started pid <pid>`. A restart prints `scheduler: restarted pid <pid> (stopped <previous>)`, plus the `processes:` lines from the manager.
19
+ 3. On a non-zero exit, quote the `error:` line verbatim and stop. Do not start `team-db.mjs schedule` by hand and do not signal a pid the script did not name.
20
+
21
+ ## What the script does
22
+
23
+ - Stops a scheduler this repository recorded, via `processes.mjs stop --name scheduler`.
24
+ - Signals a scheduler that was started outside the manager only when `scheduler.lock` names a live pid whose command line is `team-db.mjs schedule`. `SIGTERM`, then `SIGKILL` if it is still alive after 8 seconds. An in-flight child can outlive that kill.
25
+ - Removes `scheduler.lock` when its pid is already dead, so a crash does not block the next start for 90 seconds.
26
+ - Starts the timer through `processes.mjs start --name scheduler` with `exec node .ai.local/scripts/team-db.mjs schedule`, then waits until the new lease is fresh.
27
+
28
+ ## Do not
29
+
30
+ - Write `status.json`, `metrics.json`, or any task or lifecycle file.
31
+ - Run `pkill`, `killall`, or `kill` against a pid the script did not print.
32
+ - Start a second `team-db.mjs schedule` after a non-zero exit.
@@ -75,12 +75,26 @@ function readSessionLease(id) {
75
75
  return null;
76
76
  }
77
77
  }
78
+ // The lease carries the window the projector attributes rows with — never one
79
+ // instant. `firstSeenAt` survives every later write of the same (session, slug)
80
+ // pair; a different slug starts a new window, and a lease older than the TTL
81
+ // starts over instead of claiming an ancient first sighting.
82
+ function firstSeenAtOf(file, value, now) {
83
+ try {
84
+ if (Date.now() - fs.statSync(file).mtimeMs > LEASE_TTL_MS) return now;
85
+ const previous = JSON.parse(fs.readFileSync(file, 'utf8'));
86
+ if (previous && previous.slug === value && typeof previous.firstSeenAt === 'string') return previous.firstSeenAt;
87
+ } catch {}
88
+ return now;
89
+ }
78
90
  function writeSessionLease(id, value) {
79
91
  try {
80
92
  fs.mkdirSync(LEASE_ROOT, { recursive: true });
81
93
  const file = sessionLeasePath(id);
82
94
  const temporary = `${file}.${process.pid}.tmp`;
83
- fs.writeFileSync(temporary, `${JSON.stringify({ slug: value, sessionId: id, updatedAt: new Date().toISOString() })}\n`);
95
+ const now = new Date().toISOString();
96
+ const firstSeenAt = firstSeenAtOf(file, value, now);
97
+ fs.writeFileSync(temporary, `${JSON.stringify({ slug: value, sessionId: id, firstSeenAt, updatedAt: now })}\n`);
84
98
  fs.renameSync(temporary, file);
85
99
  for (const name of fs.readdirSync(LEASE_ROOT)) {
86
100
  if (!name.endsWith('.json')) continue;
@@ -11,3 +11,7 @@ Slash-command and on-demand scenario definitions. Copied to `.claude/commands/`
11
11
  | `migrate-tasks.md` | Create or reconcile `.ai.local/team/team.db`; writes only the delta |
12
12
 
13
13
  See also the preset root `README.md`. Artifacts: `.ai.local/team/README.md`.
14
+
15
+ ## Scheduler
16
+
17
+ - **`/rr-scheduler-start`** — start the team-db scheduler, or restart it when one already holds the lease. `init` seeds `.ai.local/scripts/rr-scheduler-start.mjs`.