@bonesofspring/ai-rules 0.2.91 → 0.2.92

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 (99) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/docs/TEAM-DB.md +2 -0
  3. package/package.json +1 -1
  4. package/presets/_shared/ai-local/scripts/team-db-api.mjs +33 -15
  5. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +15 -0
  6. package/presets/_shared/ai-local/scripts/team-db-project.mjs +41 -2
  7. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +23 -0
  8. package/presets/_shared/core/agent-team/agent-task-metrics.md +16 -1
  9. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +87 -6
  10. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +87 -6
  11. package/presets/claude/go/hooks/chain-team-phases.sh +87 -6
  12. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +87 -6
  13. package/presets/claude/java/hooks/chain-team-phases.sh +87 -6
  14. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +87 -6
  15. package/presets/claude/mol/hooks/chain-team-phases.sh +87 -6
  16. package/presets/claude/next/hooks/chain-team-phases.sh +87 -6
  17. package/presets/claude/nuxt/hooks/chain-team-phases.sh +87 -6
  18. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  19. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +87 -6
  20. package/presets/claude/svelte/hooks/chain-team-phases.sh +87 -6
  21. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +87 -6
  22. package/presets/cursor/go/hooks/chain-team-phases.sh +87 -6
  23. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +87 -6
  24. package/presets/cursor/java/hooks/chain-team-phases.sh +87 -6
  25. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +87 -6
  26. package/presets/cursor/mol/hooks/chain-team-phases.sh +87 -6
  27. package/presets/cursor/next/hooks/chain-team-phases.sh +87 -6
  28. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +87 -6
  29. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  30. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +87 -6
  31. package/presets/cursor/svelte/hooks/chain-team-phases.sh +87 -6
  32. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  33. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +87 -6
  34. package/presets/mavis/go/adapter-map.json +1 -1
  35. package/presets/mavis/go/hooks/chain-team-phases.sh +87 -6
  36. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  37. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +87 -6
  38. package/presets/mavis/java/adapter-map.json +1 -1
  39. package/presets/mavis/java/hooks/chain-team-phases.sh +87 -6
  40. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  41. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +87 -6
  42. package/presets/mavis/mol/adapter-map.json +1 -1
  43. package/presets/mavis/mol/hooks/chain-team-phases.sh +87 -6
  44. package/presets/mavis/next/adapter-map.json +1 -1
  45. package/presets/mavis/next/hooks/chain-team-phases.sh +87 -6
  46. package/presets/mavis/nuxt/adapter-map.json +1 -1
  47. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +87 -6
  48. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  49. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  50. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  51. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +87 -6
  52. package/presets/mavis/svelte/adapter-map.json +1 -1
  53. package/presets/mavis/svelte/hooks/chain-team-phases.sh +87 -6
  54. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  55. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +87 -6
  56. package/presets/opencode/go/adapter-map.json +1 -1
  57. package/presets/opencode/go/hooks/chain-team-phases.sh +87 -6
  58. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  59. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +87 -6
  60. package/presets/opencode/java/adapter-map.json +1 -1
  61. package/presets/opencode/java/hooks/chain-team-phases.sh +87 -6
  62. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  63. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +87 -6
  64. package/presets/opencode/mol/adapter-map.json +1 -1
  65. package/presets/opencode/mol/hooks/chain-team-phases.sh +87 -6
  66. package/presets/opencode/next/adapter-map.json +1 -1
  67. package/presets/opencode/next/hooks/chain-team-phases.sh +87 -6
  68. package/presets/opencode/nuxt/adapter-map.json +1 -1
  69. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +87 -6
  70. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  71. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  72. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  73. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +87 -6
  74. package/presets/opencode/plugins/task-status/README.md +2 -2
  75. package/presets/opencode/plugins/task-status/deepseek.ts +8 -4
  76. package/presets/opencode/svelte/adapter-map.json +1 -1
  77. package/presets/opencode/svelte/hooks/chain-team-phases.sh +87 -6
  78. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  79. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +87 -6
  80. package/presets/zcode/go/adapter-map.json +1 -1
  81. package/presets/zcode/go/hooks/chain-team-phases.sh +87 -6
  82. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  83. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +87 -6
  84. package/presets/zcode/java/adapter-map.json +1 -1
  85. package/presets/zcode/java/hooks/chain-team-phases.sh +87 -6
  86. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  87. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +87 -6
  88. package/presets/zcode/mol/adapter-map.json +1 -1
  89. package/presets/zcode/mol/hooks/chain-team-phases.sh +87 -6
  90. package/presets/zcode/next/adapter-map.json +1 -1
  91. package/presets/zcode/next/hooks/chain-team-phases.sh +87 -6
  92. package/presets/zcode/nuxt/adapter-map.json +1 -1
  93. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +87 -6
  94. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  95. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  96. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  97. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +87 -6
  98. package/presets/zcode/svelte/adapter-map.json +1 -1
  99. package/presets/zcode/svelte/hooks/chain-team-phases.sh +87 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.92
