oc-harness-setup 0.3.3 → 0.4.1

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 (136) hide show
  1. package/.docs/unwired-routing.md +16 -15
  2. package/AGENTS.md +105 -68
  3. package/CHANGELOG.md +107 -0
  4. package/GLOSSARY.md +46 -0
  5. package/LICENSE +1 -1
  6. package/README.md +49 -60
  7. package/agents/cleaner.md +86 -0
  8. package/agents/critic.md +79 -0
  9. package/agents/historian.md +92 -0
  10. package/agents/maintainer.md +106 -0
  11. package/agents/ops.md +69 -0
  12. package/agents/orchestrator.md +48 -18
  13. package/agents/researcher.md +72 -0
  14. package/agents/verifier.md +84 -0
  15. package/agents/worker.md +87 -0
  16. package/bin/cli.js +360 -133
  17. package/commands/close.md +11 -0
  18. package/commands/evolve.md +11 -0
  19. package/commands/fast.md +11 -0
  20. package/commands/goal.md +11 -0
  21. package/commands/search.md +11 -0
  22. package/commands/swarm.md +11 -0
  23. package/opencode.jsonc +39 -79
  24. package/package.json +13 -6
  25. package/reference/README.md +12 -14
  26. package/reference/canon.md +71 -0
  27. package/reference/context.md +35 -0
  28. package/reference/enforcement.md +6 -0
  29. package/reference/flow.md +19 -0
  30. package/reference/gates.md +23 -0
  31. package/reference/harness.md +15 -0
  32. package/reference/hygiene.md +13 -0
  33. package/reference/memory.md +13 -0
  34. package/reference/models.md +19 -24
  35. package/reference/phases.md +23 -0
  36. package/reference/repos.md +49 -0
  37. package/reference/tools.md +35 -0
  38. package/scripts/harness-doctor.ps1 +83 -0
  39. package/skills/close/SKILL.md +36 -0
  40. package/skills/evolve/SKILL.md +76 -0
  41. package/skills/fast/SKILL.md +36 -0
  42. package/skills/goal/SKILL.md +65 -0
  43. package/skills/search/SKILL.md +68 -0
  44. package/skills/swarm/SKILL.md +69 -0
  45. package/state-seed/lessons.md +22 -0
  46. package/state-seed/template.md +12 -0
  47. package/agents/build.md +0 -20
  48. package/agents/explore.md +0 -26
  49. package/agents/general.md +0 -19
  50. package/agents/plan.md +0 -29
  51. package/agents/reviewer.md +0 -22
  52. package/agents/vault.md +0 -73
  53. package/commands/build.md +0 -7
  54. package/commands/checkpoint.md +0 -7
  55. package/commands/code-simplify.md +0 -7
  56. package/commands/gauntlet.md +0 -7
  57. package/commands/handoff.md +0 -7
  58. package/commands/keeper.md +0 -7
  59. package/commands/kill.md +0 -11
  60. package/commands/plan.md +0 -7
  61. package/commands/retro.md +0 -15
  62. package/commands/review.md +0 -7
  63. package/commands/ship.md +0 -7
  64. package/commands/spec.md +0 -7
  65. package/commands/test.md +0 -7
  66. package/commands/webperf.md +0 -7
  67. package/reference/auto-mandate.md +0 -11
  68. package/reference/backup-convention.md +0 -9
  69. package/reference/clean-mandate.md +0 -13
  70. package/reference/editor-parity.md +0 -7
  71. package/reference/gc-scripts.md +0 -8
  72. package/reference/intent-routing.md +0 -14
  73. package/reference/lifecycle.md +0 -15
  74. package/reference/model-keeper.md +0 -46
  75. package/reference/model-test.md +0 -176
  76. package/reference/oc-source-map.md +0 -162
  77. package/reference/owner-pin.md +0 -31
  78. package/reference/roster.md +0 -15
  79. package/reference/session-scope.md +0 -9
  80. package/reference/session-state.md +0 -13
  81. package/reference/swarm.md +0 -32
  82. package/scripts/backup-config.ps1 +0 -42
  83. package/scripts/gc-branch.ps1 +0 -196
  84. package/scripts/gc-bump.ps1 +0 -198
  85. package/scripts/gc-clean.ps1 +0 -648
  86. package/scripts/gc-commit.ps1 +0 -143
  87. package/scripts/gc-merge.ps1 +0 -272
  88. package/scripts/gc-pr.ps1 +0 -190
  89. package/scripts/gc-push.ps1 +0 -111
  90. package/scripts/gc-read.ps1 +0 -150
  91. package/scripts/gc-rebase.ps1 +0 -162
  92. package/scripts/gc-release.ps1 +0 -225
  93. package/scripts/gc-stage.ps1 +0 -103
  94. package/scripts/gc-status.ps1 +0 -127
  95. package/scripts/gc-sync.ps1 +0 -65
  96. package/scripts/gc.core.ps1 +0 -715
  97. package/scripts/gc.smoke.ps1 +0 -779
  98. package/scripts/interrupt-session.ps1 +0 -65
  99. package/scripts/logbook/README.md +0 -108
  100. package/scripts/logbook/logbook.test.ts +0 -440
  101. package/scripts/logbook/logbook.ts +0 -797
  102. package/scripts/pirep/README.md +0 -147
  103. package/scripts/pirep/pirep.test.ts +0 -735
  104. package/scripts/pirep/pirep.ts +0 -836
  105. package/scripts/testflight/README.md +0 -112
  106. package/scripts/testflight/testflight.test.ts +0 -512
  107. package/scripts/testflight/testflight.ts +0 -806
  108. package/skills/_shared/SOURCES.md +0 -26
  109. package/skills/_shared/references/accessibility-checklist.md +0 -160
  110. package/skills/_shared/references/definition-of-done.md +0 -67
  111. package/skills/_shared/references/observability-checklist.md +0 -92
  112. package/skills/_shared/references/orchestration-patterns.md +0 -155
  113. package/skills/_shared/references/performance-checklist.md +0 -236
  114. package/skills/_shared/references/security-checklist.md +0 -245
  115. package/skills/_shared/references/testing-patterns.md +0 -235
  116. package/skills/api-and-interface-design/SKILL.md +0 -14
  117. package/skills/browser-testing-with-devtools/SKILL.md +0 -303
  118. package/skills/code-simplification/SKILL.md +0 -14
  119. package/skills/creative-writing/SKILL.md +0 -96
  120. package/skills/debugging-and-error-recovery/SKILL.md +0 -15
  121. package/skills/flight-deck/SKILL.md +0 -17
  122. package/skills/frontend-ui-engineering/SKILL.md +0 -16
  123. package/skills/gauntlet/SKILL.md +0 -21
  124. package/skills/git-ceremony/SKILL.md +0 -27
  125. package/skills/grilling/SKILL.md +0 -18
  126. package/skills/observability-and-instrumentation/SKILL.md +0 -18
  127. package/skills/performance-optimization/SKILL.md +0 -16
  128. package/skills/pilot-report/SKILL.md +0 -18
  129. package/skills/planning-and-task-breakdown/SKILL.md +0 -16
  130. package/skills/security-and-hardening/SKILL.md +0 -18
  131. package/skills/source-driven-development/SKILL.md +0 -16
  132. package/skills/spec-driven-development/SKILL.md +0 -26
  133. package/skills/test-driven-development/SKILL.md +0 -18
  134. package/skills/test-flight/SKILL.md +0 -14
  135. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  136. package/skills/writing-for-agents/SKILL.md +0 -89
