@bonesofspring/ai-rules 0.2.70 → 0.2.72
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.
- package/CHANGELOG.md +65 -0
- package/bin/lib/engine-scripts.js +9 -0
- package/docs/OPENCODE.md +4 -2
- package/docs/TEAM-DB.md +10 -7
- package/package.json +1 -1
- package/presets/_shared/ai-local/scripts/aggregate-agent-task-metrics.mjs +201 -0
- package/presets/_shared/ai-local/scripts/incidents.mjs +452 -0
- package/presets/_shared/ai-local/scripts/record-usage.mjs +163 -0
- package/presets/_shared/ai-local/scripts/team-db-api.mjs +4 -4
- package/presets/_shared/ai-local/scripts/team-db-project.mjs +2 -0
- package/presets/_shared/ai-local/scripts/verification.mjs +374 -0
- package/presets/_shared/core/agent-team/agent-task-metrics.md +61 -1
- package/presets/_shared/core/agent-team/agent-team-orchestrator.md +5 -4
- package/presets/_shared/core/agent-team/incident-registry.md +47 -0
- package/presets/_shared/core/architecture/feature-delivery-workflow.md +1 -1
- package/presets/_shared/hooks/chain-team-phases.sh.tmpl +108 -1
- package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/go/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/go/rules/architecture/feature-delivery.md +1 -1
- package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/ios-swift/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/ios-swift/rules/architecture/feature-delivery.md +1 -1
- package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/java/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/java/rules/architecture/feature-delivery.md +1 -1
- package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/mcp-ts/rules/architecture/feature-delivery.md +1 -1
- package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/mol/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/mol/rules/architecture/feature-delivery-workflow.md +1 -1
- package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/next/agents/README.md +4 -3
- package/presets/claude/next/agents/api-contract-reviewer.md +1 -1
- package/presets/claude/next/agents/mockup-reviewer.md +1 -1
- package/presets/claude/next/agents/task-router.md +4 -4
- package/presets/claude/next/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/next/rules/architecture/feature-delivery-workflow.md +2 -2
- package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/nuxt/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/nuxt/rules/architecture/feature-delivery-workflow.md +1 -1
- package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/php-hexagonal/rules/architecture/feature-delivery.md +1 -1
- package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/php-laravel/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/php-laravel/rules/architecture/feature-delivery.md +1 -1
- package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/claude/svelte/hooks/chain-team-phases.sh +108 -1
- package/presets/claude/svelte/rules/architecture/feature-delivery-workflow.md +1 -1
- package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
- package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/go/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/go/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/java/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/java/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/mol/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/mol/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/next/agents/README.md +4 -3
- package/presets/cursor/next/agents/api-contract-reviewer.md +1 -1
- package/presets/cursor/next/agents/mockup-reviewer.md +1 -1
- package/presets/cursor/next/agents/task-router.md +4 -4
- package/presets/cursor/next/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/next/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/next/rules/feature-delivery-workflow.mdc +1 -1
- package/presets/cursor/nuxt/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/cursor/svelte/hooks/chain-team-phases.sh +108 -1
- package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +1 -1
- package/presets/mavis/android-kotlin/adapter-map.json +1 -1
- package/presets/mavis/android-kotlin/agents/README.md +3 -3
- package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/go/adapter-map.json +1 -1
- package/presets/mavis/go/agents/README.md +2 -2
- package/presets/mavis/go/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/go/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/go/rules/feature-delivery-workflow.md +1 -1
- package/presets/mavis/ios-swift/adapter-map.json +1 -1
- package/presets/mavis/ios-swift/agents/README.md +3 -3
- package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/ios-swift/rules/feature-delivery-workflow.md +1 -1
- package/presets/mavis/java/adapter-map.json +1 -1
- package/presets/mavis/java/agents/README.md +2 -2
- package/presets/mavis/java/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/java/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/java/rules/feature-delivery-workflow.md +1 -1
- package/presets/mavis/mcp-ts/adapter-map.json +1 -1
- package/presets/mavis/mcp-ts/agents/README.md +1 -1
- package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/mcp-ts/rules/feature-delivery-workflow.md +1 -1
- package/presets/mavis/mol/adapter-map.json +1 -1
- package/presets/mavis/mol/agents/README.md +3 -3
- package/presets/mavis/mol/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/mol/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/mol/rules/feature-delivery-workflow.md +1 -1
- package/presets/mavis/next/adapter-map.json +1 -1
- package/presets/mavis/next/agents/README.md +3 -3
- package/presets/mavis/next/agents/task-router.md +4 -4
- package/presets/mavis/next/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/next/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/next/rules/feature-delivery-workflow.md +2 -2
- package/presets/mavis/nuxt/adapter-map.json +1 -1
- package/presets/mavis/nuxt/agents/README.md +3 -3
- package/presets/mavis/nuxt/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/nuxt/rules/feature-delivery-workflow.md +1 -1
- package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
- package/presets/mavis/php-hexagonal/agents/README.md +2 -2
- package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
- package/presets/mavis/php-laravel/adapter-map.json +1 -1
- package/presets/mavis/php-laravel/agents/README.md +2 -2
- package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/php-laravel/rules/feature-delivery-workflow.md +1 -1
- package/presets/mavis/svelte/adapter-map.json +1 -1
- package/presets/mavis/svelte/agents/README.md +3 -3
- package/presets/mavis/svelte/hooks/chain-team-phases.sh +108 -1
- package/presets/mavis/svelte/rules/agent-team-orchestrator.md +5 -4
- package/presets/mavis/svelte/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/android-kotlin/adapter-map.json +1 -1
- package/presets/opencode/android-kotlin/agents/README.md +4 -4
- package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/go/adapter-map.json +1 -1
- package/presets/opencode/go/agents/README.md +3 -3
- package/presets/opencode/go/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/go/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/go/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/ios-swift/adapter-map.json +1 -1
- package/presets/opencode/ios-swift/agents/README.md +4 -4
- package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/ios-swift/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/java/adapter-map.json +1 -1
- package/presets/opencode/java/agents/README.md +3 -3
- package/presets/opencode/java/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/java/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/java/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/mcp-ts/adapter-map.json +1 -1
- package/presets/opencode/mcp-ts/agents/README.md +2 -2
- package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/mcp-ts/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/mol/adapter-map.json +1 -1
- package/presets/opencode/mol/agents/README.md +4 -4
- package/presets/opencode/mol/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/mol/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/mol/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/next/adapter-map.json +1 -1
- package/presets/opencode/next/agents/README.md +4 -4
- package/presets/opencode/next/agents/task-router.md +4 -4
- package/presets/opencode/next/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/next/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/next/rules/feature-delivery-workflow.md +2 -2
- package/presets/opencode/nuxt/adapter-map.json +1 -1
- package/presets/opencode/nuxt/agents/README.md +4 -4
- package/presets/opencode/nuxt/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/nuxt/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
- package/presets/opencode/php-hexagonal/agents/README.md +3 -3
- package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/php-laravel/adapter-map.json +1 -1
- package/presets/opencode/php-laravel/agents/README.md +3 -3
- package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/php-laravel/rules/feature-delivery-workflow.md +1 -1
- package/presets/opencode/plugins/output-guard/README.md +25 -4
- package/presets/opencode/plugins/output-guard/index.ts +57 -11
- package/presets/opencode/plugins/output-guard/rewrite.ts +104 -1
- package/presets/opencode/svelte/adapter-map.json +1 -1
- package/presets/opencode/svelte/agents/README.md +4 -4
- package/presets/opencode/svelte/hooks/chain-team-phases.sh +108 -1
- package/presets/opencode/svelte/rules/agent-team-orchestrator.md +5 -4
- package/presets/opencode/svelte/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/android-kotlin/adapter-map.json +1 -1
- package/presets/zcode/android-kotlin/agents/README.md +3 -3
- package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/go/adapter-map.json +1 -1
- package/presets/zcode/go/agents/README.md +2 -2
- package/presets/zcode/go/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/go/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/go/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/ios-swift/adapter-map.json +1 -1
- package/presets/zcode/ios-swift/agents/README.md +3 -3
- package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/ios-swift/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/java/adapter-map.json +1 -1
- package/presets/zcode/java/agents/README.md +2 -2
- package/presets/zcode/java/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/java/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/java/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/mcp-ts/adapter-map.json +1 -1
- package/presets/zcode/mcp-ts/agents/README.md +1 -1
- package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/mcp-ts/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/mol/adapter-map.json +1 -1
- package/presets/zcode/mol/agents/README.md +3 -3
- package/presets/zcode/mol/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/mol/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/mol/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/next/adapter-map.json +1 -1
- package/presets/zcode/next/agents/README.md +3 -3
- package/presets/zcode/next/agents/task-router.md +4 -4
- package/presets/zcode/next/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/next/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/next/rules/feature-delivery-workflow.md +2 -2
- package/presets/zcode/nuxt/adapter-map.json +1 -1
- package/presets/zcode/nuxt/agents/README.md +3 -3
- package/presets/zcode/nuxt/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/nuxt/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
- package/presets/zcode/php-hexagonal/agents/README.md +2 -2
- package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/php-laravel/adapter-map.json +1 -1
- package/presets/zcode/php-laravel/agents/README.md +2 -2
- package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/php-laravel/rules/feature-delivery-workflow.md +1 -1
- package/presets/zcode/svelte/adapter-map.json +1 -1
- package/presets/zcode/svelte/agents/README.md +3 -3
- package/presets/zcode/svelte/hooks/chain-team-phases.sh +108 -1
- package/presets/zcode/svelte/rules/agent-team-orchestrator.md +5 -4
- package/presets/zcode/svelte/rules/feature-delivery-workflow.md +1 -1
- package/scripts/aggregate-agent-task-metrics.mjs +201 -0
- package/scripts/report-context-cost.mjs +126 -0
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Append-only incident registry for agent-pipeline failures.
|
|
4
|
+
*
|
|
5
|
+
* The registry is the promotion path between a one-off task finding and a
|
|
6
|
+
* durable rule: an incident is recorded once, `check` reports the same failure
|
|
7
|
+
* class recurring at least twice inside a 30-day window, and only a stabilized
|
|
8
|
+
* incident can be promoted — with a named enforcement (CI, test, lint, or a
|
|
9
|
+
* policy check). Promotion writes an inactive draft into
|
|
10
|
+
* `.ai.local/rules-library/`; a human moves it into `.ai.local/rules/` to
|
|
11
|
+
* activate it.
|
|
12
|
+
*
|
|
13
|
+
* Storage: `<team>/incidents.jsonl` (one JSON record per line, append-only).
|
|
14
|
+
* Secrets are rejected, never stored.
|
|
15
|
+
*
|
|
16
|
+
* Usage:
|
|
17
|
+
* node .ai.local/scripts/incidents.mjs record --title <t> --scope <s> \
|
|
18
|
+
* --failure <f> --rule <r> --evidence <ref> [--evidence <ref>] \
|
|
19
|
+
* [--task <slug>] [--tags a,b] [--advice <text>] [--json]
|
|
20
|
+
* node .ai.local/scripts/incidents.mjs list [--state open|stabilized|promoted|archived] [--json]
|
|
21
|
+
* node .ai.local/scripts/incidents.mjs check [--window-days 30] [--json]
|
|
22
|
+
* node .ai.local/scripts/incidents.mjs promote <id> --enforcement <ci|test|lint|policy-check> \
|
|
23
|
+
* [--stem <kebab>] [--json]
|
|
24
|
+
* node .ai.local/scripts/incidents.mjs advise --query <text> [--limit 3] [--json]
|
|
25
|
+
* node .ai.local/scripts/incidents.mjs archive <id> [--json]
|
|
26
|
+
*
|
|
27
|
+
* Exit codes: 0 ok, 1 store/write failure, 2 usage or threshold violation.
|
|
28
|
+
*/
|
|
29
|
+
import crypto from 'node:crypto';
|
|
30
|
+
import fs from 'node:fs';
|
|
31
|
+
import path from 'node:path';
|
|
32
|
+
import { fileURLToPath } from 'node:url';
|
|
33
|
+
|
|
34
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
35
|
+
const DEFAULT_TEAM_ROOT = path.resolve(here, '..', 'team');
|
|
36
|
+
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
37
|
+
const STATES = new Set(['open', 'stabilized', 'promoted', 'archived']);
|
|
38
|
+
const ENFORCEMENT = new Set(['ci', 'test', 'lint', 'policy-check']);
|
|
39
|
+
const DEFAULT_WINDOW_DAYS = 30;
|
|
40
|
+
const STABILIZE_THRESHOLD = 2;
|
|
41
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
42
|
+
|
|
43
|
+
const CAPS = {
|
|
44
|
+
title: 120,
|
|
45
|
+
scope: 40,
|
|
46
|
+
failure: 500,
|
|
47
|
+
rule: 300,
|
|
48
|
+
evidence: 300,
|
|
49
|
+
advice: 500,
|
|
50
|
+
task: 80,
|
|
51
|
+
tag: 32,
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const SECRET_RE =
|
|
55
|
+
/(-----BEGIN [A-Z ]+PRIVATE KEY-----|authorization:\s*bearer\s+[A-Za-z0-9._-]{10,}|(?:api[_-]?key|token|secret|password)\s*[:=]\s*\S{8,})/i;
|
|
56
|
+
|
|
57
|
+
const fail = (message, code = 2) => {
|
|
58
|
+
process.stderr.write(`incidents: ${message}\n`);
|
|
59
|
+
process.exit(code);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const FLAGS = new Set(['--json']);
|
|
63
|
+
const VALUED = new Set([
|
|
64
|
+
'--title',
|
|
65
|
+
'--scope',
|
|
66
|
+
'--failure',
|
|
67
|
+
'--rule',
|
|
68
|
+
'--evidence',
|
|
69
|
+
'--task',
|
|
70
|
+
'--tags',
|
|
71
|
+
'--advice',
|
|
72
|
+
'--state',
|
|
73
|
+
'--query',
|
|
74
|
+
'--limit',
|
|
75
|
+
'--window-days',
|
|
76
|
+
'--enforcement',
|
|
77
|
+
'--stem',
|
|
78
|
+
'--team-root',
|
|
79
|
+
]);
|
|
80
|
+
const REPEATABLE = new Set(['--evidence']);
|
|
81
|
+
|
|
82
|
+
const readArgs = (argv) => {
|
|
83
|
+
const args = { evidence: [] };
|
|
84
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
85
|
+
const key = argv[index];
|
|
86
|
+
if (key === '--help' || key === '-h') {
|
|
87
|
+
process.stdout.write(
|
|
88
|
+
'Usage: incidents.mjs <record|list|check|promote|advise|archive> [--json]\n',
|
|
89
|
+
);
|
|
90
|
+
process.exit(0);
|
|
91
|
+
}
|
|
92
|
+
if (FLAGS.has(key)) {
|
|
93
|
+
args[key.slice(2)] = true;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (!VALUED.has(key)) fail(`unknown argument ${key}`);
|
|
97
|
+
const value = argv[index + 1];
|
|
98
|
+
if (value === undefined) fail(`missing value for ${key}`);
|
|
99
|
+
const name = key.slice(2);
|
|
100
|
+
if (REPEATABLE.has(key)) args.evidence.push(value);
|
|
101
|
+
else if (args[name] !== undefined) fail(`duplicate argument ${key}`);
|
|
102
|
+
else args[name] = value;
|
|
103
|
+
index += 1;
|
|
104
|
+
}
|
|
105
|
+
return args;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const teamRootFor = (args) => (args['team-root'] ? path.resolve(args['team-root']) : DEFAULT_TEAM_ROOT);
|
|
109
|
+
const storePath = (teamRoot) => path.join(teamRoot, 'incidents.jsonl');
|
|
110
|
+
const nowIso = () => new Date().toISOString();
|
|
111
|
+
const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
|
|
112
|
+
|
|
113
|
+
const clean = (value, cap, name) => {
|
|
114
|
+
const text = String(value ?? '')
|
|
115
|
+
.replace(/[\r\n\t]+/g, ' ')
|
|
116
|
+
.replace(/\s{2,}/g, ' ')
|
|
117
|
+
.trim();
|
|
118
|
+
if (text === '') fail(`${name} must be a non-empty string`);
|
|
119
|
+
if (text.length > cap) fail(`${name} exceeds ${cap} characters`);
|
|
120
|
+
if (SECRET_RE.test(text)) fail(`${name} looks like it carries a secret; store a redacted value`);
|
|
121
|
+
return text;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const readStore = (teamRoot) => {
|
|
125
|
+
const file = storePath(teamRoot);
|
|
126
|
+
if (!fs.existsSync(file)) return [];
|
|
127
|
+
const records = [];
|
|
128
|
+
for (const [index, line] of fs.readFileSync(file, 'utf8').split('\n').entries()) {
|
|
129
|
+
if (line.trim() === '') continue;
|
|
130
|
+
try {
|
|
131
|
+
const record = JSON.parse(line);
|
|
132
|
+
if (record && typeof record === 'object' && typeof record.type === 'string') records.push(record);
|
|
133
|
+
} catch {
|
|
134
|
+
fail(`malformed record at ${file}:${index + 1}`, 1);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return records;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const appendStore = (teamRoot, record) => {
|
|
141
|
+
fs.mkdirSync(teamRoot, { recursive: true });
|
|
142
|
+
fs.appendFileSync(storePath(teamRoot), `${JSON.stringify(record)}\n`);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const signatureFor = ({ scope, failure, rule }) => {
|
|
146
|
+
const normalized = `${scope}|${failure}|${rule}`.toLowerCase().replace(/[^a-z0-9|]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
147
|
+
return sha256(normalized).slice(0, 12);
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Fold the append-only ledger into current incidents. `state` lines override
|
|
152
|
+
* the incident's own state; occurrence count is always derived from incident
|
|
153
|
+
* records inside the window, never stored.
|
|
154
|
+
*/
|
|
155
|
+
const derive = (records) => {
|
|
156
|
+
const incidents = new Map();
|
|
157
|
+
const stateLines = new Map();
|
|
158
|
+
for (const record of records) {
|
|
159
|
+
if (record.type === 'incident' && typeof record.id === 'string') {
|
|
160
|
+
incidents.set(record.id, { ...record, state: 'open' });
|
|
161
|
+
} else if (record.type === 'state' && typeof record.id === 'string') {
|
|
162
|
+
stateLines.set(record.id, record);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
for (const [id, line] of stateLines) {
|
|
166
|
+
const incident = incidents.get(id);
|
|
167
|
+
if (!incident) continue;
|
|
168
|
+
incident.state = typeof line.state === 'string' ? line.state : incident.state;
|
|
169
|
+
if (typeof line.enforcement === 'string') incident.enforcement = line.enforcement;
|
|
170
|
+
if (typeof line.rulePath === 'string') incident.rulePath = line.rulePath;
|
|
171
|
+
incident.stateAt = line.at;
|
|
172
|
+
}
|
|
173
|
+
return incidents;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
const recurring = (incidents, { windowDays = DEFAULT_WINDOW_DAYS, now = Date.now() } = {}) => {
|
|
177
|
+
const groups = new Map();
|
|
178
|
+
for (const incident of incidents.values()) {
|
|
179
|
+
if (typeof incident.signature !== 'string') continue;
|
|
180
|
+
const at = Date.parse(incident.at ?? '');
|
|
181
|
+
if (!Number.isFinite(at) || now - at > windowDays * DAY_MS) continue;
|
|
182
|
+
const group = groups.get(incident.signature) ?? [];
|
|
183
|
+
group.push(incident);
|
|
184
|
+
groups.set(incident.signature, group);
|
|
185
|
+
}
|
|
186
|
+
const report = [];
|
|
187
|
+
for (const [signature, group] of groups) {
|
|
188
|
+
const ordered = [...group].sort((left, right) => Date.parse(left.at) - Date.parse(right.at));
|
|
189
|
+
const stabilized = ordered.length >= STABILIZE_THRESHOLD;
|
|
190
|
+
report.push({
|
|
191
|
+
signature,
|
|
192
|
+
occurrences: ordered.length,
|
|
193
|
+
firstAt: ordered[0].at,
|
|
194
|
+
lastAt: ordered[ordered.length - 1].at,
|
|
195
|
+
incidentIds: ordered.map((item) => item.id),
|
|
196
|
+
stabilized,
|
|
197
|
+
promoted: ordered.some((item) => item.state === 'promoted'),
|
|
198
|
+
windowDays,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return report.sort((left, right) => right.occurrences - left.occurrences);
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const kebab = (value) =>
|
|
205
|
+
String(value)
|
|
206
|
+
.toLowerCase()
|
|
207
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
208
|
+
.replace(/^-+|-+$/g, '')
|
|
209
|
+
.slice(0, 40)
|
|
210
|
+
.replace(/-+$/g, '');
|
|
211
|
+
|
|
212
|
+
const print = (args, value, human) => {
|
|
213
|
+
process.stdout.write(args.json ? `${JSON.stringify(value)}\n` : `${human}\n`);
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
const actionRecord = (args) => {
|
|
217
|
+
const teamRoot = teamRootFor(args);
|
|
218
|
+
const title = clean(args.title, CAPS.title, '--title');
|
|
219
|
+
const scope = clean(args.scope, CAPS.scope, '--scope');
|
|
220
|
+
const failure = clean(args.failure, CAPS.failure, '--failure');
|
|
221
|
+
const rule = clean(args.rule, CAPS.rule, '--rule');
|
|
222
|
+
const advice = args.advice === undefined ? null : clean(args.advice, CAPS.advice, '--advice');
|
|
223
|
+
const task = args.task === undefined ? null : clean(args.task, CAPS.task, '--task');
|
|
224
|
+
if (task !== null && !SLUG_RE.test(task)) fail('--task must be a kebab-case slug');
|
|
225
|
+
if (args.evidence.length === 0) fail('at least one --evidence <ref> is required');
|
|
226
|
+
const evidence = args.evidence.map((value) => clean(value, CAPS.evidence, '--evidence'));
|
|
227
|
+
const tags = (args.tags ?? '')
|
|
228
|
+
.split(',')
|
|
229
|
+
.map((tag) => tag.trim())
|
|
230
|
+
.filter((tag) => tag !== '');
|
|
231
|
+
if (tags.some((tag) => !SLUG_RE.test(tag) || tag.length > CAPS.tag)) fail('--tags must be comma-separated kebab-case tags');
|
|
232
|
+
|
|
233
|
+
const signature = signatureFor({ scope, failure, rule });
|
|
234
|
+
const records = readStore(teamRoot);
|
|
235
|
+
const incidents = derive(records);
|
|
236
|
+
const duplicate = [...incidents.values()].find(
|
|
237
|
+
(incident) =>
|
|
238
|
+
incident.signature === signature &&
|
|
239
|
+
incident.task === task &&
|
|
240
|
+
Date.now() - Date.parse(incident.at ?? '') < DAY_MS,
|
|
241
|
+
);
|
|
242
|
+
if (duplicate) {
|
|
243
|
+
print(args, { ok: true, duplicate: true, id: duplicate.id, signature }, `incidents: duplicate of ${duplicate.id}`);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const at = nowIso();
|
|
248
|
+
const idBase = `inc-${at.slice(0, 10).replace(/-/g, '')}-${signature.slice(0, 6)}`;
|
|
249
|
+
const sameClass = [...incidents.values()].filter(
|
|
250
|
+
(incident) => incident.signature === signature && incident.id.startsWith(idBase),
|
|
251
|
+
).length;
|
|
252
|
+
const id = sameClass === 0 ? idBase : `${idBase}-${sameClass + 1}`;
|
|
253
|
+
const record = {
|
|
254
|
+
type: 'incident',
|
|
255
|
+
id,
|
|
256
|
+
at,
|
|
257
|
+
signature,
|
|
258
|
+
state: 'open',
|
|
259
|
+
title,
|
|
260
|
+
scope,
|
|
261
|
+
failure,
|
|
262
|
+
rule,
|
|
263
|
+
advice,
|
|
264
|
+
task,
|
|
265
|
+
tags,
|
|
266
|
+
evidence,
|
|
267
|
+
};
|
|
268
|
+
appendStore(teamRoot, record);
|
|
269
|
+
print(args, { ok: true, id, signature, state: 'open' }, `incidents: recorded ${id} (signature ${signature})`);
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const actionList = (args) => {
|
|
273
|
+
const teamRoot = teamRootFor(args);
|
|
274
|
+
const incidents = [...derive(readStore(teamRoot)).values()];
|
|
275
|
+
const filter = args.state ?? null;
|
|
276
|
+
if (filter !== null && !STATES.has(filter)) fail(`--state must be one of ${[...STATES].join('|')}`);
|
|
277
|
+
const filtered = filter === null ? incidents : incidents.filter((incident) => incident.state === filter);
|
|
278
|
+
if (args.json) {
|
|
279
|
+
process.stdout.write(`${JSON.stringify({ incidents: filtered })}\n`);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (filtered.length === 0) {
|
|
283
|
+
process.stdout.write('incidents: none\n');
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
for (const incident of filtered) {
|
|
287
|
+
process.stdout.write(`${incident.id} [${incident.state}] ${incident.title}\n`);
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
const actionCheck = (args) => {
|
|
292
|
+
const teamRoot = teamRootFor(args);
|
|
293
|
+
const windowDays = args['window-days'] === undefined ? DEFAULT_WINDOW_DAYS : Number(args['window-days']);
|
|
294
|
+
if (!Number.isInteger(windowDays) || windowDays <= 0) fail('--window-days must be a positive integer');
|
|
295
|
+
const incidents = derive(readStore(teamRoot));
|
|
296
|
+
const report = recurring(incidents, { windowDays });
|
|
297
|
+
if (args.json) {
|
|
298
|
+
process.stdout.write(`${JSON.stringify({ windowDays, threshold: STABILIZE_THRESHOLD, groups: report })}\n`);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (report.length === 0) {
|
|
302
|
+
process.stdout.write(`incidents: no recurrence in ${windowDays} days\n`);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
for (const group of report) {
|
|
306
|
+
const status = group.stabilized ? (group.promoted ? 'promoted' : 'stabilized') : 'open';
|
|
307
|
+
process.stdout.write(
|
|
308
|
+
`${group.signature} [${status}] ${group.occurrences}/${STABILIZE_THRESHOLD} in ${windowDays}d: ${group.incidentIds.join(', ')}\n`,
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
const actionPromote = (args) => {
|
|
314
|
+
const teamRoot = teamRootFor(args);
|
|
315
|
+
const id = args.id;
|
|
316
|
+
if (!id) fail('promote needs an incident id');
|
|
317
|
+
const enforcement = args.enforcement;
|
|
318
|
+
if (!enforcement || !ENFORCEMENT.has(enforcement)) fail(`--enforcement must be one of ${[...ENFORCEMENT].join('|')}`);
|
|
319
|
+
const incidents = derive(readStore(teamRoot));
|
|
320
|
+
const incident = incidents.get(id);
|
|
321
|
+
if (!incident) fail(`unknown incident ${id}`, 2);
|
|
322
|
+
if (incident.state === 'archived') fail(`incident ${id} is archived`, 2);
|
|
323
|
+
if (incident.state === 'promoted') fail(`incident ${id} is already promoted`, 2);
|
|
324
|
+
const groups = recurring(incidents);
|
|
325
|
+
const group = groups.find((entry) => entry.signature === incident.signature);
|
|
326
|
+
if (!group || !group.stabilized) {
|
|
327
|
+
fail(
|
|
328
|
+
`incident ${id} is not stabilized: ${group?.occurrences ?? 1} occurrence(s) in ${DEFAULT_WINDOW_DAYS} days, ${STABILIZE_THRESHOLD} required`,
|
|
329
|
+
2,
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
const stem = args.stem === undefined ? kebab(incident.title) : args.stem;
|
|
333
|
+
if (!SLUG_RE.test(stem) || stem.length > 40) fail('--stem must be kebab-case (<=40 chars)');
|
|
334
|
+
const libraryDir = path.join(teamRoot, '..', 'rules-library');
|
|
335
|
+
fs.mkdirSync(libraryDir, { recursive: true });
|
|
336
|
+
const rulePath = path.join(libraryDir, `${stem}.md`);
|
|
337
|
+
if (fs.existsSync(rulePath)) fail(`rules-library/${stem}.md already exists; pick --stem`, 2);
|
|
338
|
+
const body = [
|
|
339
|
+
'---',
|
|
340
|
+
`id: incident-${incident.id}`,
|
|
341
|
+
'source: incident-registry',
|
|
342
|
+
'status: draft',
|
|
343
|
+
`created: ${nowIso().slice(0, 10)}`,
|
|
344
|
+
'---',
|
|
345
|
+
'',
|
|
346
|
+
`# ${incident.title}`,
|
|
347
|
+
'',
|
|
348
|
+
`Scope: ${incident.scope}`,
|
|
349
|
+
`Failure: ${incident.failure}`,
|
|
350
|
+
`Rule: ${incident.rule}`,
|
|
351
|
+
`Enforcement: ${enforcement}`,
|
|
352
|
+
`Incidents: ${group.incidentIds.join(', ')} (${group.occurrences} in ${DEFAULT_WINDOW_DAYS} days)`,
|
|
353
|
+
`Evidence: ${incident.evidence.join('; ')}`,
|
|
354
|
+
...(incident.advice ? [`Advice: ${incident.advice}`] : []),
|
|
355
|
+
'',
|
|
356
|
+
'<!-- Draft staged from the incident registry. Move into .ai.local/rules/ to activate. -->',
|
|
357
|
+
'',
|
|
358
|
+
].join('\n');
|
|
359
|
+
fs.writeFileSync(rulePath, body);
|
|
360
|
+
appendStore(teamRoot, {
|
|
361
|
+
type: 'state',
|
|
362
|
+
id,
|
|
363
|
+
at: nowIso(),
|
|
364
|
+
state: 'promoted',
|
|
365
|
+
enforcement,
|
|
366
|
+
rulePath: path.posix.join('.ai.local', 'rules-library', `${stem}.md`),
|
|
367
|
+
});
|
|
368
|
+
print(
|
|
369
|
+
args,
|
|
370
|
+
{ ok: true, id, state: 'promoted', enforcement, rulePath: path.posix.join('.ai.local', 'rules-library', `${stem}.md`) },
|
|
371
|
+
`incidents: promoted ${id} -> .ai.local/rules-library/${stem}.md (${enforcement})`,
|
|
372
|
+
);
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
const actionAdvise = (args) => {
|
|
376
|
+
const teamRoot = teamRootFor(args);
|
|
377
|
+
const query = String(args.query ?? '').trim().toLowerCase();
|
|
378
|
+
if (query === '') fail('--query is required');
|
|
379
|
+
const limit = args.limit === undefined ? 3 : Number(args.limit);
|
|
380
|
+
if (!Number.isInteger(limit) || limit <= 0) fail('--limit must be a positive integer');
|
|
381
|
+
const incidents = derive(readStore(teamRoot));
|
|
382
|
+
const report = recurring(incidents);
|
|
383
|
+
const words = query.split(/\s+/).filter((word) => word.length >= 3);
|
|
384
|
+
const scored = [];
|
|
385
|
+
for (const incident of incidents.values()) {
|
|
386
|
+
if (incident.state === 'archived') continue;
|
|
387
|
+
const haystack = [incident.title, incident.scope, incident.failure, incident.rule, incident.advice, ...(incident.tags ?? [])]
|
|
388
|
+
.filter((value) => typeof value === 'string')
|
|
389
|
+
.join(' ')
|
|
390
|
+
.toLowerCase();
|
|
391
|
+
const tags = new Set((incident.tags ?? []).map((tag) => tag.toLowerCase()));
|
|
392
|
+
let score = 0;
|
|
393
|
+
for (const word of words) {
|
|
394
|
+
if (tags.has(word)) score += 3;
|
|
395
|
+
else if (haystack.includes(word)) score += 1;
|
|
396
|
+
}
|
|
397
|
+
if (score === 0) continue;
|
|
398
|
+
const group = report.find((entry) => entry.signature === incident.signature);
|
|
399
|
+
scored.push({
|
|
400
|
+
score,
|
|
401
|
+
id: incident.id,
|
|
402
|
+
title: incident.title,
|
|
403
|
+
state: incident.state,
|
|
404
|
+
rule: incident.rule,
|
|
405
|
+
advice: incident.advice,
|
|
406
|
+
occurrences: group?.occurrences ?? 1,
|
|
407
|
+
stabilized: Boolean(group?.stabilized),
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
scored.sort((left, right) => right.score - left.score || right.occurrences - left.occurrences);
|
|
411
|
+
const matches = scored.slice(0, limit);
|
|
412
|
+
if (args.json) {
|
|
413
|
+
process.stdout.write(`${JSON.stringify({ query, matches })}\n`);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (matches.length === 0) {
|
|
417
|
+
process.stdout.write(`incidents: no match for "${args.query}"\n`);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
for (const match of matches) {
|
|
421
|
+
process.stdout.write(
|
|
422
|
+
`${match.id} [${match.state}] ${match.title}\n rule: ${match.rule}${match.advice ? `\n advice: ${match.advice}` : ''}\n`,
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
const actionArchive = (args) => {
|
|
428
|
+
const teamRoot = teamRootFor(args);
|
|
429
|
+
const id = args.id;
|
|
430
|
+
if (!id) fail('archive needs an incident id');
|
|
431
|
+
const incidents = derive(readStore(teamRoot));
|
|
432
|
+
if (!incidents.has(id)) fail(`unknown incident ${id}`, 2);
|
|
433
|
+
appendStore(teamRoot, { type: 'state', id, at: nowIso(), state: 'archived' });
|
|
434
|
+
print(args, { ok: true, id, state: 'archived' }, `incidents: archived ${id}`);
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
const main = () => {
|
|
438
|
+
const [action, ...rest] = process.argv.slice(2);
|
|
439
|
+
const takesId = action === 'promote' || action === 'archive';
|
|
440
|
+
const id = takesId && rest[0] && !rest[0].startsWith('--') ? rest.shift() : undefined;
|
|
441
|
+
const args = readArgs(rest);
|
|
442
|
+
if (takesId) args.id = id;
|
|
443
|
+
if (action === 'record') actionRecord(args);
|
|
444
|
+
else if (action === 'list') actionList(args);
|
|
445
|
+
else if (action === 'check') actionCheck(args);
|
|
446
|
+
else if (action === 'promote') actionPromote(args);
|
|
447
|
+
else if (action === 'advise') actionAdvise(args);
|
|
448
|
+
else if (action === 'archive') actionArchive(args);
|
|
449
|
+
else fail(`unknown action ${action ?? '(none)'}; use record|list|check|promote|advise|archive`);
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
main();
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Append one token-usage event to a task's metrics ledger.
|
|
4
|
+
*
|
|
5
|
+
* The runtime does not always expose token counts; when the host does, record
|
|
6
|
+
* them next to the attempt so the retro can report tokens per attempt instead
|
|
7
|
+
* of only duration. The same `usage` object is forwarded by the chain hook when
|
|
8
|
+
* it arrives in the hook input.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* node .ai.local/scripts/record-usage.mjs --task <slug|dir> --attempt <attemptId> \
|
|
12
|
+
* --input <n> --output <n> [--cached <n>] [--cache-write <n>] [--reasoning <n>] \
|
|
13
|
+
* [--turn <turnId>] [--model <id>] [--json]
|
|
14
|
+
*
|
|
15
|
+
* Exit codes: 0 recorded, 2 usage/validation, 1 write failure.
|
|
16
|
+
*/
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import crypto from 'node:crypto'
|
|
20
|
+
import { fileURLToPath } from 'node:url'
|
|
21
|
+
|
|
22
|
+
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
23
|
+
const TEAM_ROOT = path.resolve(here, '..', 'team')
|
|
24
|
+
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
25
|
+
|
|
26
|
+
const fail = (message, code = 2) => {
|
|
27
|
+
process.stderr.write(`record-usage: ${message}\n`)
|
|
28
|
+
process.exit(code)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const readArgs = (argv) => {
|
|
32
|
+
const args = {}
|
|
33
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
34
|
+
const key = argv[index]
|
|
35
|
+
if (key === '--json') {
|
|
36
|
+
args.json = true
|
|
37
|
+
continue
|
|
38
|
+
}
|
|
39
|
+
if (
|
|
40
|
+
!['--task', '--attempt', '--input', '--output', '--cached', '--cache-write', '--reasoning', '--turn', '--model'].includes(
|
|
41
|
+
key,
|
|
42
|
+
)
|
|
43
|
+
) {
|
|
44
|
+
fail(`unknown argument ${key}`)
|
|
45
|
+
}
|
|
46
|
+
const value = argv[index + 1]
|
|
47
|
+
if (value === undefined) fail(`missing value for ${key}`)
|
|
48
|
+
args[key.slice(2)] = value
|
|
49
|
+
index += 1
|
|
50
|
+
}
|
|
51
|
+
return args
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const positiveInt = (value, name) => {
|
|
55
|
+
const number = Number(value)
|
|
56
|
+
if (!Number.isInteger(number) || number < 0) fail(`${name} must be a non-negative integer`)
|
|
57
|
+
return number
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const nonEmpty = (value, name) => {
|
|
61
|
+
const text = String(value ?? '').trim()
|
|
62
|
+
if (text === '') fail(`${name} must be a non-empty string`)
|
|
63
|
+
return text
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const lockPath = (metricsPath) => `${metricsPath}.lock`
|
|
67
|
+
|
|
68
|
+
const acquire = (metricsPath) => {
|
|
69
|
+
const lock = lockPath(metricsPath)
|
|
70
|
+
for (let attempt = 0; attempt < 50; attempt += 1) {
|
|
71
|
+
try {
|
|
72
|
+
const fd = fs.openSync(lock, 'wx')
|
|
73
|
+
fs.writeSync(fd, `${process.pid}:${Date.now()}`)
|
|
74
|
+
fs.closeSync(fd)
|
|
75
|
+
return () => {
|
|
76
|
+
try {
|
|
77
|
+
fs.unlinkSync(lock)
|
|
78
|
+
} catch {
|
|
79
|
+
// another writer already released it
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error.code !== 'EEXIST') fail(`cannot lock metrics.json: ${error.message}`, 1)
|
|
84
|
+
let stale = false
|
|
85
|
+
try {
|
|
86
|
+
stale = Date.now() - fs.statSync(lock).mtimeMs > 30_000
|
|
87
|
+
} catch {
|
|
88
|
+
// lock vanished; retry
|
|
89
|
+
}
|
|
90
|
+
if (stale) {
|
|
91
|
+
try {
|
|
92
|
+
fs.unlinkSync(lock)
|
|
93
|
+
} catch {
|
|
94
|
+
// another writer reclaimed it
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const until = Date.now() + 10
|
|
98
|
+
while (Date.now() < until) {
|
|
99
|
+
// tiny backoff; the hook uses the same 10 ms cap
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
fail('metrics lock timeout', 1)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const main = () => {
|
|
107
|
+
const args = readArgs(process.argv.slice(2))
|
|
108
|
+
if (!args.task || !args.attempt || args.input === undefined || args.output === undefined) {
|
|
109
|
+
fail('--task, --attempt, --input and --output are required')
|
|
110
|
+
}
|
|
111
|
+
const taskDir = path.isAbsolute(args.task)
|
|
112
|
+
? args.task
|
|
113
|
+
: SLUG_RE.test(args.task)
|
|
114
|
+
? path.join(TEAM_ROOT, 'tasks', args.task)
|
|
115
|
+
: path.resolve(args.task)
|
|
116
|
+
const metricsPath = path.join(taskDir, 'metrics.json')
|
|
117
|
+
let metrics
|
|
118
|
+
try {
|
|
119
|
+
metrics = JSON.parse(fs.readFileSync(metricsPath, 'utf8'))
|
|
120
|
+
} catch (error) {
|
|
121
|
+
fail(`cannot read ${metricsPath}: ${error.message}`, 1)
|
|
122
|
+
}
|
|
123
|
+
if (!Array.isArray(metrics.events)) fail('metrics.json has no events array', 1)
|
|
124
|
+
const turn = args.turn === undefined ? null : nonEmpty(args.turn, '--turn')
|
|
125
|
+
const cacheWrite = args['cache-write'] === undefined ? null : positiveInt(args['cache-write'], '--cache-write')
|
|
126
|
+
const reasoning = args.reasoning === undefined ? null : positiveInt(args.reasoning, '--reasoning')
|
|
127
|
+
const attempt = metrics.events.find(
|
|
128
|
+
(event) => event.attemptId === args.attempt && ['attempt_started', 'attempt_finished'].includes(event.type),
|
|
129
|
+
)
|
|
130
|
+
if (!attempt) fail(`attempt ${args.attempt} is not in the ledger`, 1)
|
|
131
|
+
|
|
132
|
+
const release = acquire(metricsPath)
|
|
133
|
+
try {
|
|
134
|
+
const event = {
|
|
135
|
+
eventId: `${metrics.task?.runId ?? 'run'}:usage:${Date.now()}:${crypto.randomBytes(4).toString('hex')}`,
|
|
136
|
+
type: 'usage_recorded',
|
|
137
|
+
at: new Date().toISOString(),
|
|
138
|
+
attemptId: args.attempt,
|
|
139
|
+
turn,
|
|
140
|
+
model: args.model ?? null,
|
|
141
|
+
input: positiveInt(args.input, '--input'),
|
|
142
|
+
output: positiveInt(args.output, '--output'),
|
|
143
|
+
cached: args.cached === undefined ? null : positiveInt(args.cached, '--cached'),
|
|
144
|
+
cacheWrite,
|
|
145
|
+
reasoning,
|
|
146
|
+
}
|
|
147
|
+
metrics.events.push(event)
|
|
148
|
+
const temporary = `${metricsPath}.${process.pid}.tmp`
|
|
149
|
+
fs.writeFileSync(temporary, `${JSON.stringify(metrics, null, 2)}\n`)
|
|
150
|
+
fs.renameSync(temporary, metricsPath)
|
|
151
|
+
if (args.json) {
|
|
152
|
+
process.stdout.write(`${JSON.stringify(event)}\n`)
|
|
153
|
+
} else {
|
|
154
|
+
process.stdout.write(
|
|
155
|
+
`record-usage: ${args.attempt} input=${event.input} output=${event.output} cached=${event.cached ?? '-'} cacheWrite=${event.cacheWrite ?? '-'} reasoning=${event.reasoning ?? '-'} turn=${event.turn ?? '-'} model=${event.model ?? '-'}\n`,
|
|
156
|
+
)
|
|
157
|
+
}
|
|
158
|
+
} finally {
|
|
159
|
+
release()
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
main()
|
|
@@ -1897,7 +1897,7 @@ const deleteJob = async (context) => {
|
|
|
1897
1897
|
});
|
|
1898
1898
|
if (result.ok !== true) {
|
|
1899
1899
|
const code = typeof result.code === 'string' ? result.code : 'E_INTERNAL';
|
|
1900
|
-
fail(mapTeamDbCode(code), mapTeamDbCode(code, true), String(result.message ?? `
|
|
1900
|
+
fail(mapTeamDbCode(code), mapTeamDbCode(code, true), String(result.message ?? `removing ${id} was refused`));
|
|
1901
1901
|
}
|
|
1902
1902
|
return { json: { ok: true, id: String(result.id ?? id), runsRemoved: Number(result.runsRemoved ?? 0) } };
|
|
1903
1903
|
};
|
|
@@ -1984,17 +1984,17 @@ const runDeleteChild = async (slug, context) => {
|
|
|
1984
1984
|
const parsed = await runTeamDbChild(['delete', '--slug', slug], {
|
|
1985
1985
|
settings: context.settings,
|
|
1986
1986
|
timeoutMs: SYNC_CHILD_TIMEOUT_MS,
|
|
1987
|
-
label: `
|
|
1987
|
+
label: `removal of ${slug}`,
|
|
1988
1988
|
});
|
|
1989
1989
|
if (parsed.ok === false) {
|
|
1990
1990
|
const code = typeof parsed.code === 'string' ? parsed.code : 'E_INTERNAL';
|
|
1991
1991
|
// The guard fires only when the target is the active slug, so the detail
|
|
1992
1992
|
// names it exactly; the message the child printed names it too.
|
|
1993
1993
|
const details = code === 'E_ACTIVE_TASK' ? { activeSlug: slug } : undefined;
|
|
1994
|
-
fail(mapTeamDbCode(code), mapTeamDbCode(code, true), String(parsed.message ?? `
|
|
1994
|
+
fail(mapTeamDbCode(code), mapTeamDbCode(code, true), String(parsed.message ?? `removing ${slug} was refused`), details);
|
|
1995
1995
|
}
|
|
1996
1996
|
if (parsed.ok !== true || typeof parsed.slug !== 'string') {
|
|
1997
|
-
fail('E_INTERNAL', 500, `
|
|
1997
|
+
fail('E_INTERNAL', 500, `removing ${slug} reported neither a success nor a documented refusal`);
|
|
1998
1998
|
}
|
|
1999
1999
|
return { slug: parsed.slug };
|
|
2000
2000
|
};
|