4
+
5
+ Records commit `56e612ba` after `## 0.2.91`.
6
+
7
+ ### Attempt records the tool and the model
8
+
9
+ - **Per attempt, not per task.** `attempt_started.tool` is the hook that armed the step and `attempt_finished.tool` is the hook that closed it. `metrics.task.platform` stays the bootstrap tool when the task continues in another host.
10
+ - **Model without tokens.** The hook writes `model`, `modelTier`, and `modelSource` (`host`, `lease`, `tier-map`, `session`). A session lease model is used only when `lease.tool` matches the running hook. An empty tier map does not invent an id.
11
+ - **The lease keeps its model.** `writeSessionLease` stores `tool` and carries a previous model forward only for the same slug and the same tool, so a lease written by another host does not lend its model.
12
+ - **Out-of-band events carry the same fields.** `out_of_band_started` and `out_of_band_finished` write `tool`, `modelTier`, `model`, and `modelSource` next to the step and agent they already had.
13
+ - **The projector copies them.** `team-db-project.mjs` keeps `tool` only from the five platforms and `modelTier` only from `cheap` / `standard` / `strong`, and drops an id that is not a bounded slug. `attempt_started` fills `started_tool`, `attempt_finished` fills `finished_tool`, and the status file fills a missing tool, tier, or model from the current step.
14
+ - **The API prefers an observed model.** `host` and `lease` beat the usage rollup (`model_provider` / `model_id`), which beats `tier-map`. `modelSource` names the source that won, and an execution model survives a usage row with no id.
15
+ - **Migration `0012-attempt-execution`.** `attempts` gains `started_tool`, `finished_tool`, `model_tier`, `execution_model`, and `model_source`. Token rollup stays on `model_provider` / `model_id`.
16
+ - **Rule.** `agent-task-metrics.md` gains "Execution provenance": the allowlisted values, which event writes them, and the resolution order.
17
+
18
+ ### Task detail shows the tool and the model
19
+
20
+ - **Two columns.** `ATTEMPT_COLUMNS` gains Tool and Model. A cross-host attempt reads `cursor → opencode`, and a missing finish tool shows the start tool alone.
21
+ - **Contract fields.** `AttemptDto`, `TTaskAttempt`, the mapper, the contract example, and the OpenAPI `Attempt` schema carry `startedTool`, `finishedTool`, `modelTier`, `model`, and `modelSource`.
22
+
23
+ ### Billing rows only for DeepSeek and Z.AI
24
+
25
+ - **Peak rows only for DeepSeek and Z.AI.** The two are the only providers with a published peak schedule, so `billingRates` drops every other store provider instead of showing a permanent `[off-peak]` row for it. The plugin README and `test-task-status-view.mjs` case 35c follow.
26
+
27
+ ### Tests, docs, and regenerated trees
28
+
29
+ - **`test-attempt-execution.mjs`.** New suite: a per-platform hook render writes the tool on both events, the lease model crosses steps but not hosts, the tier map resolves the step's tier when the map names it, and the projector and the API choose the same model.
30
+ - **Schema suite expects v12.** `test-team-db-schema.mjs` moves `SCHEMA_VERSION`, the migration count, and the upgrade fixtures to 12 and checks the five new columns.
31
+ - **`TEAM-DB.md`.** Migration 0012 is additive: a v11 file migrates in place and historical rows stay NULL. `execution_model` is the id named for the attempt; `model_provider` / `model_id` remain the usage rollup.
32
+ - **Preset installs and goldens.** The five native trees, every `adapter-map.json` source revision, and the CLI goldens are regenerated from the new source.
33
+
3
34
  ## 0.2.91
4
35
 
5
36
  Records commit `9a558699` after `## 0.2.90`.
package/docs/TEAM-DB.md CHANGED
@@ -732,6 +732,8 @@ review produces — and relays `failures[].reason` verbatim, so the message text
732
732
  write a reviewer's row. A tree without the CLI or without a ledger skips the gate and says so
733
733
  on stderr.
734
734
 
