@bonesofspring/ai-rules 0.2.90 → 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 (111) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/docs/OPENCODE-COMPATIBILITY.md +2 -1
  3. package/docs/OPENCODE.md +20 -2
  4. package/docs/TEAM-DB.md +2 -0
  5. package/package.json +1 -1
  6. package/presets/_shared/ai-local/scripts/team-db-api.mjs +33 -15
  7. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +15 -0
  8. package/presets/_shared/ai-local/scripts/team-db-project.mjs +41 -2
  9. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +23 -0
  10. package/presets/_shared/core/agent-team/agent-task-metrics.md +16 -1
  11. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +87 -6
  12. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +87 -6
  13. package/presets/claude/go/hooks/chain-team-phases.sh +87 -6
  14. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +87 -6
  15. package/presets/claude/java/hooks/chain-team-phases.sh +87 -6
  16. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +87 -6
  17. package/presets/claude/mol/hooks/chain-team-phases.sh +87 -6
  18. package/presets/claude/next/hooks/chain-team-phases.sh +87 -6
  19. package/presets/claude/nuxt/hooks/chain-team-phases.sh +87 -6
  20. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  21. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +87 -6
  22. package/presets/claude/svelte/hooks/chain-team-phases.sh +87 -6
  23. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +87 -6
  24. package/presets/cursor/go/hooks/chain-team-phases.sh +87 -6
  25. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +87 -6
  26. package/presets/cursor/java/hooks/chain-team-phases.sh +87 -6
  27. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +87 -6
  28. package/presets/cursor/mol/hooks/chain-team-phases.sh +87 -6
  29. package/presets/cursor/next/hooks/chain-team-phases.sh +87 -6
  30. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +87 -6
  31. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  32. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +87 -6
  33. package/presets/cursor/svelte/hooks/chain-team-phases.sh +87 -6
  34. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  35. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +87 -6
  36. package/presets/mavis/go/adapter-map.json +1 -1
  37. package/presets/mavis/go/hooks/chain-team-phases.sh +87 -6
  38. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  39. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +87 -6
  40. package/presets/mavis/java/adapter-map.json +1 -1
  41. package/presets/mavis/java/hooks/chain-team-phases.sh +87 -6
  42. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  43. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +87 -6
  44. package/presets/mavis/mol/adapter-map.json +1 -1
  45. package/presets/mavis/mol/hooks/chain-team-phases.sh +87 -6
  46. package/presets/mavis/next/adapter-map.json +1 -1
  47. package/presets/mavis/next/hooks/chain-team-phases.sh +87 -6
  48. package/presets/mavis/nuxt/adapter-map.json +1 -1
  49. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +87 -6
  50. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  51. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  52. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  53. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +87 -6
  54. package/presets/mavis/svelte/adapter-map.json +1 -1
  55. package/presets/mavis/svelte/hooks/chain-team-phases.sh +87 -6
  56. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  57. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +87 -6
  58. package/presets/opencode/go/adapter-map.json +1 -1
  59. package/presets/opencode/go/hooks/chain-team-phases.sh +87 -6
  60. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  61. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +87 -6
  62. package/presets/opencode/java/adapter-map.json +1 -1
  63. package/presets/opencode/java/hooks/chain-team-phases.sh +87 -6
  64. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  65. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +87 -6
  66. package/presets/opencode/mol/adapter-map.json +1 -1
  67. package/presets/opencode/mol/hooks/chain-team-phases.sh +87 -6
  68. package/presets/opencode/next/adapter-map.json +1 -1
  69. package/presets/opencode/next/hooks/chain-team-phases.sh +87 -6
  70. package/presets/opencode/nuxt/adapter-map.json +1 -1
  71. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +87 -6
  72. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  73. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  74. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  75. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +87 -6
  76. package/presets/opencode/plugins/output-guard/README.md +4 -3
  77. package/presets/opencode/plugins/output-guard/index.ts +4 -3
  78. package/presets/opencode/plugins/output-guard/rewrite.ts +1 -2
  79. package/presets/opencode/plugins/rule-attach/README.md +1 -1
  80. package/presets/opencode/plugins/rule-attach/index.ts +23 -4
  81. package/presets/opencode/plugins/settings-guard/README.md +3 -0
  82. package/presets/opencode/plugins/settings-guard/index.ts +1 -1
  83. package/presets/opencode/plugins/settings-guard/policy.mjs +1 -1
  84. package/presets/opencode/plugins/task-status/README.md +4 -4
  85. package/presets/opencode/plugins/task-status/deepseek.ts +27 -8
  86. package/presets/opencode/plugins/task-status/task-view.ts +8 -4
  87. package/presets/opencode/plugins/task-status/tui.tsx +12 -3
  88. package/presets/opencode/svelte/adapter-map.json +1 -1
  89. package/presets/opencode/svelte/hooks/chain-team-phases.sh +87 -6
  90. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  91. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +87 -6
  92. package/presets/zcode/go/adapter-map.json +1 -1
  93. package/presets/zcode/go/hooks/chain-team-phases.sh +87 -6
  94. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  95. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +87 -6
  96. package/presets/zcode/java/adapter-map.json +1 -1
  97. package/presets/zcode/java/hooks/chain-team-phases.sh +87 -6
  98. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  99. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +87 -6
  100. package/presets/zcode/mol/adapter-map.json +1 -1
  101. package/presets/zcode/mol/hooks/chain-team-phases.sh +87 -6
  102. package/presets/zcode/next/adapter-map.json +1 -1
  103. package/presets/zcode/next/hooks/chain-team-phases.sh +87 -6
  104. package/presets/zcode/nuxt/adapter-map.json +1 -1
  105. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +87 -6
  106. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  107. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +87 -6
  108. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  109. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +87 -6
  110. package/presets/zcode/svelte/adapter-map.json +1 -1
  111. package/presets/zcode/svelte/hooks/chain-team-phases.sh +87 -6
