@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
@@ -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 = 'php-laravel';
201
212
  const PLATFORM = 'opencode';
213
+ if (slugSource === 'TEAM_TASK_SLUG' && sessionId) writeSessionLease(sessionId, slug);
202
214
 
203
215
  let metricsLockToken = null;
204
216
  function readMetricsLockToken() {
@@ -495,6 +507,7 @@ function reclaimStaleAttempts(scope) {
495
507
  type: 'attempt_finished',
496
508
  at: now,
497
509
  attemptId,
510
+ ...closingExecution(entry, Array.isArray(steps) ? steps[entry.stepIndex] : null),
498
511
  stepIndex: entry.stepIndex,
499
512
  stepLabel: (Array.isArray(steps) && steps[entry.stepIndex] && steps[entry.stepIndex].label) || null,
500
513
  agent: entry.agent,
@@ -561,6 +574,59 @@ function saveWriteScopeBaseline(step) {
561
574
  .split('\n').map((line) => line.trim()).filter(Boolean)[0] || `exit ${result ? result.status : 'unknown'}`;
562
575
  process.stderr.write(`[chain-team-phases] ${slug}: write-scope baseline for step ${stepId} not saved (${reason}); the audit will skip that step.\n`);
563
576
  }
577
+ const MODEL_TIERS = new Set(['cheap', 'standard', 'strong']);
578
+ const MODEL_SOURCES = new Set(['host', 'lease', 'tier-map', 'session']);
579
+ function boundedModel(value) {
580
+ if (typeof value !== 'string') return null;
581
+ const text = value.trim();
582
+ return /^[A-Za-z0-9][A-Za-z0-9._:@/#-]{0,119}$/.test(text) ? text : null;
583
+ }
584
+ function readTierMapModel(tier) {
585
+ try {
586
+ const parsed = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'model-tiers.json'), 'utf8'));
587
+ const tiers = parsed && parsed.tiers;
588
+ if (!tiers || typeof tiers !== 'object') return null;
589
+ const approvedBy = typeof parsed.approvedBy === 'string' ? parsed.approvedBy.trim() : '';
590
+ const filled = ['cheap', 'standard', 'strong'].some((key) => typeof tiers[key] === 'string' && tiers[key].trim() !== '');
591
+ if (approvedBy === '' && !filled) return null;
592
+ return boundedModel(tiers[tier]);
593
+ } catch {
594
+ return null;
595
+ }
596
+ }
597
+ function observedModel() {
598
+ const execution = hookInput && hookInput.execution;
599
+ if (execution && typeof execution === 'object') {
600
+ const model = boundedModel(execution.model);
601
+ if (model) return { model, modelSource: MODEL_SOURCES.has(execution.modelSource) ? execution.modelSource : 'host' };
602
+ }
603
+ const direct = boundedModel(hookInput && hookInput.model);
604
+ return direct ? { model: direct, modelSource: 'host' } : null;
605
+ }
606
+ function leaseModel() {
607
+ if (!sessionId) return null;
608
+ const lease = readSessionLease(sessionId);
609
+ if (!lease || lease.tool !== PLATFORM) return null;
610
+ const model = boundedModel(lease.model);
611
+ return model ? { model, modelSource: 'lease' } : null;
612
+ }
613
+ function executionForStep(step) {
614
+ const modelTier = step && MODEL_TIERS.has(step.model) ? step.model : null;
615
+ const observed = observedModel() || leaseModel();
616
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
617
+ const mapped = modelTier ? readTierMapModel(modelTier) : null;
618
+ if (mapped) return { tool: PLATFORM, modelTier, model: mapped, modelSource: 'tier-map' };
619
+ return { tool: PLATFORM, modelTier, model: null, modelSource: null };
620
+ }
621
+ function closingExecution(entry, step) {
622
+ const model = boundedModel(entry && entry.model);
623
+ const armedTier = entry && MODEL_TIERS.has(entry.modelTier) ? entry.modelTier : null;
624
+ const armedSource = model && entry && MODEL_SOURCES.has(entry.modelSource) ? entry.modelSource : null;
625
+ const observed = observedModel();
626
+ const modelTier = (step && MODEL_TIERS.has(step.model) ? step.model : null) || armedTier;
627
+ if (observed) return { tool: PLATFORM, modelTier, model: observed.model, modelSource: observed.modelSource };
628
+ return { tool: PLATFORM, modelTier, model, modelSource: model ? armedSource : null };
629
+ }
564
630
  function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null) {
565
631
  const agents = Array.isArray(agentsOverride) && agentsOverride.length > 0 ? agentsOverride : getStepAgents(step);
566
632
  const parallelGroupId = step.parallel && getStepAgents(step).length > 1 ? `${status.metricsRunId || slug}:step-${stepIndex}` : null;
@@ -570,8 +636,9 @@ function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null)
570
636
  const attempt = nextAttemptOrdinal(stepIndex, agent); const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