735
+ Migration `0012-attempt-execution` moves `SCHEMA_VERSION` to 12. It is additive: `attempts` gains `started_tool`, `finished_tool`, `model_tier`, `execution_model`, and `model_source`, all nullable. A v11 file migrates in place and historical rows stay NULL. `execution_model` is the id named for the attempt even when no token usage was reported; `model_provider` / `model_id` remain the usage rollup. The files stay authoritative: the chain hook writes the fields on `attempt_started` and `attempt_finished`, and the projector copies them.
736
+
735
737
  `serve` and `schedule` keep the schema module they loaded at startup. When `team-db-schema.mjs`
736
738
  on disk is replaced by a higher `SCHEMA_VERSION`, the next request and the next idle scheduler
737
739
  tick re-import that file and open with it. A database newer than the file on disk still fails
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bonesofspring/ai-rules",
3
- "version": "0.2.91",
3
+ "version": "0.2.92",
4
4
  "description": "Presets of Cursor, Claude, Mavis, OpenCode, and ZCode rules/commands for Revy Ross personal use",
5
5
  "license": "MIT",
6
6
  "author": "Revy Ross",
@@ -911,21 +911,39 @@ const getPipeline = (db, slug) => {
911
911
  };
912
912
  };
913
913
 
914
- const attemptRow = (row) => ({
915
- attemptId: row.attempt_id,
916
- agent: row.agent ?? null,
917
- role: row.role ?? null,
918
- stepIndex: row.step_index ?? null,
919
- stepLabel: row.step_label ?? null,
920
- attempt: row.attempt_no ?? null,
921
- startedAt: row.started_at ?? null,
922
- finishedAt: row.finished_at ?? null,
923
- durationMs: row.duration_ms ?? null,
924
- outcome: row.outcome ?? null,
925
- source: row.source ?? null,
926
- attributionConfidence: row.attribution_confidence ?? null,
927
- current: row.is_current === 1,
928
- });
914
+ const usageModelOf = (row) => {
915
+ if (typeof row.model_id !== 'string' || row.model_id === '') return null;
916
+ return typeof row.model_provider === 'string' && row.model_provider !== ''
917
+ ? `${row.model_provider}/${row.model_id}`
918
+ : row.model_id;
919
+ };
920
+
921
+ const attemptRow = (row) => {
922
+ const executionModel = typeof row.execution_model === 'string' && row.execution_model !== '' ? row.execution_model : null;
923
+ const usageModel = usageModelOf(row);
924
+ const observed = row.model_source === 'host' || row.model_source === 'lease';
925
+ const preferUsage = Boolean(usageModel) && !observed;
926
+ return {
927
+ attemptId: row.attempt_id,
928
+ agent: row.agent ?? null,
929
+ role: row.role ?? null,
930
+ stepIndex: row.step_index ?? null,
931
+ stepLabel: row.step_label ?? null,
932
+ attempt: row.attempt_no ?? null,
933
+ startedAt: row.started_at ?? null,
934
+ finishedAt: row.finished_at ?? null,
935
+ durationMs: row.duration_ms ?? null,
936
+ outcome: row.outcome ?? null,
937
+ source: row.source ?? null,
938
+ attributionConfidence: row.attribution_confidence ?? null,
939
+ current: row.is_current === 1,
940
+ startedTool: row.started_tool ?? null,
941
+ finishedTool: row.finished_tool ?? null,
942
+ modelTier: row.model_tier ?? null,
943
+ model: preferUsage ? usageModel : (executionModel ?? usageModel),
944
+ modelSource: preferUsage ? (row.usage_source ?? null) : (executionModel ? (row.model_source ?? null) : (usageModel ? (row.usage_source ?? null) : null)),
945
+ };
946
+ };
929
947
 