@@ -1,836 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * pirep — which models and agents actually perform, measured from history.
4
- *
5
- * One question, answered from real OpenCode turns instead of assumptions:
6
- * which models and agents do the work, how much they process, how often
7
- * they fail, and what the metered ones cost.
8
- *
9
- * Design rules, in order of importance:
10
- *
11
- * 1. Never price an unpriced model. Subscription (limit-based, not
12
- * token-based) models record a cost of 0 with real token counts — that
13
- * zero is correct, there is no per-token bill (concrete example:
14
- * `openai/gpt-5.6-luna`). Real tokens plus zero recorded cost means
15
- * "no metered cost recorded". Metered and unpriced models are reported
16
- * in separate sections and never summed or averaged together: an
17
- * unpriced model would always look free and always "win" a cost
18
- * ranking, which is a recommendation engine confidently recommending
19
- * the wrong thing. Every cost figure that excludes unpriced turns is
20
- * labelled as partial.
21
- * 2. The host database is opened READ-ONLY and never written.
22
- * 3. Field names are read defensively, and were verified against the real
23
- * database rather than assumed. Assistant turns carry the model nested at
24
- * `model.{id,providerID,variant}`, tokens at
25
- * `tokens.{input,output,reasoning,cache.{read,write}}`, plus `cost`,
26
- * `time.{created,streamed,completed}`, `agent`, and `error`. The flat
27
- * `modelID` / `providerID` fields are kept as a fallback but appear on no
28
- * row inspected; `mode` is always null and is not read. A row that cannot
29
- * be understood is skipped and counted, never guessed at. A row with a
30
- * `time` but no `tokens` yet is a mid-stream write, not a zero-token turn,
31
- * and is skipped too.
32
- * 4. Speed is streaming speed. Output tokens-per-second is measured over
33
- * `time.streamed - time.created` — the window the model spent producing
34
- * output — and never over `time.completed - time.created`, which also
35
- * spans tool execution and would report every model as slower than it is.
36
- * Where the host recorded no stream completion the turn gets no speed
37
- * rather than a number that measures something else.
38
- * 5. Degrade quietly: a missing or unreadable database, or an unexpected
39
- * host schema, prints one clear line and exits non-zero. It never
40
- * throws a stack trace at you.
41
- *
42
- * Usage:
43
- * pirep full report: metered models, unpriced models, agents
44
- * pirep --models models only
45
- * pirep --agents agents only
46
- * pirep --since=YYYY-MM-DD only turns on or after this date
47
- * pirep --limit=N cap rows per section
48
- * pirep --json machine-readable output
49
- * pirep --help this text
50
- */
51
-
52
- import { Database } from "bun:sqlite";
53
- import { existsSync } from "node:fs";
54
- import { homedir } from "node:os";
55
- import { join } from "node:path";
56
-
57
- const HOME = homedir();
58
-
59
- /** Overridable so the suite can run against fixtures instead of your history. */
60
- const SOURCE_DB =
61
- process.env["PIREP_SOURCE"] ?? join(HOME, ".local", "share", "opencode", "opencode.db");
62
-
63
- // ---------------------------------------------------------------------------
64
- // Shapes
65
- // ---------------------------------------------------------------------------
66
-
67
- export interface Turn {
68
- readonly model: string;
69
- readonly provider: string;
70
- readonly modelId: string;
71
- readonly agent: string;
72
- readonly sessionId: string;
73
- /** Millisecond epoch. Falls back to the row's time_created when the payload carries none. */
74
- readonly ts: number;
75
- readonly input: number;
76
- readonly output: number;
77
- readonly reasoning: number;
78
- readonly cacheRead: number;
79
- readonly cacheWrite: number;
80
- readonly cost: number;
81
- /**
82
- * The turn's streaming window: `time.streamed` minus `time.created`.
83
- *
84
- * This is time the model spent producing output, which is what a
85
- * tokens-per-second figure means. It is deliberately NOT
86
- * `time.completed - time.created`, which also spans tool execution and
87
- * post-processing and would report a model as slower than it is.
88
- *
89
- * Undefined when the host recorded no stream completion — the turn is then
90
- * reported with no speed rather than given a number that measures something
91
- * else.
92
- */
93
- readonly streamMs: number | undefined;
94
- /** True when the payload carries a non-null `error` field (includes aborts/cancels). */
95
- readonly failed: boolean;
96
- }
97
-
98
- export interface ModelStat {
99
- readonly model: string;
100
- readonly provider: string;
101
- readonly id: string;
102
- readonly metered: boolean;
103
- readonly turns: number;
104
- readonly sessions: number;
105
- readonly input: number;
106
- readonly output: number;
107
- readonly reasoning: number;
108
- readonly cacheRead: number;
109
- readonly cacheWrite: number;
110
- readonly cacheHitRate: number | undefined;
111
- readonly medianTokPerSec: number | undefined;
112
- readonly totalCost: number;
113
- /** Metered models only; undefined for unpriced models (never invent a price). */
114
- readonly medianTurnCost: number | undefined;
115
- readonly failureRate: number;
116
- }
117
-
118
- export interface AgentStat {
119
- readonly agent: string;
120
- readonly turns: number;
121
- readonly sessions: number;
122
- readonly input: number;
123
- readonly output: number;
124
- readonly reasoning: number;
125
- readonly cacheRead: number;
126
- readonly cacheWrite: number;
127
- readonly cacheHitRate: number | undefined;
128
- readonly medianTokPerSec: number | undefined;
129
- /** Sum of recorded costs on metered turns only; excludes unpriced turns, so partial. */
130
- readonly meteredCostPartial: number;
131
- readonly failureRate: number;
132
- }
133
-
134
- export interface Report {
135
- readonly scanned: number;
136
- readonly skipped: number;
137
- readonly turns: number;
138
- readonly sessions: number;
139
- readonly metered: readonly ModelStat[];
140
- readonly unpriced: readonly ModelStat[];
141
- /** Sum over metered turns only. Partial by construction. */
142
- readonly totalMeteredCost: number;
143
- readonly unpricedTurns: number;
144
- readonly agents: readonly AgentStat[];
145
- }
146
-
147
- // ---------------------------------------------------------------------------
148
- // Parsing
149
- // ---------------------------------------------------------------------------
150
-
151
- /** Minimal shape checks — the host schema is not ours and must not be trusted. */
152
- function asRecord(value: unknown): Record<string, unknown> | undefined {
153
- return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : undefined;
154
- }
155
-
156
- function asText(value: unknown): string | undefined {
157
- if (typeof value !== "string") return undefined;
158
- // Untrusted host rows are text, never terminal instructions: strip C0 control
159
- // characters (including ESC) so a crafted field cannot emit an escape
160
- // sequence (e.g. OSC-52 clipboard writes) into the terminal.
161
- const cleaned = value.replace(/[\u0000-\u001f\u007f]/g, "");
162
- return cleaned.trim().length > 0 ? cleaned.trim() : undefined;
163
- }
164
-
165
- /** A finite, non-negative number, or zero. Negatives are clamped, not rejected. */
166
- function asCount(value: unknown): number {
167
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
168
- }
169
-
170
- function asMillis(value: unknown): number | undefined {
171
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
172
- }
173
-
174
- export interface TurnRow {
175
- readonly id: string;
176
- readonly session_id: string;
177
- readonly type: string;
178
- readonly time_created: number;
179
- readonly data: string;
180
- }
181
-
182
- /**
183
- * One `session_message` row becomes zero or one turns. Anything ambiguous —
184
- * bad JSON, no resolvable model, a non-assistant role — is skipped (the
185
- * caller counts it) rather than guessed at.
186
- */
187
- export function parseTurn(row: TurnRow): Turn | undefined {
188
- if (row.type !== "assistant") return undefined;
189
- let parsed: unknown;
190
- try {
191
- parsed = JSON.parse(row.data);
192
- } catch {
193
- return undefined;
194
- }
195
- const message = asRecord(parsed);
196
- if (message === undefined) return undefined;
197
-
198
- // v1 rows carry an explicit role; v2 rows omit it (the SQL type column
199
- // already filtered to assistant), so only a present non-assistant role rejects.
200
- const role = message["role"];
201
- if (role !== undefined && role !== "assistant") return undefined;
202
-
203
- // The nested `model` object is what this host writes (verified against
204
- // session_message rows). The flat v1 fields are kept as a fallback for older
205
- // rows; they are absent on every row inspected here.
206
- const nested = asRecord(message["model"]);
207
- const modelId = asText(nested?.["id"]) ?? asText(message["modelID"]);
208
- if (modelId === undefined) return undefined;
209
- const provider = asText(nested?.["providerID"]) ?? asText(message["providerID"]) ?? "unknown";
210
-
211
- // A turn with no token accounting is not a turn with zero tokens. The host
212
- // writes assistant rows mid-stream with `time` but no `tokens` yet; counting
213
- // those as zero-token turns would skew every average, so they are skipped and
214
- // counted instead.
215
- const tokens = asRecord(message["tokens"]);
216
- if (tokens === undefined) return undefined;
217
-
218
- const cache = asRecord(tokens["cache"]);
219
- const input = asCount(tokens["input"]);
220
- const output = asCount(tokens["output"]);
221
- const reasoning = asCount(tokens["reasoning"]);
222
- const cacheRead = asCount(cache?.["read"]);
223
- const cacheWrite = asCount(cache?.["write"]);
224
-
225
- const cost = asCount(message["cost"]);
226
-
227
- const time = asRecord(message["time"]);
228
- const created = asMillis(time?.["created"]) ?? asMillis(row.time_created) ?? 0;
229
- const streamed = asMillis(time?.["streamed"]);
230
- const streamMs = streamed !== undefined && streamed > created ? streamed - created : undefined;
231
-
232
- // `agent` is the field this host writes; `mode` is never populated.
233
- const agent = asText(message["agent"]) ?? "unknown";
234
- const failed = message["error"] !== undefined && message["error"] !== null;
235
-
236
- return {
237
- model: `${provider}/${modelId}`,
238
- provider,
239
- modelId,
240
- agent,
241
- sessionId: row.session_id,
242
- ts: created,
243
- input,
244
- output,
245
- reasoning,
246
- cacheRead,
247
- cacheWrite,
248
- cost,
249
- streamMs,
250
- failed,
251
- };
252
- }
253
-
254
- /** Median of a set of samples; undefined when there is nothing to summarise. */
255
- export function median(values: readonly number[]): number | undefined {
256
- if (values.length === 0) return undefined;
257
- const sorted = [...values].sort((a, b) => a - b);
258
- const mid = Math.floor(sorted.length / 2);
259
- if (sorted.length % 2 === 1) return sorted[mid];
260
- const lo = sorted[mid - 1] ?? 0;
261
- const hi = sorted[mid] ?? 0;
262
- return (lo + hi) / 2;
263
- }
264
-
265
- /** Cache hit rate, the same definition `opencode stats` uses: read / (read + input). */
266
- export function cacheHitRate(read: number, input: number): number | undefined {
267
- return read + input > 0 ? read / (read + input) : undefined;
268
- }
269
-
270
- /** Output speed for one turn, measured over its streaming window. */
271
- export function turnTokPerSec(turn: Turn): number | undefined {
272
- if (turn.streamMs === undefined || turn.streamMs <= 0 || turn.output <= 0) return undefined;
273
- return turn.output / (turn.streamMs / 1000);
274
- }
275
-
276
- // ---------------------------------------------------------------------------
277
- // Collection and aggregation
278
- // ---------------------------------------------------------------------------
279
-
280
- export function collectTurns(
281
- source: Database,
282
- sinceMs?: number,
283
- ): { turns: Turn[]; scanned: number; skipped: number } {
284
- const turns: Turn[] = [];
285
- let scanned = 0;
286
- let skipped = 0;
287
- const consume = (row: TurnRow): void => {
288
- scanned += 1;
289
- try {
290
- const turn = parseTurn(row);
291
- if (turn === undefined) skipped += 1;
292
- else turns.push(turn);
293
- } catch {
294
- // One unreadable message must not abandon the other tens of thousands.
295
- skipped += 1;
296
- }
297
- };
298
- // `--since` is a SQL predicate, not a JS filter: with the index on
299
- // time_created this is a range scan instead of a full-table read that then
300
- // throws most rows away.
301
- if (sinceMs === undefined) {
302
- const rows = source.query<TurnRow, []>(
303
- `select id, session_id, type, time_created, data from session_message where type = 'assistant'`,
304
- );
305
- for (const row of rows.iterate()) consume(row);
306
- } else {
307
- const rows = source.query<TurnRow, [number]>(
308
- `select id, session_id, type, time_created, data from session_message where type = 'assistant' and time_created >= ?`,
309
- );
310
- for (const row of rows.iterate(sinceMs)) consume(row);
311
- }
312
- return { turns, scanned, skipped };
313
- }
314
-
315
- function statForModel(model: string, provider: string, id: string, turns: readonly Turn[]): ModelStat {
316
- const sessions = new Set(turns.map((turn) => turn.sessionId)).size;
317
- let input = 0;
318
- let output = 0;
319
- let reasoning = 0;
320
- let cacheRead = 0;
321
- let cacheWrite = 0;
322
- let failed = 0;
323
- let totalCost = 0;
324
- const speeds: number[] = [];
325
- const costs: number[] = [];
326
- for (const turn of turns) {
327
- input += turn.input;
328
- output += turn.output;
329
- reasoning += turn.reasoning;
330
- cacheRead += turn.cacheRead;
331
- cacheWrite += turn.cacheWrite;
332
- if (turn.failed) failed += 1;
333
- totalCost += turn.cost;
334
- costs.push(turn.cost);
335
- const speed = turnTokPerSec(turn);
336
- if (speed !== undefined) speeds.push(speed);
337
- }
338
- // The hard rule: any recorded cost makes the model metered; real tokens
339
- // with zero recorded cost is a subscription-style model, not a free one.
340
- const metered = totalCost > 0;
341
- return {
342
- model,
343
- provider,
344
- id,
345
- metered,
346
- turns: turns.length,
347
- sessions,
348
- input,
349
- output,
350
- reasoning,
351
- cacheRead,
352
- cacheWrite,
353
- cacheHitRate: cacheHitRate(cacheRead, input),
354
- medianTokPerSec: median(speeds),
355
- totalCost,
356
- medianTurnCost: metered ? median(costs) : undefined,
357
- failureRate: turns.length > 0 ? failed / turns.length : 0,
358
- };
359
- }
360
-
361
- function statForAgent(agent: string, turns: readonly Turn[]): AgentStat {
362
- const sessions = new Set(turns.map((turn) => turn.sessionId)).size;
363
- let input = 0;
364
- let output = 0;
365
- let reasoning = 0;
366
- let cacheRead = 0;
367
- let cacheWrite = 0;
368
- let failed = 0;
369
- let meteredCostPartial = 0;
370
- const speeds: number[] = [];
371
- for (const turn of turns) {
372
- input += turn.input;
373
- output += turn.output;
374
- reasoning += turn.reasoning;
375
- cacheRead += turn.cacheRead;
376
- cacheWrite += turn.cacheWrite;
377
- if (turn.failed) failed += 1;
378
- // Agent turns mix metered and unpriced models, so no median and no
379
- // total: only the metered slice, labelled partial.
380
- if (turn.cost > 0) meteredCostPartial += turn.cost;
381
- const speed = turnTokPerSec(turn);
382
- if (speed !== undefined) speeds.push(speed);
383
- }
384
- return {
385
- agent,
386
- turns: turns.length,
387
- sessions,
388
- input,
389
- output,
390
- reasoning,
391
- cacheRead,
392
- cacheWrite,
393
- cacheHitRate: cacheHitRate(cacheRead, input),
394
- medianTokPerSec: median(speeds),
395
- meteredCostPartial,
396
- failureRate: turns.length > 0 ? failed / turns.length : 0,
397
- };
398
- }
399
-
400
- function byTurnsDesc(a: { turns: number; model?: string; agent?: string }, b: { turns: number; model?: string; agent?: string }): number {
401
- return b.turns - a.turns || String(a.model ?? a.agent).localeCompare(String(b.model ?? b.agent));
402
- }
403
-
404
- export function aggregate(turns: readonly Turn[]): Report {
405
- const byModel = new Map<string, Turn[]>();
406
- const byAgent = new Map<string, Turn[]>();
407
- for (const turn of turns) {
408
- const models = byModel.get(turn.model);
409
- if (models === undefined) byModel.set(turn.model, [turn]);
410
- else models.push(turn);
411
- const agents = byAgent.get(turn.agent);
412
- if (agents === undefined) byAgent.set(turn.agent, [turn]);
413
- else agents.push(turn);
414
- }
415
-
416
- const metered: ModelStat[] = [];
417
- const unpriced: ModelStat[] = [];
418
- let totalMeteredCost = 0;
419
- let unpricedTurns = 0;
420
- for (const [model, modelTurns] of byModel) {
421
- const first = modelTurns[0];
422
- if (first === undefined) continue;
423
- const stat = statForModel(model, first.provider, first.modelId, modelTurns);
424
- if (stat.metered) {
425
- metered.push(stat);
426
- totalMeteredCost += stat.totalCost;
427
- } else {
428
- unpriced.push(stat);
429
- unpricedTurns += stat.turns;
430
- }
431
- }
432
- metered.sort(byTurnsDesc);
433
- unpriced.sort(byTurnsDesc);
434
-
435
- const agents: AgentStat[] = [...byAgent].map(([agent, agentTurns]) => statForAgent(agent, agentTurns));
436
- agents.sort(byTurnsDesc);
437
-
438
- return {
439
- scanned: 0,
440
- skipped: 0,
441
- turns: turns.length,
442
- sessions: new Set(turns.map((turn) => turn.sessionId)).size,
443
- metered,
444
- unpriced,
445
- totalMeteredCost,
446
- unpricedTurns,
447
- agents,
448
- };
449
- }
450
-
451
- // ---------------------------------------------------------------------------
452
- // Output
453
- // ---------------------------------------------------------------------------
454
-
455
- function fmtInt(n: number): string {
456
- return Math.round(n).toString();
457
- }
458
-
459
- function fmtCost(n: number): string {
460
- if (n === 0) return "$0";
461
- if (n >= 1) return `$${n.toFixed(2)}`;
462
- return `$${n.toFixed(4)}`;
463
- }
464
-
465
- function fmtPct(rate: number | undefined): string {
466
- return rate === undefined ? "-" : `${(rate * 100).toFixed(1)}%`;
467
- }
468
-
469
- function fmtSpeed(speed: number | undefined): string {
470
- return speed === undefined ? "-" : speed.toFixed(1);
471
- }
472
-
473
- /**
474
- * Column padding that never hides data.
475
- *
476
- * The first version sliced an over-long value down to the column width, which
477
- * silently corrupted exactly the numbers this report exists to show — a ten
478
- * digit token total came out as its last nine digits with no indication. A
479
- * column that is too narrow should look ragged, not lie.
480
- */
481
- function padEnd(text: string, width: number): string {
482
- return text.length >= width ? text : text + " ".repeat(width - text.length);
483
- }
484
-
485
- function padStart(text: string, width: number): string {
486
- return text.length >= width ? text : " ".repeat(width - text.length) + text;
487
- }
488
-
489
- /**
490
- * Token totals are abbreviated for the report (`518`, `83.2M`, `1.4B`).
491
- *
492
- * They have to be: a single model's lifetime input can run to ten digits, which
493
- * would either blow the table apart or get truncated. `--json` carries the exact
494
- * integer counts for anything that needs them.
495
- */
496
- export function fmtCount(n: number): string {
497
- const value = Math.round(n);
498
- if (value < 1_000) return String(value);
499
- // Round at each step and only stay in a unit while the rounded value fits —
500
- // 999_999 rounds to 1000k, which must promote to 1M rather than print "1000k".
501
- const thousands = Math.round(value / 1_000);
502
- if (thousands < 1_000) return `${thousands}k`;
503
- const millions = (value / 1_000_000).toFixed(1);
504
- if (Number(millions) < 1_000) {
505
- return `${millions.endsWith(".0") ? millions.slice(0, -2) : millions}M`;
506
- }
507
- const billions = (value / 1_000_000_000).toFixed(2);
508
- return `${billions.endsWith(".00") ? billions.slice(0, -3) : billions}B`;
509
- }
510
-
511
- export interface ViewOptions {
512
- readonly modelsOnly: boolean;
513
- readonly agentsOnly: boolean;
514
- readonly limit: number;
515
- readonly sinceLabel: string | undefined;
516
- }
517
-
518
- const METERING_NOTE =
519
- "metered and unpriced models are never summed or averaged together: a model with no metered cost would always look free and always win a cost ranking.";
520
- const PARTIAL_NOTE = "every cost figure excludes unpriced turns and is partial.";
521
- const SPEED_NOTE =
522
- "out-tok/s is measured over each turn's streaming window (time.streamed minus time.created), so it is model throughput and excludes tool execution; - means the host recorded no stream completion for that turn.";
523
- const COUNTS_NOTE =
524
- "token columns are abbreviated (k/M/B) so a lifetime total fits the table; --json carries the exact integers.";
525
- const FAILURE_NOTE = "failure rate counts turns with a non-null error field (includes aborts/cancels), not judged quality.";
526
-
527
- interface Column {
528
- readonly head: string;
529
- readonly width: number;
530
- /** Numbers right-align; the trailing model/agent name is left-aligned. */
531
- readonly align?: "left" | "right";
532
- }
533
-
534
- /**
535
- * One definition per table, so the header and the body cannot drift apart and no
536
- * cell is ever cut to fit. The name goes last because it is the only
537
- * variable-width field: an unexpectedly long model name then pushes outwards
538
- * instead of shoving every number out of its column.
539
- */
540
- function renderTable(columns: readonly Column[], rows: readonly (readonly string[])[]): string[] {
541
- const pad = (text: string, column: Column | undefined): string => {
542
- if (column === undefined) return text;
543
- return column.align === "left" ? padEnd(text, column.width) : padStart(text, column.width);
544
- };
545
- const line = (cells: readonly string[]) =>
546
- cells.map((value, index) => pad(value, columns[index])).join(" ").trimEnd();
547
- return [line(columns.map((column) => column.head)), ...rows.map(line)];
548
- }
549
-
550
- const MODEL_COLUMNS: readonly Column[] = [
551
- { head: "turns", width: 6 },
552
- { head: "sess", width: 5 },
553
- { head: "in", width: 7 },
554
- { head: "out", width: 7 },
555
- { head: "cache-r", width: 7 },
556
- { head: "hit%", width: 6 },
557
- { head: "tok/s", width: 6 },
558
- { head: "cost", width: 9 },
559
- { head: "med-cost", width: 9 },
560
- { head: "fail%", width: 6 },
561
- { head: "model", width: 0, align: "left" },
562
- ];
563
-
564
- const UNPRICED_MODEL_COLUMNS: readonly Column[] = MODEL_COLUMNS.filter(
565
- (column) => column.head !== "cost" && column.head !== "med-cost",
566
- );
567
-
568
- const AGENT_COLUMNS: readonly Column[] = [
569
- { head: "turns", width: 6 },
570
- { head: "sess", width: 5 },
571
- { head: "in", width: 7 },
572
- { head: "out", width: 7 },
573
- { head: "cache-r", width: 7 },
574
- { head: "hit%", width: 6 },
575
- { head: "tok/s", width: 6 },
576
- { head: "metered$*", width: 10 },
577
- { head: "fail%", width: 6 },
578
- { head: "agent", width: 0, align: "left" },
579
- ];
580
-
581
- function modelCells(stat: ModelStat, showCost: boolean): string[] {
582
- const cells = [
583
- fmtInt(stat.turns),
584
- fmtInt(stat.sessions),
585
- fmtCount(stat.input),
586
- fmtCount(stat.output),
587
- fmtCount(stat.cacheRead),
588
- fmtPct(stat.cacheHitRate),
589
- fmtSpeed(stat.medianTokPerSec),
590
- ];
591
- if (showCost) cells.push(fmtCost(stat.totalCost), fmtCost(stat.medianTurnCost ?? 0));
592
- cells.push(fmtPct(stat.failureRate), stat.model);
593
- return cells;
594
- }
595
-
596
- function modelRows(stats: readonly ModelStat[], limit: number, showCost: boolean): string[] {
597
- const columns = showCost ? MODEL_COLUMNS : UNPRICED_MODEL_COLUMNS;
598
- const rows = stats.slice(0, limit).map((stat) => modelCells(stat, showCost));
599
- return renderTable(columns, rows.length > 0 ? rows : [["(none)"]]);
600
- }
601
-
602
- function agentRows(stats: readonly AgentStat[], limit: number): string[] {
603
- const rows = stats.slice(0, limit).map((stat) => [
604
- fmtInt(stat.turns),
605
- fmtInt(stat.sessions),
606
- fmtCount(stat.input),
607
- fmtCount(stat.output),
608
- fmtCount(stat.cacheRead),
609
- fmtPct(stat.cacheHitRate),
610
- fmtSpeed(stat.medianTokPerSec),
611
- fmtCost(stat.meteredCostPartial),
612
- fmtPct(stat.failureRate),
613
- stat.agent,
614
- ]);
615
- return renderTable(AGENT_COLUMNS, rows.length > 0 ? rows : [["(none)"]]);
616
- }
617
-
618
- export function formatReport(report: Report, source: string, opts: ViewOptions): string {
619
- const lines: string[] = [];
620
- const scope = opts.sinceLabel === undefined ? "all history" : `since ${opts.sinceLabel}`;
621
- lines.push("pirep — measured model and agent performance");
622
- lines.push(`source (read-only): ${source}`);
623
- lines.push(`scope: ${scope}`);
624
- lines.push(
625
- `scanned ${report.scanned} assistant messages: ${report.turns} turns across ${report.sessions} sessions` +
626
- (report.skipped > 0 ? `, ${report.skipped} skipped (unreadable)` : ""),
627
- );
628
- lines.push("");
629
-
630
- const showModels = !opts.agentsOnly;
631
- const showAgents = !opts.modelsOnly;
632
-
633
- if (showModels) {
634
- lines.push("Metered models (recorded cost above zero; med-cost is per-turn median of recorded cost):");
635
- lines.push(...modelRows(report.metered, opts.limit, true));
636
- lines.push(
637
- `total metered cost ${fmtCost(report.totalMeteredCost)} (partial: excludes ${report.unpricedTurns} unpriced turns)`,
638
- );
639
- lines.push("");
640
- lines.push("Unpriced models (no metered cost recorded — real tokens, zero cost, e.g. subscription models):");
641
- lines.push(...modelRows(report.unpriced, opts.limit, false));
642
- lines.push("cost columns omitted here on purpose: a zero-cost model would always win a cost ranking.");
643
- lines.push("");
644
- }
645
-
646
- if (showAgents) {
647
- lines.push("Agents (turns mix models; metered$* counts metered turns only, partial):");
648
- lines.push(...agentRows(report.agents, opts.limit));
649
- lines.push("");
650
- }
651
-
652
- lines.push(`notes: ${METERING_NOTE}`);
653
- lines.push(`notes: ${COUNTS_NOTE}`);
654
- lines.push(`notes: ${PARTIAL_NOTE}`);
655
- lines.push(`notes: ${SPEED_NOTE}`);
656
- lines.push(`notes: ${FAILURE_NOTE}`);
657
- return lines.join("\n");
658
- }
659
-
660
- export interface JsonPayload {
661
- readonly source: string;
662
- readonly since: string | null;
663
- readonly scanned: number;
664
- readonly skipped: number;
665
- readonly turns: number;
666
- readonly sessions: number;
667
- readonly limit: number | null;
668
- readonly totalMeteredCostPartial: number;
669
- readonly unpricedTurns: number;
670
- readonly metered: readonly ModelStat[];
671
- readonly unpriced: readonly ModelStat[];
672
- readonly agents: readonly AgentStat[];
673
- readonly notes: readonly string[];
674
- }
675
-
676
- export function buildPayload(
677
- report: Report,
678
- source: string,
679
- sinceLabel: string | undefined,
680
- limit: number | undefined,
681
- ): JsonPayload {
682
- return {
683
- source,
684
- since: sinceLabel ?? null,
685
- scanned: report.scanned,
686
- skipped: report.skipped,
687
- turns: report.turns,
688
- sessions: report.sessions,
689
- limit: limit ?? null,
690
- totalMeteredCostPartial: report.totalMeteredCost,
691
- unpricedTurns: report.unpricedTurns,
692
- metered: limit === undefined ? report.metered : report.metered.slice(0, limit),
693
- unpriced: limit === undefined ? report.unpriced : report.unpriced.slice(0, limit),
694
- agents: limit === undefined ? report.agents : report.agents.slice(0, limit),
695
- notes: [METERING_NOTE, PARTIAL_NOTE, SPEED_NOTE, FAILURE_NOTE],
696
- };
697
- }
698
-
699
- // ---------------------------------------------------------------------------
700
- // CLI
701
- // ---------------------------------------------------------------------------
702
-
703
- export interface Args {
704
- readonly json: boolean;
705
- readonly sinceLabel: string | undefined;
706
- readonly sinceMs: number | undefined;
707
- readonly limit: number | undefined;
708
- readonly modelsOnly: boolean;
709
- readonly agentsOnly: boolean;
710
- readonly help: boolean;
711
- readonly error: string | undefined;
712
- }
713
-
714
- export function parseArgs(argv: readonly string[]): Args {
715
- let json = false;
716
- let sinceLabel: string | undefined;
717
- let sinceMs: number | undefined;
718
- let limit: number | undefined;
719
- let modelsOnly = false;
720
- let agentsOnly = false;
721
- let help = false;
722
- let error: string | undefined;
723
-
724
- for (const arg of argv) {
725
- if (arg === "--json") json = true;
726
- else if (arg === "--models") modelsOnly = true;
727
- else if (arg === "--agents") agentsOnly = true;
728
- else if (arg === "--help" || arg === "-h") help = true;
729
- else if (arg.startsWith("--since=")) {
730
- const value = arg.slice("--since=".length);
731
- if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(`${value}T00:00:00Z`))) {
732
- error = `bad --since value ${JSON.stringify(value)} (want YYYY-MM-DD)`;
733
- break;
734
- }
735
- sinceLabel = value;
736
- sinceMs = Date.parse(`${value}T00:00:00Z`);
737
- } else if (arg.startsWith("--limit=")) {
738
- const value = Number(arg.slice("--limit=".length));
739
- if (!Number.isInteger(value) || value <= 0) {
740
- error = `bad --limit value ${JSON.stringify(arg.slice("--limit=".length))} (want a positive integer)`;
741
- break;
742
- }
743
- limit = value;
744
- } else if (arg.startsWith("--")) {
745
- error = `unknown flag ${JSON.stringify(arg)}`;
746
- break;
747
- } else {
748
- error = `unexpected argument ${JSON.stringify(arg)} (pirep takes flags only)`;
749
- break;
750
- }
751
- }
752
-
753
- return { json, sinceLabel, sinceMs, limit, modelsOnly, agentsOnly, help, error };
754
- }
755
-
756
- const USAGE = `pirep — which models and agents actually perform, measured from history
757
-
758
- pirep full report: metered models, unpriced models, agents
759
- pirep --models models only
760
- pirep --agents agents only
761
- pirep --since=YYYY-MM-DD only turns on or after this date
762
- pirep --limit=N cap rows per section
763
- pirep --json machine-readable output
764
- pirep --help this text
765
-
766
- Source (read-only): ${SOURCE_DB}`;
767
-
768
- async function main(): Promise<number> {
769
- const args = parseArgs(process.argv.slice(2));
770
-
771
- if (args.help) {
772
- console.log(USAGE);
773
- return 0;
774
- }
775
- if (args.error !== undefined) {
776
- console.error(`pirep: ${args.error}`);
777
- console.error(USAGE);
778
- return 1;
779
- }
780
-
781
- if (!existsSync(SOURCE_DB)) {
782
- console.error(`pirep: no history found at ${SOURCE_DB}`);
783
- return 1;
784
- }
785
-
786
- let source: Database;
787
- try {
788
- // The one promise that matters: this is a reader, never a writer.
789
- source = new Database(SOURCE_DB, { readonly: true });
790
- } catch {
791
- console.error(`pirep: cannot read history at ${SOURCE_DB}`);
792
- return 1;
793
- }
794
-
795
- let collected: { turns: Turn[]; scanned: number; skipped: number };
796
- try {
797
- collected = collectTurns(source, args.sinceMs);
798
- } catch {
799
- console.error(`pirep: cannot read history at ${SOURCE_DB}`);
800
- return 1;
801
- } finally {
802
- try {
803
- source.close();
804
- } catch {
805
- /* closing a read-only handle must not fail the report */
806
- }
807
- }
808
-
809
- const report = aggregate(collected.turns);
810
- const full: Report = { ...report, scanned: collected.scanned, skipped: collected.skipped };
811
-
812
- // The human string is for text mode only: --json must always emit a valid
813
- // payload (an empty one when the scope has no turns) so JSON consumers never
814
- // receive prose.
815
- if (full.turns === 0 && !args.json) {
816
- console.log("no assistant turns found for this scope.");
817
- return 0;
818
- }
819
-
820
- if (args.json) {
821
- console.log(JSON.stringify(buildPayload(full, SOURCE_DB, args.sinceLabel, args.limit), null, 2));
822
- return 0;
823
- }
824
- console.log(
825
- formatReport(full, SOURCE_DB, {
826
- modelsOnly: args.modelsOnly,
827
- agentsOnly: args.agentsOnly,
828
- limit: args.limit ?? Number.MAX_SAFE_INTEGER,
829
- sinceLabel: args.sinceLabel,
830
- }),
831
- );
832
- return 0;
833
- }
834
-
835
- // Importing this module (from the test suite) must not run the CLI.
836
- if (import.meta.main) process.exit(await main());