571
637
  status.metricsRunId = runId; const attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
572
638
  if (active[attemptId]) continue;
573
- active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null };
574
- 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' });
639
+ const execution = executionForStep(step);
640
+ active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null, ...execution };
641
+ 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 });
575
642
  }
576
643
  status.activeAttempts = active;
577
644
  saveWriteScopeBaseline(step);
@@ -1575,10 +1642,12 @@ function finishActiveAttempt(forced) {
1575
1642
  const idleMs = wallMs === null ? null : Math.max(0, wallMs - (activeMs ?? 0));
1576
1643
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
1577
1644
  const usage = sanitizeUsage(hookInput.usage);
1645
+ const execution = closingExecution(resolved.entry, Array.isArray(steps) ? steps[resolved.entry.stepIndex] : null);
1578
1646
  appendMetric({
1579
1647
  type: 'attempt_finished',
1580
1648
  at: now,
1581
1649
  attemptId: resolved.attemptId,
1650
+ ...execution,
1582
1651
  stepIndex: typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : null,
1583
1652
  agent: resolved.entry.agent || null,
1584
1653
  outcome,
@@ -2924,9 +2993,10 @@ function armResumedAttempt(step, stepIndex, agent) {
2924
2993
  0,
2925
2994
  ) + 1;
2926
2995
  attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
2996
+ const execution = executionForStep(step);
2927
2997
  status.activeAttempts = {
2928
2998
  ...(status.activeAttempts || {}),
2929
- [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null },
2999
+ [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null, ...execution },
2930
3000
  };
2931
3001
  events.push({
2932
3002
  eventId: `${runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,
@@ -2942,6 +3012,7 @@ function armResumedAttempt(step, stepIndex, agent) {
2942
3012
  waveId: null,
2943
3013
  source: 'hook',
2944
3014
  attributionConfidence: 'high',
3015
+ ...execution,
2945
3016
  });
2946
3017
  });
2947
3018
  return attemptId;
@@ -3117,12 +3188,17 @@ if (hookInput.action === 'out_of_band_start') {
3117
3188
  const agent = typeof hookInput.agent === 'string' ? hookInput.agent : 'unknown';
3118
3189
  const reason = typeof hookInput.reason === 'string' ? hookInput.reason : null;
3119
3190
  const outOfBandId = `${status.metricsRunId || slug}:oob:${Date.now()}:${Math.random().toString(16).slice(2, 8)}`;
3191
+ const observed = observedModel();
3120
3192
  appendMetric({
3121
3193
  type: 'out_of_band_started',
3122
3194
  outOfBandId,
3123
3195
  agent,
3124
3196
  reason,
3125
3197
  at: now,
3198
+ tool: PLATFORM,
3199
+ modelTier: null,
3200
+ model: observed ? observed.model : null,
3201
+ modelSource: observed ? observed.modelSource : null,
3126
3202
  source: 'orchestrator',
3127
3203
  attributionConfidence: 'high',
3128
3204
  });
@@ -3157,6 +3233,7 @@ if (hookInput.action === 'out_of_band_end') {
3157
3233
  }
3158
3234
  const durationMs = Math.max(0, Date.parse(now) - Date.parse(started.at));
3159
3235
  const outcome = typeof hookInput.outcome === 'string' ? hookInput.outcome : 'completed';
3236
+ const finishedModel = boundedModel(started.model);
3160
3237
  appendMetric({
3161
3238
  type: 'out_of_band_finished',
3162
3239
  outOfBandId: started.outOfBandId,
@@ -3165,6 +3242,10 @@ if (hookInput.action === 'out_of_band_end') {
3165
3242
  outcome,
3166
3243
  durationMs,
3167
3244
  at: now,
3245
+ tool: PLATFORM,
3246
+ modelTier: MODEL_TIERS.has(started.modelTier) ? started.modelTier : null,
3247
+ model: finishedModel,
3248
+ modelSource: finishedModel && MODEL_SOURCES.has(started.modelSource) ? started.modelSource : null,
3168
3249
  source: 'orchestrator',
3169
3250
  attributionConfidence: 'high',
3170
3251
  });
@@ -13,7 +13,7 @@ call; persisted history is untouched.
13
13
  | Item | Value |
14
14
  |---|---|
15
15
  | Trigger | `tool-result` text over **8192 B** (`AI_RULES_OUTPUT_GUARD_BYTES`) |
16
- | Tools | `shell`, `bash`, `read`, `grep`, `glob`, `webfetch` — a `read` of `.opencode/rules/**` or `.ai.local/rules/**` is never replaced |
16
+ | Tools | every named tool. A `read` of `.opencode/rules/**` or `.ai.local/rules/**` is never replaced. A result with no tool name is left alone |
17
17
  | Replacement (8–20 KB band) | structured head + tail: named elision, top-level JSON keys that sit in the gap, a `grep -n '<term>'` hint for a whole-line gap that carries a usable term, or `tail -c` when a line is cut mid-way |
18
18
  | Replacement (over 20 KB) | 40-line / 2 KB head + 15-line / 1 KB tail + path + hints |
19
19
  | Shape override | `AI_RULES_OUTPUT_GUARD_SHAPE=flat` forces the legacy renderer in the band |
@@ -40,8 +40,9 @@ adds a `[json: full document at the path]` note so the agent can `jq` the file.
40
40
 
41
41
  ## Ledgers
42
42
 
43
- All four files live in `.ai.local/team/output-guard/`. None but `results.jsonl`
44
- and `usage.jsonl` rotate.
43
+ All four files live in `.ai.local/team/output-guard/`. `results.jsonl`,
44
+ `usage.jsonl`, and `stats.jsonl` rotate once when the plugin starts.
45
+ `context.jsonl` does not: the dedupe set is seeded from the file.
45
46
 
46
47
  | File | Row | Written when |
47
48
  |---|---|---|
@@ -19,7 +19,9 @@
19
19
  *
20
20
  * Telemetry beside the guard: `usage.jsonl` reads the token rows of the session
21
21
  * and of the child sessions it discovers, and `context.jsonl` keeps one row per
22
- * `(sessionID, toolset)` for the MCP schema split. Neither rotates. Child
22
+ * `(sessionID, toolset)` for the MCP schema split. `results.jsonl`, `usage.jsonl`,
23
+ * and `stats.jsonl` rotate once in `setup()`. `context.jsonl` does not: its
24
+ * dedupe set is seeded from the file. Child
23
25
  * discovery starts after the rewrite, is never awaited, and stops being waited
24
26
  * for at AI_RULES_OUTPUT_GUARD_DISCOVERY_MS (default 250 ms); it cannot be
25
27
  * cancelled.
@@ -51,7 +53,6 @@ const MAX_TRACKED_SESSIONS = 12
51
53
  const DEFAULT_DISCOVERY_MS = 250
52
54
  /** The bound on every timing map; a late `after` must not grow a session's heap. */
53
55
  const MAX_TIMING_ENTRIES = 256
54
- const ALLOWLIST = new Set(["shell", "bash", "read", "grep", "glob", "webfetch"])
55
56
 
56
57
  const findTeamRoot = (start: string): string | null => {
57
58
  let dir = path.resolve(start)
@@ -304,7 +305,6 @@ export default Plugin.define({
304
305
  tailBytes: TAIL_BYTES,
305
306
  headLines: HEAD_LINES,
306
307
  tailLines: TAIL_LINES,
307
- allowlist: ALLOWLIST,
308
308
  marker: MARKER,
309
309
  shape: process.env.AI_RULES_OUTPUT_GUARD_SHAPE === "flat" ? ("flat" as const) : ("structured" as const),
310
310
  }
@@ -318,6 +318,7 @@ export default Plugin.define({
318
318
  const rotateBytes = parseRotateBytes(process.env[ROTATE_BYTES_ENV])
319
319
  rotateLedger(path.join(outputDir, "results.jsonl"), rotateBytes)
320
320
  rotateLedger(path.join(outputDir, "usage.jsonl"), rotateBytes)
321
+ rotateLedger(path.join(outputDir, "stats.jsonl"), rotateBytes)
321
322
  const projectRoot = path.resolve(root, "..", "..")
322
323
  const savedPaths = new Map<string, string>()
323
324
  const statsRecorded = new Set<string>()
@@ -12,7 +12,6 @@ export type OutputGuardOptions = {
12
12
  tailBytes: number
13
13
  headLines: number
14
14
  tailLines: number
15
- allowlist: ReadonlySet<string>
16
15
  marker: string
17
16
  /** `"flat"` forces the legacy renderer inside the band; default is structured. */
18
17
  shape?: "flat" | "structured"
@@ -268,7 +267,7 @@ export function rewriteMessages(
268
267
  for (const item of content as ToolResult[]) {
269
268
  if (item?.type !== "tool-result") continue
270
269
  const tool = typeof item.name === "string" ? item.name : ""
271
- if (tool === "" || !options.allowlist.has(tool)) continue
270
+ if (tool === "") continue
272
271
  const result = item.result
273
272
  if (result?.type !== "text" || typeof result.value !== "string") continue
274
273
  const value = result.value
@@ -23,7 +23,7 @@ to a plugin.
23
23
  | Dedupe | per `(sessionID, stem)`, and the marker in the assembled messages wins over the in-memory set |
24
24
  | Budget | `MAX_ATTACH_LINES = 420` non-empty lines per attach — the largest `check-next-attached-budget.mjs` fixture cap. A stem that does not fit is skipped, never truncated |
25
25
  | Kill switch | `AI_RULES_RULE_ATTACH=0` |
26
- | Debug | `AI_RULES_RULE_ATTACH_DEBUG=1` → `.ai.local/team/output-guard/debug.log` |
26
+ | Debug | `AI_RULES_RULE_ATTACH_DEBUG=1` → `.ai.local/team/output-guard/rule-attach.log`. A skipped stem (already attached, unreadable, over the line cap) is logged there and is not injected |
27
27
  | Host | OpenCode V2 with `ctx.session.hook`; a host without it no-ops |
28
28
 
29
29
  Injects text only: no shell, no `child_process`, nothing the model wrote is
@@ -9,7 +9,7 @@
9
9
  * Three bounds, all in `attach.ts`: only a stem whose glob matches a touched
10
10
  * path is attached, each stem once per session, and the bodies stay inside the
11
11
  * line budget. `AI_RULES_RULE_ATTACH=0` disables the plugin; debug output goes
12
- * to `.ai.local/team/output-guard/debug.log` through `AI_RULES_RULE_ATTACH_DEBUG=1`.
12
+ * to `.ai.local/team/output-guard/rule-attach.log` through `AI_RULES_RULE_ATTACH_DEBUG=1`.
13
13
  *
14
14
  * Injected text is a trailing user message carrying `[ai-rules rule-attach]`
15
15
  * and the rule body. It carries text only — no shell, no `child_process`, and
@@ -95,17 +95,30 @@ const carries = (messages: unknown, stem: string): boolean => {
95
95
  return false
96
96
  }
97
97
 
98
+ const MAX_ATTACHED_SESSIONS = 32
99
+
98
100
  const debugLog = (projectRoot: string, message: string): void => {
99
101
  if (process.env.AI_RULES_RULE_ATTACH_DEBUG !== "1") return
100
102
  try {
101
103
  const dir = path.join(projectRoot, ".ai.local", "team", "output-guard")
102
104
  fs.mkdirSync(dir, { recursive: true })
103
- fs.appendFileSync(path.join(dir, "debug.log"), `${new Date().toISOString()} rule-attach ${message}\n`)
105
+ fs.appendFileSync(path.join(dir, "rule-attach.log"), `${new Date().toISOString()} ${message}\n`)
104
106
  } catch {
105
107
  /* an unlogged attach is still a correct attach */
106
108
  }
107
109
  }
108
110
 
111
+ /** Keep the newest sessions. A re-touch moves the id to the end of the map. */
112
+ const rememberSession = (attached: Map<string, Set<string>>, sessionID: string, stems: Set<string>): void => {
113
+ if (attached.has(sessionID)) attached.delete(sessionID)
114
+ attached.set(sessionID, stems)
115
+ while (attached.size > MAX_ATTACHED_SESSIONS) {
116
+ const oldest = attached.keys().next().value
117
+ if (oldest === undefined) break
118
+ attached.delete(oldest)
119
+ }
120
+ }
121
+
109
122
  export default Plugin.define({
110
123
  id: "ai-rules.rule-attach",
111
124
  async setup(ctx) {
@@ -147,16 +160,22 @@ export default Plugin.define({
147
160
  attached: already,
148
161
  readRule,
149
162
  })
163
+ if (plan.skipped.length > 0) {
164
+ debugLog(
165
+ projectRoot,
166
+ `skipped ${plan.skipped.map((entry) => `${entry.stem}:${entry.reason}`).join(",")} (session ${sessionID})`,
167
+ )
168
+ }
150
169
  const fresh = plan.inject.filter((entry) => !carries(record.messages, entry.stem))
151
170
  if (fresh.length === 0) return
152
- for (const entry of fresh) already.add(entry.stem)
153
- attached.set(sessionID, already)
154
171
  const messages = record.messages
155
172
  if (!Array.isArray(messages)) return
156
173
  messages.push({
157
174
  role: "user",
158
175
  content: [{ type: "text", text: fresh.map((entry) => entry.text).join("\n") }],
159
176
  })
177
+ for (const entry of fresh) already.add(entry.stem)
178
+ rememberSession(attached, sessionID, already)
160
179
  debugLog(projectRoot, `attached ${fresh.map((entry) => entry.stem).join(",")} (session ${sessionID})`)
161
180
  } catch (error) {
162
181
  debugLog(projectRoot, `attach failed: ${error instanceof Error ? error.message : String(error)}`)
@@ -10,8 +10,11 @@ The plugin imports `evaluate` from `.opencode/hooks/guard-shell-command.mjs`.
10
10
  |---|---|---|
11
11
  | `allow` on a plain `git commit` / `git push` | effect `allow` (the static ask is lifted) | no throw; the static ask remains |
12
12
  | `ask` | effect `ask`, with the guard's message | throw, so the command does not run |
13
+ | `evaluate` throws | effect `ask`, message `shell guard failed` | throw, so the command does not run |
13
14
  | `allow` on anything else | unchanged | unchanged |
14
15
 
16
+ An event whose `action` is not `shell` or `bash` is not a shell check. A missing or empty `action` is left unchanged.
17
+
15
18
  `false`, a missing file, and a broken file stay `ask`. `true` allows only a plain commit or push. Destructive, alias, and indirect shapes stay `ask`.
16
19
 
17
20
  ## Autoroute — `AI_RULES_AUTOROUTE_UNCHAINED_PROMPTS`
@@ -53,7 +53,7 @@ export default Plugin.define({
53
53
  const decision = await guard({ command }, { root: projectRoot })
54
54
  return decision && typeof decision.permission === "string" ? decision : null
55
55
  } catch {
56
- return null
56
+ return { permission: "ask", user_message: "shell guard failed" }
57
57
  }
58
58
  }
59
59
 
@@ -27,7 +27,7 @@ const firstText = (values) => {
27
27
  export const commandFromPermission = (event) => {
28
28
  const record = recordOf(event);
29
29
  const action = typeof record.action === 'string' ? record.action : '';
30
- if (action !== '' && action !== 'shell' && action !== 'bash') return null;
30
+ if (action !== 'shell' && action !== 'bash') return null;
31
31
  const fromResources = firstText(record.resources);
32
32
  if (fromResources !== null) return fromResources;
33
33
  const metadata = recordOf(record.metadata);
@@ -12,8 +12,8 @@ Modelled on the built-in MCP sidebar plugin (`packages/tui/src/feature-plugins/s
12
12
  - the step row carries a progress bar, e.g. `3/7 ███░░░░░ · attempt 1 · 3h 35m`; a parallel wave reads `3/7 ███░░░░░ · 3 agents · 42m` and clocks from the oldest start; a `status.json` written before any attempt reads `3/7 · no attempt started` instead of hiding the plan
13
13
  - the `eta` row reads `~52m · p90 3h 32m`: estimated time to finish the remaining plan steps. It hides while the run waits on a human gate, is paused, blocked, waiting for a receipt, or is done. A stale run keeps it — the estimate is historical, not live — and with fewer than 3 ledgers the row reads `—` instead of disappearing
14
14
  - clicking any row opens a details dialog with 3-cell side padding: `goal.md`, pipeline steps with the current one marked, artifacts from `artifact-manifest.json`, the last manifest entries, the prompt, the last update age and the ETA with its ledger count. The body scrolls with ↑/↓, PgUp/PgDn, Home/End or the mouse wheel; `esc` closes it.
15
- - a live task shows `■ stop` in the header; click → confirm → writes the task-scoped `.ai.local/team/tasks/<slug>/STOP` (the repo-wide `.ai.local/STOP` only when the task directory is gone). The in-flight attempt finishes, no next step starts. A task with a stop sentinel shows `▶ resume` instead: confirm clears it. Saying `/task-continue <slug>` (or `продолжай` / `continue`) in a matched session is the keyboard path. <!-- i18n-keep: E4 -->
16
- - a `DeepSeek` row under the fields reads `[peak]` in red or `[off-peak]` in green: the current DeepSeek billing window, read from the same models store as the team-tasks UI — the peak `windows` linked to the `DeepSeek` provider under the nearest `.ai.local/models` above the project directory. Window semantics are shared with the UI: a weekly window covers `[startHour, endHour)` — the end hour is exclusive — and `startHour > endHour` wraps across midnight. Without a store the row falls back to the published schedule shipped with the plugin: 09:00–12:00 and 14:00–18:00 Asia/Shanghai, Monday–Friday. Chinese public holidays are off-peak all day but are not tracked, so a holiday weekday still reads `peak` inside a window
15
+ - a live task shows `■ stop` in the header; click → confirm → writes the task-scoped `.ai.local/team/tasks/<slug>/STOP`. If that directory cannot be written, a second confirm asks before the repo-wide `.ai.local/STOP` is written. The in-flight attempt finishes, no next step starts. A task with a stop sentinel shows `▶ resume` instead: confirm clears it. Saying `/task-continue <slug>` (or `продолжай` / `continue`) in a matched session is the keyboard path. <!-- i18n-keep: E4 -->
16
+ - one `[peak]` / `[off-peak]` row for DeepSeek and Z.AI in the nearest `.ai.local/models` store (the same `providers` / `links` / `windows` records the team-tasks UI reads). Those two are the only providers with a published peak schedule, so every other provider is omitted. No store, no rows. A weekly window covers `[startHour, endHour)` — the end hour is exclusive — and `startHour > endHour` wraps across midnight. A missing or non-finite hour drops that window. Chinese public holidays are off-peak all day but are not tracked, so a holiday weekday still reads `peak` inside a window
17
17
  - a `Z.AI` row reads the same `[peak]`/`[off-peak]` for the GLM Coding Plan: the peak `windows` linked to the `Z.AI` provider in the same store (Monday–Friday 14:00–18:00 Asia/Singapore; weekends deduct at off-peak rates all day). Without a store it falls back to that published schedule. Quota consumption percentages and reset times are intentionally not shown: the plan quota is server-side and no usage API is documented
18
18
  - a stale task reads `◌ stale · 8d 17h ago` with a muted tone instead of pretending to run
19
19
  - the open flag lives in `context.storage.store("panel", { initial: { open: true } })`, so it survives restarts; the live view stays in `context.storage.memory`
@@ -21,7 +21,7 @@ Modelled on the built-in MCP sidebar plugin (`packages/tui/src/feature-plugins/s
21
21
 
22
22
  ## Data
23
23
 
24
- Reads the nearest `.ai.local/team/` above the session directory, and the provider peak windows (DeepSeek, Z.AI) from the nearest `.ai.local/models/` — the same `providers`/`links`/`windows` records `apps/team-tasks-ui` reads (`MODELS_ROOT` points at the models directory; the deprecated `CATALOG_ROOT` still works for one release):
24
+ Reads the nearest `.ai.local/team/` above the session directory, and the provider peak windows from the nearest `.ai.local/models/` — the same `providers`/`links`/`windows` records `apps/team-tasks-ui` reads (`MODELS_ROOT` points at the models directory; the deprecated `CATALOG_ROOT` still works for one release). The sidebar lists only DeepSeek and Z.AI when the store names them:
25
25
 
26
26
  - `tasks/<slug>/prompt.md` — the original prompt, the session-matching anchor
27
27
  - `tasks/<slug>/prompt-log.md` — the follow-up log, shown in the details dialog only
@@ -107,7 +107,7 @@ The sidebar is session-scoped and follows `session.sidebar.toggle` (`ctrl+x b`).
107
107
 
108
108
  ## Limits
109
109
 
110
- - The stop button writes the task-scoped `tasks/<slug>/STOP`; the repo-wide `.ai.local/STOP` is the fallback when that directory is gone and remains the operator's own pause, so it blocks new steps for every task.
110
+ - The stop button writes the task-scoped `tasks/<slug>/STOP`. The repo-wide `.ai.local/STOP` is written only after a second confirm, when the task directory cannot be written. It blocks new steps for every task.
111
111
  - The resume intent clears a task-scoped sentinel only for the session's pinned task; a repository-wide `.ai.local/STOP` is lifted only by an explicit `/task-continue <slug>`, never by a text match in an unrelated session. <!-- i18n-keep: E4 -->
112
112
  - Mapping relies on prompt text: a task without `prompt.md` cannot be matched, so its tab falls back to the prompt view. A session whose first message is not the prompt (for example a resumed tab opened with a bare `продолжай`) needs `/task-continue <slug>`. <!-- i18n-keep: E4 -->
113
113
  - With a remote server, messages come from the server but the prompt files are read from the client filesystem; a failed message fetch keeps the last view and marks it `offline` for a minute.
@@ -8,8 +8,9 @@
8
8
  * covers `[startHour, endHour)` — the end hour is exclusive, so the published
9
9
  * "14:00-18:00" schedule ends at 18:00 — and `startHour > endHour` spans
10
10
  * midnight; absolute windows match `[startAt, endAt]`. When no store is
11
- * reachable — a project that never ran the sync — the published schedule
12
- * shipped below applies unchanged.
11
+ * reachable, `billingRates` returns no rows, and only DeepSeek and Z.AI get a
12
+ * row because no other provider publishes a peak schedule. `deepseekRate` and
13
+ * `zaiRate` still fall back to the published schedule below for a direct caller.
13
14
  *
14
15
  * Chinese public holidays are off-peak all day, but a holiday calendar is not
15
16
  * shipped here, so a holiday weekday still reads `peak` inside a window.
@@ -105,14 +106,20 @@ const resolveModelsRoot = (directory: string | undefined): string | undefined =>
105
106
  return undefined
106
107
  }
107
108
 
109
+ const finiteHour = (value: number | undefined): number | null =>
110
+ typeof value === "number" && Number.isFinite(value) ? value : null
111
+
108
112
  const asPeakWindow = (window: CatalogWindow): PeakWindow | null => {
109
113
  if (window.kind !== "peak") return null
110
114
  if (window.shape === "weekly" && Array.isArray(window.weekdays)) {
115
+ const startHour = finiteHour(window.startHour)
116
+ const endHour = finiteHour(window.endHour)
117
+ if (startHour === null || endHour === null) return null
111
118
  return {
112
119
  shape: "weekly",
113
120
  weekdays: window.weekdays,
114
- startHour: window.startHour ?? 0,
115
- endHour: window.endHour ?? 0,
121
+ startHour,
122
+ endHour,
116
123
  timezone: window.timezone ?? "UTC",
117
124
  }
118
125
  }
@@ -221,7 +228,19 @@ export const deepseekRate = (now: Date, directory?: string): DeepseekRate =>
221
228
  export const zaiRate = (now: Date, directory?: string): DeepseekRate =>
222
229
  providerRate("Z.AI", now, directory)
223
230
 
224
- export const billingRates = (at: Date, directory?: string) => [
225
- { label: "DeepSeek" as const, rate: deepseekRate(at, directory) },
226
- { label: "Z.AI" as const, rate: zaiRate(at, directory) },
227
- ]
231
+ /** Providers with a published peak schedule; anyone else would always read `off-peak`. */
232
+ const BILLING_PROVIDERS = new Set(["DeepSeek", "Z.AI"])
233
+
234
+ /** DeepSeek and Z.AI rows present in the models store, in name order. No store, no rows. */
235
+ export const billingRates = (at: Date, directory?: string): Array<{ label: string; rate: ProviderRate }> => {
236
+ const root = resolveModelsRoot(directory)
237
+ if (root === undefined) return []
238
+ const names = [
239
+ ...new Set(
240
+ readRecords<CatalogProvider>(path.join(root, "providers"))
241
+ .map((provider) => provider?.name)
242
+ .filter((name): name is string => typeof name === "string" && BILLING_PROVIDERS.has(name)),
243
+ ),
244
+ ].sort((left, right) => left.localeCompare(right))
245
+ return names.map((label) => ({ label, rate: providerRate(label, at, directory) }))
246
+ }
@@ -252,14 +252,18 @@ const pauseStartedAt = (root: string, slug: string | undefined, scope: PauseScop
252
252
  .sort((left, right) => left - right)[0]
253
253
  }
254
254
 
255
- /** The scope actually written, or `null` when no sentinel could be written. */
256
- export const engagePause = (root: string, slug?: string): PauseScope | null => {
257
- if (slug) {
255
+ /**
256
+ * The scope actually written, or `null` when nothing was written.
257
+ * A slug writes only the task sentinel. The repository sentinel is written
258
+ * when `scope` is `"repo"`, which the sidebar does after a second confirm.
259
+ */
260
+ export const engagePause = (root: string, slug?: string, scope?: PauseScope): PauseScope | null => {
261
+ if (scope !== "repo" && slug) {
258
262
  try {
259
263
  fs.writeFileSync(taskSentinel(root, slug), pausePayload("task"), "utf8")
260
264
  return "task"
261
265
  } catch {
262
- // A task directory can disappear under a stale view; fall back to the repo sentinel.
266
+ return null
263
267
  }
264
268
  }
265
269
  const overlay = overlayDir(root)
@@ -52,12 +52,21 @@ const TaskSidebar = () => {
52
52
  label: { confirm: "Stop", cancel: "Cancel" },
53
53
  })
54
54
  if (!confirmed) return
55
- const written = engagePause(view.root, view.slug)
55
+ let written = engagePause(view.root, view.slug)
56
56
  if (!written) {
57
- context.ui.toast.show({ title: "Task", message: "Cannot write .ai.local/STOP", variant: "error" })
57
+ const confirmedRepo = await context.ui.dialog.confirm({
58
+ title: "Stop repository",
59
+ message: `The ${view.slug} task directory is not writable. Write a repository-wide stop?`,
60
+ label: { confirm: "Stop repository", cancel: "Cancel" },
61
+ })
62
+ if (!confirmedRepo) return
63
+ written = engagePause(view.root, view.slug, "repo")
64
+ }
65
+ if (!written) {
66
+ context.ui.toast.show({ title: "Task", message: "Cannot write the stop sentinel", variant: "error" })
58
67
  return
59
68
  }
60
- const where = written === "repo" ? `repository-wide (the ${view.slug} task dir was unwritable)` : `for ${view.slug}`
69
+ const where = written === "repo" ? "repository-wide" : `for ${view.slug}`
61
70
  context.ui.toast.show({ title: "Task", message: `Soft stop engaged ${where}`, variant: "warning" })
62
71
  }
63
72
 
@@ -3,7 +3,7 @@
3
3
  "platform": "opencode",
4
4
  "stack": "svelte",
5
5
  "semanticSource": "cursor/svelte",
6
- "sourceRevision": "0ee4bc76f8ae9c99addaee8e5a1b99985d8965e58991c447caea624973d52bd7",
6
+ "sourceRevision": "645efc03569bae44b124b827b7a52c981820f26082bd5f6b011b135cdc5c42ef",
7
7
  "entries": [
8
8
  {
9
9
  "source": "AGENTS.md",