930
948
  const listAttempts = (db, slug, query) => {
931
949
  requireTask(db, slug);
@@ -349,6 +349,11 @@ const schemas = {
349
349
  source: nullable('string'),
350
350
  attributionConfidence: nullable('string'),
351
351
  current: { type: 'boolean' },
352
+ startedTool: nullable('string'),
353
+ finishedTool: nullable('string'),
354
+ modelTier: nullable('string'),
355
+ model: nullable('string'),
356
+ modelSource: nullable('string'),
352
357
  },
353
358
  [
354
359
  'attemptId',
@@ -364,6 +369,11 @@ const schemas = {
364
369
  'source',
365
370
  'attributionConfidence',
366
371
  'current',
372
+ 'startedTool',
373
+ 'finishedTool',
374
+ 'modelTier',
375
+ 'model',
376
+ 'modelSource',
367
377
  ],
368
378
  ),
369
379
  AttemptList: object(
@@ -2136,6 +2146,11 @@ const attemptExample = {
2136
2146
  source: 'hook',
2137
2147
  attributionConfidence: 'high',
2138
2148
  current: false,
2149
+ startedTool: 'cursor',
2150
+ finishedTool: 'opencode',
2151
+ modelTier: 'strong',
2152
+ model: 'deepseek/deepseek-v4-pro',
2153
+ modelSource: 'host',
2139
2154
  };
2140
2155
 
2141
2156
  const eventExample = {
@@ -1024,6 +1024,11 @@ const normalizeEvent = (event, index, slug) => {
1024
1024
  source: typeof event.source === 'string' ? event.source : null,
1025
1025
  attributionConfidence:
1026
1026
  typeof event.attributionConfidence === 'string' ? event.attributionConfidence : null,
1027
+ tool: EXECUTION_TOOLS.has(event.tool) ? event.tool : null,
1028
+ modelTier: MODEL_TIERS.has(event.modelTier) ? event.modelTier : null,
1029
+ executionModel: executionModelOf(event.model),
1030
+ modelSource:
1031
+ executionModelOf(event.model) && MODEL_SOURCES.has(event.modelSource) ? event.modelSource : null,
1027
1032
  usage: isRecord(event.usage) ? event.usage : null,
1028
1033
  usageEvent:
1029
1034
  type === 'usage_recorded'
@@ -1044,6 +1049,13 @@ const normalizeEvent = (event, index, slug) => {
1044
1049
  };
1045
1050
  };
1046
1051
 
1052
+ const EXECUTION_TOOLS = new Set(['cursor', 'claude', 'mavis', 'opencode', 'zcode']);
1053
+ const MODEL_TIERS = new Set(['cheap', 'standard', 'strong']);
1054
+ const MODEL_SOURCES = new Set(['host', 'lease', 'tier-map', 'session']);
1055
+
1056
+ const executionModelOf = (value) =>
1057
+ typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(value) ? value : null;
1058
+
1047
1059
  const attemptSuffix = (attemptId) => {
1048
1060
  const match = /:attempt-(\d+)$/.exec(attemptId || '');
1049
1061
  return match ? Number(match[1]) : null;
@@ -1243,6 +1255,11 @@ export function deriveAttempts(events, status) {
1243
1255
  source: 'metrics',
1244
1256
  attributionConfidence: null,
1245
1257
  isCurrent: 0,
1258
+ startedTool: null,
1259
+ finishedTool: null,
1260
+ modelTier: null,
1261
+ executionModel: null,
1262
+ modelSource: null,
1246
1263
  });
1247
1264
  }
1248
1265
  return attempts.get(attemptId);
@@ -1259,12 +1276,19 @@ export function deriveAttempts(events, status) {
1259
1276
  row.parallelGroupId = event.parallelGroupId ?? row.parallelGroupId;
1260
1277
  row.source = event.source ?? row.source;
1261
1278
  row.attributionConfidence = event.attributionConfidence ?? row.attributionConfidence;
1279
+ if (event.modelTier) row.modelTier = event.modelTier;
1280
+ if (event.executionModel) {
1281
+ row.executionModel = event.executionModel;
1282
+ row.modelSource = event.modelSource;
1283
+ }
1262
1284
  if (event.type === 'attempt_started') {
1263
1285
  row.startedAt = event.at ?? row.startedAt;
1286
+ if (event.tool) row.startedTool = event.tool;
1264
1287
  } else if (event.type === 'attempt_finished') {
1265
1288
  row.finishedAt = event.at ?? row.finishedAt;
1266
1289
  row.durationMs = event.durationMs ?? row.durationMs;
1267
1290
  row.outcome = event.outcome ?? row.outcome;
1291
+ if (event.tool) row.finishedTool = event.tool;
1268
1292
  if (isRecord(event.usage)) hostUsage.set(event.attemptId, event.usage);
1269
1293
  } else if (event.type === 'attempt_skipped') {
1270
1294
  row.outcome = 'skipped';
@@ -1285,6 +1309,15 @@ export function deriveAttempts(events, status) {
1285
1309
  row.waveId = typeof value.waveId === 'string' ? value.waveId : row.waveId;
1286
1310
  row.parallelGroupId = typeof value.parallelGroupId === 'string' ? value.parallelGroupId : row.parallelGroupId;
1287
1311
  row.startedAt = isoTimestamp(value.startedAt) ?? row.startedAt;
1312
+ if (!row.startedTool && EXECUTION_TOOLS.has(value.tool)) row.startedTool = value.tool;
1313
+ if (!row.modelTier && MODEL_TIERS.has(value.modelTier)) row.modelTier = value.modelTier;
1314
+ if (!row.executionModel) {
1315
+ const model = executionModelOf(value.model);
1316
+ if (model) {
1317
+ row.executionModel = model;
1318
+ row.modelSource = MODEL_SOURCES.has(value.modelSource) ? value.modelSource : null;
1319
+ }
1320
+ }
1288
1321
  row.source = row.startedAt && !row.finishedAt ? 'status' : row.source;
1289
1322
  }
1290
1323
  for (const row of attempts.values()) {
@@ -1588,8 +1621,9 @@ const replaceAttempts = (db, slug, attempts) => {
1588
1621
  parallel_group_id, started_at, finished_at, duration_ms, outcome, source,
1589
1622
  attribution_confidence, is_current, input_tokens, output_tokens, reasoning_tokens,
1590
1623
  cache_read_tokens, cache_write_tokens, cost_usd, usage_origin, usage_source,
1591
- usage_turn_count, model_provider, model_id
1592
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1624
+ usage_turn_count, model_provider, model_id, started_tool, finished_tool,
1625
+ model_tier, execution_model, model_source
1626
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1593
1627
  );
1594
1628
  for (const attempt of attempts) {
1595
1629
  statement.run(
@@ -1620,6 +1654,11 @@ const replaceAttempts = (db, slug, attempts) => {
1620
1654
  attempt.usageTurnCount,
1621
1655
  attempt.modelProvider,
1622
1656
  attempt.modelId,
1657
+ attempt.startedTool,
1658
+ attempt.finishedTool,
1659
+ attempt.modelTier,
1660
+ attempt.executionModel,
1661
+ attempt.modelSource,
1623
1662
  );
1624
1663
  }
1625
1664
  };
@@ -966,6 +966,23 @@ CREATE INDEX idx_projects_status_name ON projects(status, name COLLATE NOCASE);
966
966
  CREATE INDEX idx_project_repositories_repository ON project_repositories(repository_id);
967
967
  `;
968
968
 
969
+ /**
970
+ * Migration 12: which tool armed and closed an attempt, and which model was
971
+ * named for it. Nullable, so a version-11 file migrates in place. Token
972
+ * rollup stays on model_provider / model_id; execution_model is the armed id
973
+ * even when no usage was reported.
974
+ */
975
+ export const ATTEMPT_EXECUTION_SQL = SQL`ALTER TABLE attempts ADD COLUMN started_tool TEXT;
976
+
977
+ ALTER TABLE attempts ADD COLUMN finished_tool TEXT;
978
+
979
+ ALTER TABLE attempts ADD COLUMN model_tier TEXT;
980
+
981
+ ALTER TABLE attempts ADD COLUMN execution_model TEXT;
982
+
983
+ ALTER TABLE attempts ADD COLUMN model_source TEXT;
984
+ `;
985
+
969
986
  const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
970
987
  /**
971
988
  * Ordered, immutable migrations. The literal checksum is verified before any
@@ -1038,6 +1055,12 @@ export const MIGRATIONS = [
1038
1055
  sql: PROJECT_REGISTRY_SQL,
1039
1056
  checksum: '46ff23b832f6d4b7891e90c119173b5f5f533ffa4b47dc43ebf6a605de812779',
1040
1057
  },
1058
+ {
1059
+ version: 12,
1060
+ name: '0012-attempt-execution',
1061
+ sql: ATTEMPT_EXECUTION_SQL,
1062
+ checksum: '161f913d7b70f68033a073bd894a295369fe36d76616bd1abcdbae47661bfb9d',
1063
+ },
1041
1064
  ];
1042
1065
 
1043
1066
  /** Highest migration version shipped by this module. */
@@ -14,7 +14,7 @@ Each pipeline run owns `<team>/tasks/<slug>/metrics.json`:
14
14
  }
15
15
  ```
16
16
 
17
- `events` is append-only. A task is one `runId`; a subtask is one invocation of `pipeline.steps[i]`. Every invocation has an `attemptId`, including each member of a parallel step. Events inherit the immutable task dimensions rather than duplicating them.
17
+ `events` is append-only. A task is one `runId`; a subtask is one invocation of `pipeline.steps[i]`. Every invocation has an `attemptId`, including each member of a parallel step. Events inherit the immutable task dimensions rather than duplicating them. `task.platform` is the tool that bootstrapped the ledger. A continuation in another tool does not rewrite it.
18
18
 
19
19
  Allowed event types are `task_started`, `attempt_started`, `attempt_finished`, `retry_scheduled`, `attempt_skipped`, `human_gate_started`, `human_gate_ended`, `pipeline_parse_error`, `task_completed`, `profile_changed`, `out_of_band_started`, `out_of_band_finished`, `usage_recorded`, `verification_recorded`, `verification_stale`, and the parallel events `parallel_wave_started`, `step_joined`, `parallel_attribution_repair`, `parallel_conflict_deferred`.
20
20
 
@@ -58,6 +58,21 @@ A **wave** is the scheduling unit: one `parallel: true` step, or (in graph mode)
58
58
  - `parallel_conflict_deferred` marks a ready step the hook deferred because the ready set was not conflict-free or a member lacked declared scopes (`stepIndex`, `deferredStepIndexes[]`, `reason`). The hook defers and logs; it never blocks and never stalls.
59
59
  - Attribution always prefers the active attempt or an explicit receipt; `currentAgent` is only a third disambiguator and is always marked `fallback`.
60
60
 
61
+ ## Execution provenance
62
+
63
+ The hook that arms or closes an attempt writes four allowlisted fields. Agents do not write them.
64
+
65
+ | Field | Values |
66
+ |---|---|
67
+ | `tool` | `cursor`, `claude`, `mavis`, `opencode`, `zcode` — the platform constant of the hook writing the event |
68
+ | `modelTier` | `cheap`, `standard`, `strong`, or null — `steps[i].model` only |
69
+ | `model` | `provider/id`, or null. Recorded without token counts |
70
+ | `modelSource` | `host`, `lease`, `tier-map`, `session`, or null |
71
+
72
+ `tool` on `attempt_started` is the hook that armed the attempt. `tool` on `attempt_finished` is the hook that closed it. The same four fields are written on `out_of_band_started` and `out_of_band_finished`.
73
+
74
+ Resolution order for `model`: the hook input (`execution.model` or `model`), then the session lease when `lease.tool` equals this hook's platform, then the approved `.ai.local/team/model-tiers.json` entry for the step tier. An empty `approvedBy` and an empty `tiers` object is not a map. `tier-map` is the resolved intent, not a measurement. A missing id stays null.
75
+
61
76
  ## Token usage
62
77
 
63
78
  Tokens are optional evidence, never an estimate. A missing record stays missing
@@ -88,7 +88,20 @@ function writeSessionLease(id, value) {
88
88
  const temporary = `${file}.${process.pid}.tmp`;
89
89
  const now = new Date().toISOString();
90
90
  const firstSeenAt = firstSeenAtOf(file, value, now);
91
- fs.writeFileSync(temporary, `${JSON.stringify({ slug: value, sessionId: id, firstSeenAt, updatedAt: now })}\n`);
91
+ let model = null;
92
+ try {
93
+ if (Date.now() - fs.statSync(file).mtimeMs <= LEASE_TTL_MS) {
94
+ const previous = JSON.parse(fs.readFileSync(file, 'utf8'));
95
+ const previousTool = previous && typeof previous.tool === 'string' ? previous.tool : '';
96
+ const keepModel = previous && previous.slug === value && (previousTool === '' || previousTool === PLATFORM);
97
+ if (keepModel && typeof previous.model === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(previous.model)) {
98
+ model = previous.model;
99
+ }
100
+ }
101
+ } catch {}
102
+ const body = { slug: value, sessionId: id, firstSeenAt, updatedAt: now, tool: PLATFORM };
103
+ if (model) body.model = model;
104
+ fs.writeFileSync(temporary, `${JSON.stringify(body)}\n`);
92
105
  fs.renameSync(temporary, file);
93
106
  for (const name of fs.readdirSync(LEASE_ROOT)) {
94
107
  if (!name.endsWith('.json')) continue;
@@ -179,8 +192,6 @@ if (slugSource === 'active-task.json') {
179
192
  if (slugSource !== 'TEAM_TASK_SLUG') {
180
193
  process.stderr.write(`WARNING: ${slug}: chain hook resolved the slug from ${slugSource}; pass TEAM_TASK_SLUG=<slug> on every hook call so parallel sessions cannot no-op each other.\n`);
181
194
  }
182
- if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
183
-
184
195
  const taskDir = path.join(TEAM_ROOT, 'tasks', slug);
185
196
  const statusPath = path.join(taskDir, 'status.json');
186
197
  const pipelinePath = path.join(taskDir, 'pipeline.json');
@@ -199,6 +210,7 @@ let status;
199
210
  const now = new Date().toISOString();
200
211
  const STACK = '__STACK__';
201
212
  const PLATFORM = '__PLATFORM__';
213
+ if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
202
214
 
203
215
  let metricsLockToken = null;
204
216
  function readMetricsLockToken() {
@@ -476,6 +488,7 @@ function reclaimStaleAttempts(scope) {
476
488
  type: 'attempt_finished',
477
489
  at: now,
478
490
  attemptId,
491
+ ...closingExecution(entry, Array.isArray(steps) ? steps[entry.stepIndex] : null),
479
492
  stepIndex: entry.stepIndex,
480
493
  stepLabel: (Array.isArray(steps) && steps[entry.stepIndex] && steps[entry.stepIndex].label) || null,
481
494
  agent: entry.agent,
@@ -542,6 +555,59 @@ function saveWriteScopeBaseline(step) {
542
555
  .split('\n').map((line) => line.trim()).filter(Boolean)[0] || `exit ${result ? result.status : 'unknown'}`;
543
556
  process.stderr.write(`[chain-team-phases] ${slug}: write-scope baseline for step ${stepId} not saved (${reason}); the audit will skip that step.\n`);
544
557
  }
558
+ const MODEL_TIERS = new Set(['cheap', 'standard', 'strong']);
559
+ const MODEL_SOURCES = new Set(['host', 'lease', 'tier-map', 'session']);
560
+ function boundedModel(value) {
561
+ if (typeof value !== 'string') return null;
562
+ const text = value.trim();
563
+ return /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(text) ? text : null;
564
+ }
565
+ function readTierMapModel(tier) {
566
+ try {
567
+ const parsed = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'model-tiers.json'), 'utf8'));
568
+ const tiers = parsed && parsed.tiers;
569
+ if (!tiers || typeof tiers !== 'object') return null;
570
+ const approvedBy = typeof parsed.approvedBy === 'string' ? parsed.approvedBy.trim() : '';
571
+ const filled = ['cheap', 'standard', 'strong'].some((key) => typeof tiers[key] === 'string' && tiers[key].trim() !== '');
572
+ if (approvedBy === '' && !filled) return null;
573
+ return boundedModel(tiers[tier]);
574
+ } catch {
575
+ return null;
576
+ }
577
+ }
578
+ function observedModel() {
579
+ const execution = hookInput && hookInput.execution;
580
+ if (execution && typeof execution === 'object') {
581
+ const model = boundedModel(execution.model);
582
+ if (model) return { model, modelSource: MODEL_SOURCES.has(execution.modelSource) ? execution.modelSource : 'host' };
583
+ }
584
+ const direct = boundedModel(hookInput && hookInput.model);
585
+ return direct ? { model: direct, modelSource: 'host' } : null;
586
+ }
587
+ function leaseModel() {
588
+ if (!sessionId) return null;
589
+ const lease = readSessionLease(sessionId);
590
+ if (!lease || lease.tool !== PLATFORM) return null;
591
+ const model = boundedModel(lease.model);
592
+ return model ? { model, modelSource: 'lease' } : null;
593
+ }
594
+ function executionForStep(step) {
595
+ const modelTier = step && MODEL_TIERS.has(step.model) ? step.model : null;
596
+ const observed = observedModel() || leaseModel();
597
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
598
+ const mapped = modelTier ? readTierMapModel(modelTier) : null;
599
+ if (mapped) return { tool: PLATFORM, modelTier, model: mapped, modelSource: 'tier-map' };
600
+ return { tool: PLATFORM, modelTier, model: null, modelSource: null };
601
+ }
602
+ function closingExecution(entry, step) {
603
+ const model = boundedModel(entry && entry.model);
604
+ const armedTier = entry && MODEL_TIERS.has(entry.modelTier) ? entry.modelTier : null;
605
+ const armedSource = model && entry && MODEL_SOURCES.has(entry.modelSource) ? entry.modelSource : null;
606
+ const observed = observedModel();
607
+ const modelTier = (step && MODEL_TIERS.has(step.model) ? step.model : null) || armedTier;
608
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
609
+ return { tool: PLATFORM, modelTier, model, modelSource: model ? armedSource : null };
610
+ }
545
611
  function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null) {
546
612
  const agents = Array.isArray(agentsOverride) && agentsOverride.length > 0 ? agentsOverride : getStepAgents(step);
547
613
  const parallelGroupId = step.parallel && getStepAgents(step).length > 1 ? `${status.metricsRunId || slug}:step-${stepIndex}` : null;
@@ -551,8 +617,9 @@ function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null)
551
617
  const attempt = nextAttemptOrdinal(stepIndex, agent); const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
552
618
  status.metricsRunId = runId; const attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
553
619
  if (active[attemptId]) continue;
554
- active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null };
555
- appendMetric({ type: 'attempt_started', at: now, attemptId, stepIndex, stepLabel: step.label || null, agent, role: roleFor(agent), attempt, parallelGroupId, waveId: waveId || null, source: 'hook', attributionConfidence: 'high' });
620
+ const execution = executionForStep(step);
621
+ active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null, ...execution };
622
+ appendMetric({ type: 'attempt_started', at: now, attemptId, stepIndex, stepLabel: step.label || null, agent, role: roleFor(agent), attempt, parallelGroupId, waveId: waveId || null, source: 'hook', attributionConfidence: 'high', ...execution });
556
623
  }
557
624
  status.activeAttempts = active;
558
625
  saveWriteScopeBaseline(step);
@@ -1556,10 +1623,12 @@ function finishActiveAttempt(forced) {
1556
1623
  const idleMs = wallMs === null ? null : Math.max(0, wallMs - (activeMs ?? 0));
1557
1624
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
1558
1625
  const usage = sanitizeUsage(hookInput.usage);
1626
+ const execution = closingExecution(resolved.entry, Array.isArray(steps) ? steps[resolved.entry.stepIndex] : null);
1559
1627
  appendMetric({
1560
1628
  type: 'attempt_finished',
1561
1629
  at: now,
1562
1630
  attemptId: resolved.attemptId,
1631
+ ...execution,
1563
1632
  stepIndex: typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : null,
1564
1633
  agent: resolved.entry.agent || null,
1565
1634
  outcome,
@@ -2787,9 +2856,10 @@ function armResumedAttempt(step, stepIndex, agent) {
2787
2856
  0,
2788
2857
  ) + 1;
2789
2858
  attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
2859
+ const execution = executionForStep(step);
2790
2860
  status.activeAttempts = {
2791
2861
  ...(status.activeAttempts || {}),
2792
- [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null },
2862
+ [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null, ...execution },
2793
2863
  };
2794
2864
  events.push({
2795
2865
  eventId: `${runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,
@@ -2805,6 +2875,7 @@ function armResumedAttempt(step, stepIndex, agent) {
2805
2875
  waveId: null,
2806
2876
  source: 'hook',
2807
2877
  attributionConfidence: 'high',
2878
+ ...execution,
2808
2879
  });
2809
2880
  });
2810
2881
  return attemptId;
@@ -2980,12 +3051,17 @@ if (hookInput.action === 'out_of_band_start') {
2980
3051
  const agent = typeof hookInput.agent === 'string' ? hookInput.agent : 'unknown';
2981
3052
  const reason = typeof hookInput.reason === 'string' ? hookInput.reason : null;
2982
3053
  const outOfBandId = `${status.metricsRunId || slug}:oob:${Date.now()}:${Math.random().toString(16).slice(2, 8)}`;
3054
+ const observed = observedModel();
2983
3055
  appendMetric({
2984
3056
  type: 'out_of_band_started',
2985
3057
  outOfBandId,
2986
3058
  agent,
2987
3059
  reason,
2988
3060
  at: now,
3061
+ tool: PLATFORM,
3062
+ modelTier: null,
3063
+ model: observed ? observed.model : null,
3064
+ modelSource: observed ? observed.modelSource : null,
2989
3065
  source: 'orchestrator',
2990
3066
  attributionConfidence: 'high',
2991
3067
  });
@@ -3020,6 +3096,7 @@ if (hookInput.action === 'out_of_band_end') {
3020
3096
  }
3021
3097
  const durationMs = Math.max(0, Date.parse(now) - Date.parse(started.at));
3022
3098
  const outcome = typeof hookInput.outcome === 'string' ? hookInput.outcome : 'completed';
3099
+ const finishedModel = boundedModel(started.model);
3023
3100
  appendMetric({
3024
3101
  type: 'out_of_band_finished',
3025
3102
  outOfBandId: started.outOfBandId,
@@ -3028,6 +3105,10 @@ if (hookInput.action === 'out_of_band_end') {
3028
3105
  outcome,
3029
3106
  durationMs,
3030
3107
  at: now,
3108
+ tool: PLATFORM,
3109
+ modelTier: MODEL_TIERS.has(started.modelTier) ? started.modelTier : null,
3110
+ model: finishedModel,
3111
+ modelSource: finishedModel && MODEL_SOURCES.has(started.modelSource) ? started.modelSource : null,
3031
3112
  source: 'orchestrator',
3032
3113
  attributionConfidence: 'high',
3033
3114
  });