@@ -104,7 +104,20 @@ function writeSessionLease(id, value) {
104
104
  const temporary = `${file}.${process.pid}.tmp`;
105
105
  const now = new Date().toISOString();
106
106
  const firstSeenAt = firstSeenAtOf(file, value, now);
107
- fs.writeFileSync(temporary, `${JSON.stringify({ slug: value, sessionId: id, firstSeenAt, updatedAt: now })}\n`);
107
+ let model = null;
108
+ try {
109
+ if (Date.now() - fs.statSync(file).mtimeMs <= LEASE_TTL_MS) {
110
+ const previous = JSON.parse(fs.readFileSync(file, 'utf8'));
111
+ const previousTool = previous && typeof previous.tool === 'string' ? previous.tool : '';
112
+ const keepModel = previous && previous.slug === value && (previousTool === '' || previousTool === PLATFORM);
113
+ if (keepModel && typeof previous.model === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(previous.model)) {
114
+ model = previous.model;
115
+ }
116
+ }
117
+ } catch {}
118
+ const body = { slug: value, sessionId: id, firstSeenAt, updatedAt: now, tool: PLATFORM };
119
+ if (model) body.model = model;
120
+ fs.writeFileSync(temporary, `${JSON.stringify(body)}\n`);
108
121
  fs.renameSync(temporary, file);
109
122
  for (const name of fs.readdirSync(LEASE_ROOT)) {
110
123
  if (!name.endsWith('.json')) continue;
@@ -195,8 +208,6 @@ if (slugSource === 'active-task.json') {
195
208
  if (slugSource !== 'TEAM_TASK_SLUG') {
196
209
  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`);
197
210
  }
198
- if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
199
-
200
211
  const taskDir = path.join(TEAM_ROOT, 'tasks', slug);
201
212
  const statusPath = path.join(taskDir, 'status.json');
202
213
  const pipelinePath = path.join(taskDir, 'pipeline.json');
@@ -215,6 +226,7 @@ let status;
215
226
  const now = new Date().toISOString();
216
227
  const STACK = 'next';
217
228
  const PLATFORM = 'claude';
229
+ if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
218
230
 
219
231
  let metricsLockToken = null;
220
232
  function readMetricsLockToken() {
@@ -513,6 +525,7 @@ function reclaimStaleAttempts(scope) {
513
525
  type: 'attempt_finished',
514
526
  at: now,
515
527
  attemptId,
528
+ ...closingExecution(entry, Array.isArray(steps) ? steps[entry.stepIndex] : null),
516
529
  stepIndex: entry.stepIndex,
517
530
  stepLabel: (Array.isArray(steps) && steps[entry.stepIndex] && steps[entry.stepIndex].label) || null,
518
531
  agent: entry.agent,
@@ -579,6 +592,59 @@ function saveWriteScopeBaseline(step) {
579
592
  .split('\n').map((line) => line.trim()).filter(Boolean)[0] || `exit ${result ? result.status : 'unknown'}`;
580
593
  process.stderr.write(`[chain-team-phases] ${slug}: write-scope baseline for step ${stepId} not saved (${reason}); the audit will skip that step.\n`);
581
594
  }
595
+ const MODEL_TIERS = new Set(['cheap', 'standard', 'strong']);
596
+ const MODEL_SOURCES = new Set(['host', 'lease', 'tier-map', 'session']);
597
+ function boundedModel(value) {
598
+ if (typeof value !== 'string') return null;
599
+ const text = value.trim();
600
+ return /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(text) ? text : null;
601
+ }
602
+ function readTierMapModel(tier) {
603
+ try {
604
+ const parsed = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'model-tiers.json'), 'utf8'));
605
+ const tiers = parsed && parsed.tiers;
606
+ if (!tiers || typeof tiers !== 'object') return null;
607
+ const approvedBy = typeof parsed.approvedBy === 'string' ? parsed.approvedBy.trim() : '';
608
+ const filled = ['cheap', 'standard', 'strong'].some((key) => typeof tiers[key] === 'string' && tiers[key].trim() !== '');
609
+ if (approvedBy === '' && !filled) return null;
610
+ return boundedModel(tiers[tier]);
611
+ } catch {
612
+ return null;
613
+ }
614
+ }
615
+ function observedModel() {
616
+ const execution = hookInput && hookInput.execution;
617
+ if (execution && typeof execution === 'object') {
618
+ const model = boundedModel(execution.model);
619
+ if (model) return { model, modelSource: MODEL_SOURCES.has(execution.modelSource) ? execution.modelSource : 'host' };
620
+ }
621
+ const direct = boundedModel(hookInput && hookInput.model);
622
+ return direct ? { model: direct, modelSource: 'host' } : null;
623
+ }
624
+ function leaseModel() {
625
+ if (!sessionId) return null;
626
+ const lease = readSessionLease(sessionId);
627
+ if (!lease || lease.tool !== PLATFORM) return null;
628
+ const model = boundedModel(lease.model);
629
+ return model ? { model, modelSource: 'lease' } : null;
630
+ }
631
+ function executionForStep(step) {
632
+ const modelTier = step && MODEL_TIERS.has(step.model) ? step.model : null;
633
+ const observed = observedModel() || leaseModel();
634
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
635
+ const mapped = modelTier ? readTierMapModel(modelTier) : null;
636
+ if (mapped) return { tool: PLATFORM, modelTier, model: mapped, modelSource: 'tier-map' };
637
+ return { tool: PLATFORM, modelTier, model: null, modelSource: null };
638
+ }
639
+ function closingExecution(entry, step) {
640
+ const model = boundedModel(entry && entry.model);
641
+ const armedTier = entry && MODEL_TIERS.has(entry.modelTier) ? entry.modelTier : null;
642
+ const armedSource = model && entry && MODEL_SOURCES.has(entry.modelSource) ? entry.modelSource : null;
643
+ const observed = observedModel();
644
+ const modelTier = (step && MODEL_TIERS.has(step.model) ? step.model : null) || armedTier;
645
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
646
+ return { tool: PLATFORM, modelTier, model, modelSource: model ? armedSource : null };
647
+ }
582
648
  function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null) {
583
649
  const agents = Array.isArray(agentsOverride) && agentsOverride.length > 0 ? agentsOverride : getStepAgents(step);
584
650
  const parallelGroupId = step.parallel && getStepAgents(step).length > 1 ? `${status.metricsRunId || slug}:step-${stepIndex}` : null;
@@ -588,8 +654,9 @@ function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null)
588
654
  const attempt = nextAttemptOrdinal(stepIndex, agent); const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
589
655
  status.metricsRunId = runId; const attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
590
656
  if (active[attemptId]) continue;
591
- active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null };
592
- 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' });
657
+ const execution = executionForStep(step);
658
+ active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null, ...execution };
659
+ 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 });
593
660
  }
594
661
  status.activeAttempts = active;
595
662
  saveWriteScopeBaseline(step);
@@ -1593,10 +1660,12 @@ function finishActiveAttempt(forced) {
1593
1660
  const idleMs = wallMs === null ? null : Math.max(0, wallMs - (activeMs ?? 0));
1594
1661
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
1595
1662
  const usage = sanitizeUsage(hookInput.usage);
1663
+ const execution = closingExecution(resolved.entry, Array.isArray(steps) ? steps[resolved.entry.stepIndex] : null);
1596
1664
  appendMetric({
1597
1665
  type: 'attempt_finished',
1598
1666
  at: now,
1599
1667
  attemptId: resolved.attemptId,
1668
+ ...execution,
1600
1669
  stepIndex: typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : null,
1601
1670
  agent: resolved.entry.agent || null,
1602
1671
  outcome,
@@ -2944,9 +3013,10 @@ function armResumedAttempt(step, stepIndex, agent) {
2944
3013
  0,
2945
3014
  ) + 1;
2946
3015
  attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
3016
+ const execution = executionForStep(step);
2947
3017
  status.activeAttempts = {
2948
3018
  ...(status.activeAttempts || {}),
2949
- [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null },
3019
+ [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null, ...execution },
2950
3020
  };
2951
3021
  events.push({
2952
3022
  eventId: `${runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,
@@ -2962,6 +3032,7 @@ function armResumedAttempt(step, stepIndex, agent) {
2962
3032
  waveId: null,
2963
3033
  source: 'hook',
2964
3034
  attributionConfidence: 'high',
3035
+ ...execution,
2965
3036
  });
2966
3037
  });
2967
3038
  return attemptId;
@@ -3137,12 +3208,17 @@ if (hookInput.action === 'out_of_band_start') {
3137
3208
  const agent = typeof hookInput.agent === 'string' ? hookInput.agent : 'unknown';
3138
3209
  const reason = typeof hookInput.reason === 'string' ? hookInput.reason : null;
3139
3210
  const outOfBandId = `${status.metricsRunId || slug}:oob:${Date.now()}:${Math.random().toString(16).slice(2, 8)}`;
3211
+ const observed = observedModel();
3140
3212
  appendMetric({
3141
3213
  type: 'out_of_band_started',
3142
3214
  outOfBandId,
3143
3215
  agent,
3144
3216
  reason,
3145
3217
  at: now,
3218
+ tool: PLATFORM,
3219
+ modelTier: null,
3220
+ model: observed ? observed.model : null,
3221
+ modelSource: observed ? observed.modelSource : null,
3146
3222
  source: 'orchestrator',
3147
3223
  attributionConfidence: 'high',
3148
3224
  });
@@ -3177,6 +3253,7 @@ if (hookInput.action === 'out_of_band_end') {
3177
3253
  }
3178
3254
  const durationMs = Math.max(0, Date.parse(now) - Date.parse(started.at));
3179
3255
  const outcome = typeof hookInput.outcome === 'string' ? hookInput.outcome : 'completed';
3256
+ const finishedModel = boundedModel(started.model);
3180
3257
  appendMetric({
3181
3258
  type: 'out_of_band_finished',
3182
3259
  outOfBandId: started.outOfBandId,
@@ -3185,6 +3262,10 @@ if (hookInput.action === 'out_of_band_end') {
3185
3262
  outcome,
3186
3263
  durationMs,
3187
3264
  at: now,
3265
+ tool: PLATFORM,
3266
+ modelTier: MODEL_TIERS.has(started.modelTier) ? started.modelTier : null,
3267
+ model: finishedModel,
3268
+ modelSource: finishedModel && MODEL_SOURCES.has(started.modelSource) ? started.modelSource : null,
3188
3269
  source: 'orchestrator',
3189
3270
  attributionConfidence: 'high',
3190
3271
  });
@@ -104,7 +104,20 @@ function writeSessionLease(id, value) {
104
104
  const temporary = `${file}.${process.pid}.tmp`;
105
105
  const now = new Date().toISOString();
106
106
  const firstSeenAt = firstSeenAtOf(file, value, now);
107
- fs.writeFileSync(temporary, `${JSON.stringify({ slug: value, sessionId: id, firstSeenAt, updatedAt: now })}\n`);
107
+ let model = null;
108
+ try {
109
+ if (Date.now() - fs.statSync(file).mtimeMs <= LEASE_TTL_MS) {
110
+ const previous = JSON.parse(fs.readFileSync(file, 'utf8'));
111
+ const previousTool = previous && typeof previous.tool === 'string' ? previous.tool : '';
112
+ const keepModel = previous && previous.slug === value && (previousTool === '' || previousTool === PLATFORM);
113
+ if (keepModel && typeof previous.model === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(previous.model)) {
114
+ model = previous.model;
115
+ }
116
+ }
117
+ } catch {}
118
+ const body = { slug: value, sessionId: id, firstSeenAt, updatedAt: now, tool: PLATFORM };
119
+ if (model) body.model = model;
120
+ fs.writeFileSync(temporary, `${JSON.stringify(body)}\n`);
108
121
  fs.renameSync(temporary, file);
109
122
  for (const name of fs.readdirSync(LEASE_ROOT)) {
110
123
  if (!name.endsWith('.json')) continue;
@@ -195,8 +208,6 @@ if (slugSource === 'active-task.json') {
195
208
  if (slugSource !== 'TEAM_TASK_SLUG') {
196
209
  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`);
197
210
  }
198
- if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
199
-
200
211
  const taskDir = path.join(TEAM_ROOT, 'tasks', slug);
201
212
  const statusPath = path.join(taskDir, 'status.json');
202
213
  const pipelinePath = path.join(taskDir, 'pipeline.json');
@@ -215,6 +226,7 @@ let status;
215
226
  const now = new Date().toISOString();
216
227
  const STACK = 'nuxt';
217
228
  const PLATFORM = 'claude';
229
+ if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
218
230
 
219
231
  let metricsLockToken = null;
220
232
  function readMetricsLockToken() {
@@ -513,6 +525,7 @@ function reclaimStaleAttempts(scope) {
513
525
  type: 'attempt_finished',
514
526
  at: now,
515
527
  attemptId,
528
+ ...closingExecution(entry, Array.isArray(steps) ? steps[entry.stepIndex] : null),
516
529
  stepIndex: entry.stepIndex,
517
530
  stepLabel: (Array.isArray(steps) && steps[entry.stepIndex] && steps[entry.stepIndex].label) || null,
518
531
  agent: entry.agent,
@@ -579,6 +592,59 @@ function saveWriteScopeBaseline(step) {
579
592
  .split('\n').map((line) => line.trim()).filter(Boolean)[0] || `exit ${result ? result.status : 'unknown'}`;
580
593
  process.stderr.write(`[chain-team-phases] ${slug}: write-scope baseline for step ${stepId} not saved (${reason}); the audit will skip that step.\n`);
581
594
  }
595
+ const MODEL_TIERS = new Set(['cheap', 'standard', 'strong']);
596
+ const MODEL_SOURCES = new Set(['host', 'lease', 'tier-map', 'session']);
597
+ function boundedModel(value) {
598
+ if (typeof value !== 'string') return null;
599
+ const text = value.trim();
600
+ return /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(text) ? text : null;
601
+ }
602
+ function readTierMapModel(tier) {
603
+ try {
604
+ const parsed = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'model-tiers.json'), 'utf8'));
605
+ const tiers = parsed && parsed.tiers;
606
+ if (!tiers || typeof tiers !== 'object') return null;
607
+ const approvedBy = typeof parsed.approvedBy === 'string' ? parsed.approvedBy.trim() : '';
608
+ const filled = ['cheap', 'standard', 'strong'].some((key) => typeof tiers[key] === 'string' && tiers[key].trim() !== '');
609
+ if (approvedBy === '' && !filled) return null;
610
+ return boundedModel(tiers[tier]);
611
+ } catch {
612
+ return null;
613
+ }
614
+ }
615
+ function observedModel() {
616
+ const execution = hookInput && hookInput.execution;
617
+ if (execution && typeof execution === 'object') {
618
+ const model = boundedModel(execution.model);
619
+ if (model) return { model, modelSource: MODEL_SOURCES.has(execution.modelSource) ? execution.modelSource : 'host' };
620
+ }
621
+ const direct = boundedModel(hookInput && hookInput.model);
622
+ return direct ? { model: direct, modelSource: 'host' } : null;
623
+ }
624
+ function leaseModel() {
625
+ if (!sessionId) return null;
626
+ const lease = readSessionLease(sessionId);
627
+ if (!lease || lease.tool !== PLATFORM) return null;
628
+ const model = boundedModel(lease.model);
629
+ return model ? { model, modelSource: 'lease' } : null;
630
+ }
631
+ function executionForStep(step) {
632
+ const modelTier = step && MODEL_TIERS.has(step.model) ? step.model : null;
633
+ const observed = observedModel() || leaseModel();
634
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
635
+ const mapped = modelTier ? readTierMapModel(modelTier) : null;
636
+ if (mapped) return { tool: PLATFORM, modelTier, model: mapped, modelSource: 'tier-map' };
637
+ return { tool: PLATFORM, modelTier, model: null, modelSource: null };
638
+ }
639
+ function closingExecution(entry, step) {
640
+ const model = boundedModel(entry && entry.model);
641
+ const armedTier = entry && MODEL_TIERS.has(entry.modelTier) ? entry.modelTier : null;
642
+ const armedSource = model && entry && MODEL_SOURCES.has(entry.modelSource) ? entry.modelSource : null;
643
+ const observed = observedModel();
644
+ const modelTier = (step && MODEL_TIERS.has(step.model) ? step.model : null) || armedTier;
645
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
646
+ return { tool: PLATFORM, modelTier, model, modelSource: model ? armedSource : null };
647
+ }
582
648
  function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null) {
583
649
  const agents = Array.isArray(agentsOverride) && agentsOverride.length > 0 ? agentsOverride : getStepAgents(step);
584
650
  const parallelGroupId = step.parallel && getStepAgents(step).length > 1 ? `${status.metricsRunId || slug}:step-${stepIndex}` : null;
@@ -588,8 +654,9 @@ function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null)
588
654
  const attempt = nextAttemptOrdinal(stepIndex, agent); const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
589
655
  status.metricsRunId = runId; const attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
590
656
  if (active[attemptId]) continue;
591
- active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null };
592
- 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' });
657
+ const execution = executionForStep(step);
658
+ active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null, ...execution };
659
+ 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 });
593
660
  }
594
661
  status.activeAttempts = active;
595
662
  saveWriteScopeBaseline(step);
@@ -1593,10 +1660,12 @@ function finishActiveAttempt(forced) {
1593
1660
  const idleMs = wallMs === null ? null : Math.max(0, wallMs - (activeMs ?? 0));
1594
1661
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
1595
1662
  const usage = sanitizeUsage(hookInput.usage);
1663
+ const execution = closingExecution(resolved.entry, Array.isArray(steps) ? steps[resolved.entry.stepIndex] : null);
1596
1664
  appendMetric({
1597
1665
  type: 'attempt_finished',
1598
1666
  at: now,
1599
1667
  attemptId: resolved.attemptId,
1668
+ ...execution,
1600
1669
  stepIndex: typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : null,
1601
1670
  agent: resolved.entry.agent || null,
1602
1671
  outcome,
@@ -2944,9 +3013,10 @@ function armResumedAttempt(step, stepIndex, agent) {
2944
3013
  0,
2945
3014
  ) + 1;
2946
3015
  attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
3016
+ const execution = executionForStep(step);
2947
3017
  status.activeAttempts = {
2948
3018
  ...(status.activeAttempts || {}),
2949
- [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null },
3019
+ [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null, ...execution },
2950
3020
  };
2951
3021
  events.push({
2952
3022
  eventId: `${runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,
@@ -2962,6 +3032,7 @@ function armResumedAttempt(step, stepIndex, agent) {
2962
3032
  waveId: null,
2963
3033
  source: 'hook',
2964
3034
  attributionConfidence: 'high',
3035
+ ...execution,
2965
3036
  });
2966
3037
  });
2967
3038
  return attemptId;
@@ -3137,12 +3208,17 @@ if (hookInput.action === 'out_of_band_start') {
3137
3208
  const agent = typeof hookInput.agent === 'string' ? hookInput.agent : 'unknown';
3138
3209
  const reason = typeof hookInput.reason === 'string' ? hookInput.reason : null;
3139
3210
  const outOfBandId = `${status.metricsRunId || slug}:oob:${Date.now()}:${Math.random().toString(16).slice(2, 8)}`;
3211
+ const observed = observedModel();
3140
3212
  appendMetric({
3141
3213
  type: 'out_of_band_started',
3142
3214
  outOfBandId,
3143
3215
  agent,
3144
3216
  reason,
3145
3217
  at: now,
3218
+ tool: PLATFORM,
3219
+ modelTier: null,
3220
+ model: observed ? observed.model : null,
3221
+ modelSource: observed ? observed.modelSource : null,
3146
3222
  source: 'orchestrator',
3147
3223
  attributionConfidence: 'high',
3148
3224
  });
@@ -3177,6 +3253,7 @@ if (hookInput.action === 'out_of_band_end') {
3177
3253
  }
3178
3254
  const durationMs = Math.max(0, Date.parse(now) - Date.parse(started.at));
3179
3255
  const outcome = typeof hookInput.outcome === 'string' ? hookInput.outcome : 'completed';
3256
+ const finishedModel = boundedModel(started.model);
3180
3257
  appendMetric({
3181
3258
  type: 'out_of_band_finished',
3182
3259
  outOfBandId: started.outOfBandId,
@@ -3185,6 +3262,10 @@ if (hookInput.action === 'out_of_band_end') {
3185
3262
  outcome,
3186
3263
  durationMs,
3187
3264
  at: now,
3265
+ tool: PLATFORM,
3266
+ modelTier: MODEL_TIERS.has(started.modelTier) ? started.modelTier : null,
3267
+ model: finishedModel,
3268
+ modelSource: finishedModel && MODEL_SOURCES.has(started.modelSource) ? started.modelSource : null,
3188
3269
  source: 'orchestrator',
3189
3270
  attributionConfidence: 'high',
3190
3271
  });
@@ -106,7 +106,20 @@ function writeSessionLease(id, value) {
106
106
  const temporary = `${file}.${process.pid}.tmp`;
107
107
  const now = new Date().toISOString();
108
108
  const firstSeenAt = firstSeenAtOf(file, value, now);
109
- fs.writeFileSync(temporary, `${JSON.stringify({ slug: value, sessionId: id, firstSeenAt, updatedAt: now })}\n`);
109
+ let model = null;
110
+ try {
111
+ if (Date.now() - fs.statSync(file).mtimeMs <= LEASE_TTL_MS) {
112
+ const previous = JSON.parse(fs.readFileSync(file, 'utf8'));
113
+ const previousTool = previous && typeof previous.tool === 'string' ? previous.tool : '';
114
+ const keepModel = previous && previous.slug === value && (previousTool === '' || previousTool === PLATFORM);
115
+ if (keepModel && typeof previous.model === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(previous.model)) {
116
+ model = previous.model;
117
+ }
118
+ }
119
+ } catch {}
120
+ const body = { slug: value, sessionId: id, firstSeenAt, updatedAt: now, tool: PLATFORM };
121
+ if (model) body.model = model;
122
+ fs.writeFileSync(temporary, `${JSON.stringify(body)}\n`);
110
123
  fs.renameSync(temporary, file);
111
124
  for (const name of fs.readdirSync(LEASE_ROOT)) {
112
125
  if (!name.endsWith('.json')) continue;
@@ -197,8 +210,6 @@ if (slugSource === 'active-task.json') {
197
210
  if (slugSource !== 'TEAM_TASK_SLUG') {
198
211
  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`);
199
212
  }
200
- if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
201
-
202
213
  const taskDir = path.join(TEAM_ROOT, 'tasks', slug);
203
214
  const statusPath = path.join(taskDir, 'status.json');
204
215
  const pipelinePath = path.join(taskDir, 'pipeline.json');
@@ -217,6 +228,7 @@ let status;
217
228
  const now = new Date().toISOString();
218
229
  const STACK = 'php-hexagonal';
219
230
  const PLATFORM = 'claude';
231
+ if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
220
232
 
221
233
  let metricsLockToken = null;
222
234
  function readMetricsLockToken() {
@@ -513,6 +525,7 @@ function reclaimStaleAttempts(scope) {
513
525
  type: 'attempt_finished',
514
526
  at: now,
515
527
  attemptId,
528
+ ...closingExecution(entry, Array.isArray(steps) ? steps[entry.stepIndex] : null),
516
529
  stepIndex: entry.stepIndex,
517
530
  stepLabel: (Array.isArray(steps) && steps[entry.stepIndex] && steps[entry.stepIndex].label) || null,
518
531
  agent: entry.agent,
@@ -579,6 +592,59 @@ function saveWriteScopeBaseline(step) {
579
592
  .split('\n').map((line) => line.trim()).filter(Boolean)[0] || `exit ${result ? result.status : 'unknown'}`;
580
593
  process.stderr.write(`[chain-team-phases] ${slug}: write-scope baseline for step ${stepId} not saved (${reason}); the audit will skip that step.\n`);
581
594
  }
595
+ const MODEL_TIERS = new Set(['cheap', 'standard', 'strong']);
596
+ const MODEL_SOURCES = new Set(['host', 'lease', 'tier-map', 'session']);
597
+ function boundedModel(value) {
598
+ if (typeof value !== 'string') return null;
599
+ const text = value.trim();
600
+ return /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(text) ? text : null;
601
+ }
602
+ function readTierMapModel(tier) {
603
+ try {
604
+ const parsed = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'model-tiers.json'), 'utf8'));
605
+ const tiers = parsed && parsed.tiers;
606
+ if (!tiers || typeof tiers !== 'object') return null;
607
+ const approvedBy = typeof parsed.approvedBy === 'string' ? parsed.approvedBy.trim() : '';
608
+ const filled = ['cheap', 'standard', 'strong'].some((key) => typeof tiers[key] === 'string' && tiers[key].trim() !== '');
609
+ if (approvedBy === '' && !filled) return null;
610
+ return boundedModel(tiers[tier]);
611
+ } catch {
612
+ return null;
613
+ }
614
+ }
615
+ function observedModel() {
616
+ const execution = hookInput && hookInput.execution;
617
+ if (execution && typeof execution === 'object') {
618
+ const model = boundedModel(execution.model);
619
+ if (model) return { model, modelSource: MODEL_SOURCES.has(execution.modelSource) ? execution.modelSource : 'host' };
620
+ }
621
+ const direct = boundedModel(hookInput && hookInput.model);
622
+ return direct ? { model: direct, modelSource: 'host' } : null;
623
+ }
624
+ function leaseModel() {
625
+ if (!sessionId) return null;
626
+ const lease = readSessionLease(sessionId);
627
+ if (!lease || lease.tool !== PLATFORM) return null;
628
+ const model = boundedModel(lease.model);
629
+ return model ? { model, modelSource: 'lease' } : null;
630
+ }
631
+ function executionForStep(step) {
632
+ const modelTier = step && MODEL_TIERS.has(step.model) ? step.model : null;
633
+ const observed = observedModel() || leaseModel();
634
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
635
+ const mapped = modelTier ? readTierMapModel(modelTier) : null;
636
+ if (mapped) return { tool: PLATFORM, modelTier, model: mapped, modelSource: 'tier-map' };
637
+ return { tool: PLATFORM, modelTier, model: null, modelSource: null };
638
+ }
639
+ function closingExecution(entry, step) {
640
+ const model = boundedModel(entry && entry.model);
641
+ const armedTier = entry && MODEL_TIERS.has(entry.modelTier) ? entry.modelTier : null;
642
+ const armedSource = model && entry && MODEL_SOURCES.has(entry.modelSource) ? entry.modelSource : null;
643
+ const observed = observedModel();
644
+ const modelTier = (step && MODEL_TIERS.has(step.model) ? step.model : null) || armedTier;
645
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
646
+ return { tool: PLATFORM, modelTier, model, modelSource: model ? armedSource : null };
647
+ }
582
648
  function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null) {
583
649
  const agents = Array.isArray(agentsOverride) && agentsOverride.length > 0 ? agentsOverride : getStepAgents(step);
584
650
  const parallelGroupId = step.parallel && getStepAgents(step).length > 1 ? `${status.metricsRunId || slug}:step-${stepIndex}` : null;
@@ -588,8 +654,9 @@ function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null)
588
654
  const attempt = nextAttemptOrdinal(stepIndex, agent); const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
589
655
  status.metricsRunId = runId; const attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
590
656
  if (active[attemptId]) continue;
591
- active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null };
592
- 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' });
657
+ const execution = executionForStep(step);
658
+ active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null, ...execution };
659
+ 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 });
593
660
  }
594
661
  status.activeAttempts = active;
595
662
  saveWriteScopeBaseline(step);
@@ -1593,10 +1660,12 @@ function finishActiveAttempt(forced) {
1593
1660
  const idleMs = wallMs === null ? null : Math.max(0, wallMs - (activeMs ?? 0));
1594
1661
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
1595
1662
  const usage = sanitizeUsage(hookInput.usage);
1663
+ const execution = closingExecution(resolved.entry, Array.isArray(steps) ? steps[resolved.entry.stepIndex] : null);
1596
1664
  appendMetric({
1597
1665
  type: 'attempt_finished',
1598
1666
  at: now,
1599
1667
  attemptId: resolved.attemptId,
1668
+ ...execution,
1600
1669
  stepIndex: typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : null,
1601
1670
  agent: resolved.entry.agent || null,
1602
1671
  outcome,
@@ -2942,9 +3011,10 @@ function armResumedAttempt(step, stepIndex, agent) {
2942
3011
  0,
2943
3012
  ) + 1;
2944
3013
  attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
3014
+ const execution = executionForStep(step);
2945
3015
  status.activeAttempts = {
2946
3016
  ...(status.activeAttempts || {}),
2947
- [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null },
3017
+ [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null, ...execution },
2948
3018
  };
2949
3019
  events.push({
2950
3020
  eventId: `${runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,
@@ -2960,6 +3030,7 @@ function armResumedAttempt(step, stepIndex, agent) {
2960
3030
  waveId: null,
2961
3031
  source: 'hook',
2962
3032
  attributionConfidence: 'high',
3033
+ ...execution,
2963
3034
  });
2964
3035
  });
2965
3036
  return attemptId;
@@ -3135,12 +3206,17 @@ if (hookInput.action === 'out_of_band_start') {
3135
3206
  const agent = typeof hookInput.agent === 'string' ? hookInput.agent : 'unknown';
3136
3207
  const reason = typeof hookInput.reason === 'string' ? hookInput.reason : null;
3137
3208
  const outOfBandId = `${status.metricsRunId || slug}:oob:${Date.now()}:${Math.random().toString(16).slice(2, 8)}`;
3209
+ const observed = observedModel();
3138
3210
  appendMetric({
3139
3211
  type: 'out_of_band_started',
3140
3212
  outOfBandId,
3141
3213
  agent,
3142
3214
  reason,
3143
3215
  at: now,
3216
+ tool: PLATFORM,
3217
+ modelTier: null,
3218
+ model: observed ? observed.model : null,
3219
+ modelSource: observed ? observed.modelSource : null,
3144
3220
  source: 'orchestrator',
3145
3221
  attributionConfidence: 'high',
3146
3222
  });
@@ -3175,6 +3251,7 @@ if (hookInput.action === 'out_of_band_end') {
3175
3251
  }
3176
3252
  const durationMs = Math.max(0, Date.parse(now) - Date.parse(started.at));
3177
3253
  const outcome = typeof hookInput.outcome === 'string' ? hookInput.outcome : 'completed';
3254
+ const finishedModel = boundedModel(started.model);
3178
3255
  appendMetric({
3179
3256
  type: 'out_of_band_finished',
3180
3257
  outOfBandId: started.outOfBandId,
@@ -3183,6 +3260,10 @@ if (hookInput.action === 'out_of_band_end') {
3183
3260
  outcome,
3184
3261
  durationMs,
3185
3262
  at: now,
3263
+ tool: PLATFORM,
3264
+ modelTier: MODEL_TIERS.has(started.modelTier) ? started.modelTier : null,
3265
+ model: finishedModel,
3266
+ modelSource: finishedModel && MODEL_SOURCES.has(started.modelSource) ? started.modelSource : null,
3186
3267
  source: 'orchestrator',
3187
3268
  attributionConfidence: 'high',
3188
3269
  });