coauthored 0.0.0-stage → 1.0.0

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 (130) hide show
  1. package/LICENSE +21 -0
  2. package/PRIVACY.md +107 -0
  3. package/README.md +113 -3
  4. package/THIRD_PARTY_LICENSES.md +105 -0
  5. package/dist/cli/analytics/anchors.js +39 -0
  6. package/dist/cli/analytics/archetypes.js +193 -0
  7. package/dist/cli/analytics/content/analyzer.js +945 -0
  8. package/dist/cli/analytics/content/classify.js +115 -0
  9. package/dist/cli/analytics/content/demo-corpus.js +301 -0
  10. package/dist/cli/analytics/content/sketch.js +54 -0
  11. package/dist/cli/analytics/dataset.js +321 -0
  12. package/dist/cli/analytics/demo-fixtures.js +531 -0
  13. package/dist/cli/analytics/fdr.js +183 -0
  14. package/dist/cli/analytics/helicorder.js +66 -0
  15. package/dist/cli/analytics/insights.js +589 -0
  16. package/dist/cli/analytics/models.js +75 -0
  17. package/dist/cli/analytics/pricing.js +121 -0
  18. package/dist/cli/analytics/probable-cause.js +115 -0
  19. package/dist/cli/analytics/report-builder.js +162 -0
  20. package/dist/cli/analytics/statistics.js +91 -0
  21. package/dist/cli/analytics/time.js +252 -0
  22. package/dist/cli/cli/args.js +105 -0
  23. package/dist/cli/cli/browser.js +71 -0
  24. package/dist/cli/cli/index.js +20 -0
  25. package/dist/cli/cli/main.js +520 -0
  26. package/dist/cli/cli/phrase-review.js +78 -0
  27. package/dist/cli/cli/server.js +481 -0
  28. package/dist/cli/cli/terminal.js +363 -0
  29. package/dist/cli/ingest/adapters/aider.js +116 -0
  30. package/dist/cli/ingest/adapters/claude-code.js +139 -0
  31. package/dist/cli/ingest/adapters/cline-roo.js +89 -0
  32. package/dist/cli/ingest/adapters/codex-cli.js +240 -0
  33. package/dist/cli/ingest/adapters/content.js +99 -0
  34. package/dist/cli/ingest/adapters/cursor-ide.js +149 -0
  35. package/dist/cli/ingest/adapters/gemini-cli.js +208 -0
  36. package/dist/cli/ingest/adapters/index.js +18 -0
  37. package/dist/cli/ingest/adapters/opencode.js +203 -0
  38. package/dist/cli/ingest/adapters/pi-agent.js +85 -0
  39. package/dist/cli/ingest/adapters/shared.js +484 -0
  40. package/dist/cli/ingest/content-sink.js +31 -0
  41. package/dist/cli/ingest/discovery.js +50 -0
  42. package/dist/cli/ingest/message-digests.js +61 -0
  43. package/dist/cli/ingest/pipeline.js +155 -0
  44. package/dist/cli/ingest/safe-fs.js +284 -0
  45. package/dist/cli/ingest/sqlite-stage.js +139 -0
  46. package/dist/cli/ingest/time-window.js +34 -0
  47. package/dist/cli/ingest/tool-map.js +24 -0
  48. package/dist/cli/ingest/types.js +1 -0
  49. package/dist/cli/ingest/worker.js +97 -0
  50. package/dist/cli/report/content/emoji-names.js +3956 -0
  51. package/dist/cli/report/content/insights.js +41 -0
  52. package/dist/cli/report/content/lexicons.js +112 -0
  53. package/dist/cli/report/content/policy.js +77 -0
  54. package/dist/cli/report/content/redact.js +164 -0
  55. package/dist/cli/report/content/stopwords.js +8848 -0
  56. package/dist/cli/report/content/suppression.js +2617 -0
  57. package/dist/cli/report/content/validate.js +152 -0
  58. package/dist/cli/report/copy-lint.js +105 -0
  59. package/dist/cli/report/share.js +132 -0
  60. package/dist/cli/report/types.js +1 -0
  61. package/dist/cli/report/validators.js +334 -0
  62. package/dist/web/assets/Archivo-VF-BohoA-Sn.woff2 +0 -0
  63. package/dist/web/assets/DelaGothicOne-subset-CpoJGhTq.woff2 +0 -0
  64. package/dist/web/assets/Film-Dq8Xxn7U.css +1 -0
  65. package/dist/web/assets/MartianMono-VF-CmJ1nXx9.woff2 +0 -0
  66. package/dist/web/assets/app-DEQgytaq.js +38 -0
  67. package/dist/web/assets/bricolage-grotesque-latin-700-normal-gtcctNPv.woff2 +0 -0
  68. package/dist/web/assets/bricolage-grotesque-latin-800-normal-J50vIsBe.woff2 +0 -0
  69. package/dist/web/assets/chorus-D7bfON5Z.ogg +0 -0
  70. package/dist/web/assets/chorus-bass-CBTKpMv_.ogg +0 -0
  71. package/dist/web/assets/chorus-drums-BOzgLSoq.ogg +0 -0
  72. package/dist/web/assets/chorus-harmony-DnJYs_tp.ogg +0 -0
  73. package/dist/web/assets/chorus-lead-CFpg5DC1.ogg +0 -0
  74. package/dist/web/assets/chunk-BNfsY4o8.js +1 -0
  75. package/dist/web/assets/chunk-BSm8IhPY.js +1 -0
  76. package/dist/web/assets/chunk-Bi6EQAkf.js +1 -0
  77. package/dist/web/assets/chunk-BmDwUWlX.js +1 -0
  78. package/dist/web/assets/chunk-Ds4joAI5.js +46 -0
  79. package/dist/web/assets/chunk-V3YGpFIw.js +1 -0
  80. package/dist/web/assets/chunk-XGhNFWse.js +1 -0
  81. package/dist/web/assets/dialogue-card-A5zmbNhu.ogg +0 -0
  82. package/dist/web/assets/groove-bass-BFNelLKi.ogg +0 -0
  83. package/dist/web/assets/groove-drums-BY1SBntR.ogg +0 -0
  84. package/dist/web/assets/groove-harmony-C0CrBzu3.ogg +0 -0
  85. package/dist/web/assets/groove-lead-CEYPzm5U.ogg +0 -0
  86. package/dist/web/assets/groove-ln-zQmTb.ogg +0 -0
  87. package/dist/web/assets/guess-high-CL6mF18x.ogg +0 -0
  88. package/dist/web/assets/guess-low-C3UnKayZ.ogg +0 -0
  89. package/dist/web/assets/higher-BevsMIWl.ogg +0 -0
  90. package/dist/web/assets/identity-0EPS3msD.ogg +0 -0
  91. package/dist/web/assets/index-DpT0dtHc.css +1 -0
  92. package/dist/web/assets/intro-DeRh6kUx.ogg +0 -0
  93. package/dist/web/assets/intro-bass-D63IPU0H.ogg +0 -0
  94. package/dist/web/assets/intro-drums-Dt9QO534.ogg +0 -0
  95. package/dist/web/assets/intro-harmony-DBsMG9jJ.ogg +0 -0
  96. package/dist/web/assets/intro-lead-DWcWS1ia.ogg +0 -0
  97. package/dist/web/assets/jar-coin-rtCvspuq.ogg +0 -0
  98. package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  99. package/dist/web/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  100. package/dist/web/assets/ledger-tick-C1rQgQGX.ogg +0 -0
  101. package/dist/web/assets/night-B_bMOZcf.ogg +0 -0
  102. package/dist/web/assets/night-bass-B-7Ay9ME.ogg +0 -0
  103. package/dist/web/assets/night-drums-zEtqWXX3.ogg +0 -0
  104. package/dist/web/assets/night-harmony-C5Ix2yce.ogg +0 -0
  105. package/dist/web/assets/night-lead-B7KMlRyj.ogg +0 -0
  106. package/dist/web/assets/ourturn-DX78hTEz.ogg +0 -0
  107. package/dist/web/assets/plus-jakarta-sans-latin-400-normal-Dhut76fR.woff2 +0 -0
  108. package/dist/web/assets/plus-jakarta-sans-latin-500-normal-Bf-nb4oT.woff2 +0 -0
  109. package/dist/web/assets/plus-jakarta-sans-latin-600-normal-DLTa1BUW.woff2 +0 -0
  110. package/dist/web/assets/plus-jakarta-sans-latin-700-normal-CfpNZvy6.woff2 +0 -0
  111. package/dist/web/assets/reveal-BmWAGHih.ogg +0 -0
  112. package/dist/web/assets/review-split-Dac4zagw.ogg +0 -0
  113. package/dist/web/assets/shutter-uhz2Y9S9.ogg +0 -0
  114. package/dist/web/assets/soclose-CiUFR5St.ogg +0 -0
  115. package/dist/web/assets/stinger-TnnzHAMN.ogg +0 -0
  116. package/dist/web/assets/stomp-mzIk4cGm.ogg +0 -0
  117. package/dist/web/assets/syne-latin-700-normal-AF3Rs61n.woff2 +0 -0
  118. package/dist/web/assets/syne-latin-800-normal-EehdNYzx.woff2 +0 -0
  119. package/dist/web/assets/tension-BHvWG5ru.ogg +0 -0
  120. package/dist/web/assets/tension-bass-4G-2qA9W.ogg +0 -0
  121. package/dist/web/assets/tension-drums-D7sdehJr.ogg +0 -0
  122. package/dist/web/assets/tension-harmony-FyPldmLb.ogg +0 -0
  123. package/dist/web/assets/tension-lead-C5uoFMR8.ogg +0 -0
  124. package/dist/web/assets/why-clock-Dzs1A_ym.ogg +0 -0
  125. package/dist/web/favicon.svg +1 -0
  126. package/dist/web/index.html +16 -0
  127. package/dist/web/licenses/OFL-Archivo.txt +93 -0
  128. package/dist/web/licenses/OFL-DelaGothic.txt +93 -0
  129. package/dist/web/licenses/OFL-MartianMono.txt +93 -0
  130. package/package.json +63 -6
@@ -0,0 +1,589 @@
1
+ import { estimate, groupBy, HARNESS_NAMES, lowerBound, mean, median, pct, quantile } from './dataset.js';
2
+ import { contextFill, normalizeModelId } from './models.js';
3
+ import { computePricing, PRICING_CATALOG_DATE } from './pricing.js';
4
+ import { pickWrittenAnchor, WORDS_PER_TOKEN } from './anchors.js';
5
+ import { addDays, chronotypeFor, circularMean, datesBetween, dayDistance, formatClock, localTimestamp, makeActiveSpans, MINUTE_MS, monday, spanMinutes, unionSpans, } from './time.js';
6
+ import { mannWhitneyU, normalizedEntropy, permutationTurningPoint } from './statistics.js';
7
+ export const TOOL_LABELS = {
8
+ investigate: 'Investigate', modify: 'Modify', execute: 'Execute', delegate: 'Delegate',
9
+ research: 'Research', plan: 'Plan', integrate: 'Integrate', other: 'Other',
10
+ };
11
+ const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
12
+ const countIn = (events, start, end) => lowerBound(events, end, (e) => e.tsMs) - lowerBound(events, start, (e) => e.tsMs);
13
+ export function buildRhythm(d, onNight) {
14
+ const prompts = d.humanPrompts.filter((p) => d.capability(p.sessionId, 'humanPromptTimestamps') !== 'absent');
15
+ const clockSource = prompts.length || d.capabilities.humanPromptTimestamps !== 'absent' ? 'human' : 'agent';
16
+ const clockEvents = clockSource === 'human' ? prompts : d.agentRequests.filter((r) => d.capability(r.sessionId, 'agentRequestTimestamps') !== 'absent');
17
+ const grouped = groupBy(clockEvents, (e) => d.codingDate(e.tsMs));
18
+ const hourlyDistribution = Array(24).fill(0);
19
+ const weighted = [];
20
+ for (const group of grouped.values()) {
21
+ for (const e of group) {
22
+ const { hour } = d.local(e.tsMs);
23
+ hourlyDistribution[hour]++;
24
+ }
25
+ // Evenly sample the full day so the cap does not prefer the earliest prompts.
26
+ const n = Math.min(30, group.length);
27
+ for (let i = 0; i < n; i++) {
28
+ const p = group[Math.floor((i + 0.5) * group.length / n)];
29
+ weighted.push(d.local(p.tsMs).minuteOfDay + d.local(p.tsMs).second / 60);
30
+ }
31
+ }
32
+ const solarEligible = clockEvents.length >= 40 && grouped.size >= 5;
33
+ const center = circularMean(weighted);
34
+ const peak = solarEligible && center.resultantR >= 0.25 ? center.minute : null;
35
+ const peakTimeFormatted = peak === null ? null : formatClock(peak);
36
+ const solarNoon = {
37
+ eligible: solarEligible, peakMinuteOfDay: peak, peakTimeFormatted,
38
+ resultantR: solarEligible ? center.resultantR : null,
39
+ chronotype: solarEligible && clockSource === 'human' ? chronotypeFor(peak, center.resultantR) : null,
40
+ hourlyDistribution, clockSource,
41
+ copy: solarEligible ? peakTimeFormatted
42
+ ? `${clockSource === 'human' ? 'Your coding clock' : 'Your agent clock'} peaks around ${peakTimeFormatted} local time (${weighted.length.toLocaleString('en-US')} sampled ${clockSource === 'human' ? 'prompts' : 'requests'}).`
43
+ : `No single peak hour — ${clockSource === 'human' ? 'you work' : 'your agents run'} evenly around the clock.`
44
+ : 'Too few timestamps to call a daily rhythm yet.',
45
+ };
46
+ const grid7x24 = Array.from({ length: 7 }, () => Array(24).fill(0));
47
+ for (const prompt of prompts) {
48
+ const { dayOfWeek, hour } = d.local(prompt.tsMs);
49
+ grid7x24[(dayOfWeek + 6) % 7][hour]++;
50
+ }
51
+ const rows = grid7x24.map((row) => row.reduce((a, b) => a + b, 0));
52
+ const cols = Array.from({ length: 24 }, (_, h) => grid7x24.reduce((n, row) => n + row[h], 0));
53
+ let best = null;
54
+ let raw = null;
55
+ for (const [day, row] of grid7x24.entries()) {
56
+ for (const [hour, count] of row.entries()) {
57
+ if (!count)
58
+ continue;
59
+ const lift = count * prompts.length / (rows[day] * cols[hour]);
60
+ const cell = { day, hour, count, lift };
61
+ if (!raw || count > raw.count)
62
+ raw = cell;
63
+ if (count >= 8 && (!best || lift > best.lift || (lift === best.lift && count > best.count)))
64
+ best = cell;
65
+ }
66
+ }
67
+ const witchEligible = prompts.length >= 150;
68
+ const cell = witchEligible ? best ?? raw : null;
69
+ const label = cell ? `${DAYS[cell.day]}, ${formatClock(cell.hour * 60)}` : null;
70
+ const witchingHour = {
71
+ eligible: !!cell, dayOfWeek: cell?.day ?? null, hour: cell?.hour ?? null, label,
72
+ lift: witchEligible ? best?.lift ?? null : null, isRawMaxFallback: !!cell && !best, grid7x24,
73
+ copy: cell
74
+ ? best && best.lift >= 2.0
75
+ ? `${label} is your signature slot — ${cell.count.toLocaleString('en-US')} prompts (${estimate(best.lift)}× your usual pace).`
76
+ : best
77
+ ? `No single standout hour — your schedule stays pretty even (busiest: ${label}, ${cell.count.toLocaleString('en-US')} prompts).`
78
+ : `${label} was your busiest hour of the week.`
79
+ : 'Not enough human prompts to call a signature hour yet.',
80
+ };
81
+ let longest = null, night = null;
82
+ const nightWindows = new Map();
83
+ for (const span of d.active.wallSpans) {
84
+ if (span.end - span.start < 60 * MINUTE_MS || countIn(prompts, span.start, span.end + 1) < 3)
85
+ continue;
86
+ if (!longest || span.end - span.start > longest.end - longest.start)
87
+ longest = span;
88
+ const nightDates = datesBetween(addDays(d.local(span.start).date, -1), d.local(span.end).date);
89
+ const nightOverlap = nightDates.reduce((sum, date) => {
90
+ let range = nightWindows.get(date);
91
+ if (!range) {
92
+ range = { start: localTimestamp(date, 1320, d.timezone), end: localTimestamp(addDays(date, 1), 300, d.timezone) };
93
+ nightWindows.set(date, range);
94
+ }
95
+ return sum + Math.max(0, Math.min(span.end, range.end) - Math.max(span.start, range.start));
96
+ }, 0);
97
+ if (nightOverlap >= 30 * MINUTE_MS && (!night || span.end - span.start > night.end - night.start))
98
+ night = span;
99
+ }
100
+ onNight?.(night);
101
+ const longestSpan = night ?? longest;
102
+ const startLocal = longestSpan ? d.local(longestSpan.start) : null;
103
+ const endLocal = longestSpan ? d.local(longestSpan.end) : null;
104
+ const dateRangeLabel = startLocal && endLocal ? startLocal.date === endLocal.date ? startLocal.date : `${startLocal.date} – ${endLocal.date}` : null;
105
+ const longestNight = {
106
+ eligible: !!longestSpan, isDayFallback: !night && !!longest, dateRangeLabel,
107
+ startTimeLabel: startLocal ? formatClock(startLocal.minuteOfDay) : null,
108
+ endTimeLabel: endLocal ? formatClock(endLocal.minuteOfDay) : null,
109
+ activeMinutes: longestSpan ? spanMinutes([longestSpan]) : 0,
110
+ humanPrompts: longestSpan ? countIn(prompts, longestSpan.start, longestSpan.end + 1) : 0,
111
+ copy: longestSpan ? `Longest ${night ? 'late-night' : 'daytime'} stretch: ≈ ${estimate(spanMinutes([longestSpan]))} active minutes straight.`
112
+ : 'No single stretch hit the 60-minute threshold yet.',
113
+ };
114
+ const activeDays = [...groupBy(prompts, (p) => d.codingDate(p.tsMs)).keys()]
115
+ .sort().filter((date) => (d.codingMinutes.get(date) ?? 0) >= 5);
116
+ let topRun = 0, runStart = '', streakStart = '', streakEnd = '', restStart = '', restEnd = '', topRest = 0;
117
+ for (const [i, date] of activeDays.entries()) {
118
+ const previous = activeDays[i - 1];
119
+ if (!previous || dayDistance(previous, date) > 1) {
120
+ runStart = date;
121
+ const rest = previous ? dayDistance(previous, date) - 1 : 0;
122
+ if (previous && rest > topRest) {
123
+ topRest = rest;
124
+ restStart = addDays(previous, 1);
125
+ restEnd = addDays(date, -1);
126
+ }
127
+ }
128
+ const run = dayDistance(runStart, date) + 1;
129
+ if (run > topRun) {
130
+ topRun = run;
131
+ streakStart = runStart;
132
+ streakEnd = date;
133
+ }
134
+ }
135
+ const exhale = d.capturedWindow.daysSpanned >= 30 && topRest >= 4;
136
+ const codingWindow = d.events.length ? dayDistance(d.codingDate(d.events[0].tsMs), d.codingDate(d.events.at(-1).tsMs)) + 1 : 0;
137
+ const streaks = {
138
+ longestStreakDays: topRun, longestStreakRange: topRun >= 3 ? `${streakStart} – ${streakEnd}` : null,
139
+ longestExhaleDays: exhale ? topRest : null, longestExhaleRange: exhale ? `${restStart} – ${restEnd}` : null,
140
+ activeDayRatio: codingWindow ? activeDays.length / codingWindow : 0,
141
+ copy: [
142
+ topRun >= 3 ? `${topRun} days straight without missing a beat.` : topRun === 2 ? 'Two days back-to-back.' : '',
143
+ exhale ? `Longest breather: ${topRest} days offline while your agents waited patiently.` : '',
144
+ ].filter(Boolean).join(' '),
145
+ };
146
+ const weekdays = [], weekends = [];
147
+ const isWeekend = (date) => [0, 6].includes(new Date(`${date}T00:00:00Z`).getUTCDay());
148
+ for (const date of activeDays)
149
+ (isWeekend(date) ? weekends : weekdays).push(d.codingMinutes.get(date));
150
+ const eligible = weekdays.length >= 15 && weekends.length >= 6 && d.capabilities.humanPromptTimestamps === 'present';
151
+ const test = eligible ? mannWhitneyU(weekends, weekdays) : null;
152
+ const ratio = test ? mean(weekends) / mean(weekdays) : null;
153
+ const significant = !!test && ratio !== null && test.pValue < 0.05 && (ratio >= 1.4 || ratio <= 0.7);
154
+ const weekdayProjects = new Set(), weekendProjects = new Set();
155
+ for (const p of prompts) {
156
+ const project = d.sessionMap.get(p.sessionId)?.projectHmac;
157
+ if (project)
158
+ (isWeekend(d.codingDate(p.tsMs)) ? weekendProjects : weekdayProjects).add(project);
159
+ }
160
+ return {
161
+ solarNoon, witchingHour, longestNight, streaks,
162
+ weekendContrast: {
163
+ eligible, significant, ratioActiveMinutes: ratio, pValue: test?.pValue ?? null,
164
+ weekendOnlyProjects: significant ? [...weekendProjects].filter((project) => !weekdayProjects.has(project)).length : null,
165
+ copy: significant ? `Qualifying weekend days averaged ≈ ${estimate(ratio)}× the active minutes of qualifying weekdays.`
166
+ : eligible ? 'The recorded weekday and weekend contrast fell below the evidence thresholds.' : 'There are too few qualifying days for a weekday and weekend comparison.',
167
+ },
168
+ };
169
+ }
170
+ export function buildCraft(d) {
171
+ const tools = d.toolCalls.filter((t) => d.capability(t.sessionId, 'toolNames') !== 'absent');
172
+ const requests = d.agentRequests.filter((r) => d.capability(r.sessionId, 'agentRequestTimestamps') !== 'absent');
173
+ const prompts = d.humanPrompts.filter((p) => d.capability(p.sessionId, 'humanPromptTimestamps') !== 'absent');
174
+ const toolCoverage = d.coverage('toolNames').usable;
175
+ const toolMode = tools.length >= 30 && toolCoverage >= 0.1;
176
+ const groups = groupBy(tools, (t) => t.toolFamily);
177
+ const toolMix = toolMode ? Object.entries(TOOL_LABELS).map(([family, label]) => {
178
+ const count = groups.get(family)?.length ?? 0;
179
+ return { family: family, label, count, share: count / tools.length };
180
+ }) : [];
181
+ const inv = groups.get('investigate')?.length ?? 0;
182
+ const mod = groups.get('modify')?.length ?? 0;
183
+ const readEditRatio = toolMode && tools.length >= 100 && mod > 0 ? inv / mod : null;
184
+ const knownCalls = tools.filter((t) => d.capability(t.sessionId, 'toolErrors') !== 'absent');
185
+ let totalErrors = 0, recovered = 0;
186
+ for (const calls of groupBy(knownCalls, (t) => t.sessionId).values()) {
187
+ for (const [i, t] of calls.entries()) {
188
+ if (t.isError !== true)
189
+ continue;
190
+ totalErrors++;
191
+ if (calls.slice(i + 1, i + 4).some((n) => n.toolFamily === t.toolFamily && n.isError === false))
192
+ recovered++;
193
+ }
194
+ }
195
+ const bounceEligible = totalErrors >= 30 && d.coverage('toolErrors').usable >= 0.1;
196
+ const measured = knownCalls.filter((t) => t.isError !== null);
197
+ const nemesis = bounceEligible ? [...groupBy(measured, (t) => t.toolFamily)].filter(([, calls]) => calls.length >= 50)
198
+ .map(([family, calls]) => ({ family, rate: calls.filter((t) => t.isError).length / calls.length }))
199
+ .sort((a, b) => b.rate - a.rate || a.family.localeCompare(b.family))[0] : undefined;
200
+ const useLeashTools = tools.length > 0 && toolCoverage >= 0.1;
201
+ const unit = useLeashTools ? 'tool-calls' : 'agent-requests';
202
+ const stream = useLeashTools ? tools : requests;
203
+ const rootedActions = groupBy(stream, (e) => d.rootId(e.sessionId));
204
+ const promptsBySession = groupBy(prompts, (p) => p.sessionId);
205
+ const runs = [];
206
+ for (const [id, human] of promptsBySession) {
207
+ if (d.capability(id, useLeashTools ? 'toolNames' : 'agentRequestTimestamps') === 'absent')
208
+ continue;
209
+ const entries = rootedActions.get(id) ?? [];
210
+ for (const [i, p] of human.entries()) {
211
+ const end = human[i + 1]?.tsMs ?? Math.max(d.sessionMap.get(id).endTsMs, entries.at(-1)?.tsMs ?? p.tsMs) + 1;
212
+ const from = lowerBound(entries, p.tsMs, (e) => e.tsMs);
213
+ const to = lowerBound(entries, end, (e) => e.tsMs);
214
+ const minutes = spanMinutes(makeActiveSpans(entries.slice(from, to).map((e) => e.tsMs), undefined, d.bounds));
215
+ runs.push({ count: to - from, minutes });
216
+ }
217
+ }
218
+ const runCounts = runs.map((r) => r.count);
219
+ const max = runs.reduce((a, b) => b.count > a.count || (b.count === a.count && b.minutes > a.minutes) ? b : a, { count: 0, minutes: 0 });
220
+ const leashEligible = runs.length > 0 && max.count > 0;
221
+ const actionCapability = useLeashTools ? 'toolNames' : 'agentRequestTimestamps';
222
+ const bothCovered = (sessionId) => {
223
+ const root = d.rootId(sessionId);
224
+ return d.capability(root, 'humanPromptTimestamps') !== 'absent' && d.capability(sessionId, actionCapability) !== 'absent';
225
+ };
226
+ const humanCount = prompts.filter((p) => bothCovered(p.sessionId)).length;
227
+ const actionCount = stream.filter((e) => bothCovered(e.sessionId)).length;
228
+ const actionsShare = humanCount && actionCount ? actionCount / (humanCount + actionCount) : 0;
229
+ const leashMedian = Math.round(median(runCounts));
230
+ const leashP90 = Math.round(quantile(runCounts, 0.9));
231
+ const unitLabel = unit === 'tool-calls' ? 'tool calls' : 'requests';
232
+ const recoveryRate = bounceEligible ? recovered / totalErrors : null;
233
+ const roundPct = (rate) => `${Math.round(rate * 100)}%`;
234
+ const agentPct = Math.round(actionsShare * 100);
235
+ const humanPct = 100 - agentPct;
236
+ return {
237
+ eligible: toolMode || leashEligible, fallbackMode: toolMode ? 'tools' : leashEligible ? 'conversation-shape' : 'minimal', toolMix,
238
+ readEditRatio,
239
+ readEditCopy: readEditRatio === null ? null : readEditRatio >= 3
240
+ ? `${estimate(readEditRatio)} reads for every edit. Actually reading the codebase before touching it.`
241
+ : readEditRatio < 0.8
242
+ ? `${estimate(readEditRatio)} reads per edit — edit first, ask questions later.`
243
+ : `${estimate(readEditRatio)} reads per edit — steady look-then-leap balance.`,
244
+ bounceBack: {
245
+ eligible: bounceEligible, totalErrors, recoveryRate,
246
+ nemesisFamily: nemesis?.family ?? null, nemesisErrorRate: nemesis?.rate ?? null,
247
+ copy: bounceEligible && recoveryRate !== null
248
+ ? `Your agents shook off ${roundPct(recoveryRate)} of tool errors within 3 steps${nemesis ? ` — toughest tool: ${TOOL_LABELS[nemesis.family].toLowerCase()} (${roundPct(nemesis.rate)} error rate)` : ''}.`
249
+ : 'Too few tool errors logged to measure recovery.',
250
+ },
251
+ leashLength: {
252
+ eligible: leashEligible, unit, median: leashMedian, p90: leashP90, maxCount: max.count, maxActiveMinutes: max.minutes,
253
+ copy: leashEligible
254
+ ? leashMedian >= 12
255
+ ? `Median leash: ${leashMedian} ${unitLabel} per prompt. Hand over the spec and let it run.`
256
+ : leashMedian <= 3
257
+ ? `Short leash (${leashMedian} ${unitLabel} per prompt) — tight back-and-forth steering.`
258
+ : `Median leash: ${leashMedian} ${unitLabel} per prompt before you stepped back in.`
259
+ : 'Not enough overlapping prompt and agent logs to measure leash length.',
260
+ },
261
+ pilotSplit: {
262
+ eligible: actionsShare > 0, agentActionsShare: actionsShare, humanPromptsShare: actionsShare > 0 ? 1 - actionsShare : 0,
263
+ copy: actionsShare > 0
264
+ ? `Agents handled ${agentPct}% of the turns (Pilot Flying) while you steered with ${humanPct}% of the turns (Pilot Monitoring).`
265
+ : 'Not enough overlapping logs for a control split.',
266
+ },
267
+ ...(toolMode && d.coverage('toolNames').full < 1
268
+ ? { coverageNote: `Tool mixes describe the recorded calls. ${pct(toolCoverage)} of sessions supplied a tool-name stream.` } : {}),
269
+ };
270
+ }
271
+ export function buildDelegation(d, isNocturnal = false) {
272
+ const children = d.sessions.filter((s) => s.isSubagent && d.capability(s.sessionId, 'subagentSpawns') !== 'absent');
273
+ const markers = d.toolCalls.filter((t) => t.isSubagentSpawn && d.capability(t.sessionId, 'subagentSpawns') !== 'absent');
274
+ const linksByRoot = groupBy(children, (s) => d.rootId(s.sessionId));
275
+ const spawnsByRoot = groupBy(markers, (t) => d.rootId(t.sessionId));
276
+ const roots = new Set([...linksByRoot.keys(), ...spawnsByRoot.keys()]);
277
+ const totalSpawns = [...roots].reduce((n, id) => n + Math.max(linksByRoot.get(id)?.length ?? 0, spawnsByRoot.get(id)?.length ?? 0), 0);
278
+ const edges = children.flatMap((s) => (d.active.perSession.get(s.sessionId) ?? []).flatMap((span) => [
279
+ { ts: span.start, delta: 1 }, { ts: span.end, delta: -1 },
280
+ ])).sort((a, b) => a.ts - b.ts || a.delta - b.delta);
281
+ let running = 0, maxConcurrent = 0, peakDateLabel = null;
282
+ for (const { ts, delta } of edges) {
283
+ running += delta;
284
+ if (running > maxConcurrent) {
285
+ maxConcurrent = running;
286
+ peakDateLabel = d.local(ts).date;
287
+ }
288
+ }
289
+ const orchestraEligible = totalSpawns >= 10 && d.capabilities.subagentSpawns === 'present';
290
+ const compactions = d.compactions.filter((c) => d.capability(c.sessionId, 'compactions') !== 'absent');
291
+ const requestsBySession = groupBy(d.agentRequests, (r) => r.sessionId);
292
+ const survived = new Set();
293
+ const turnsAfter = [];
294
+ for (const c of compactions) {
295
+ if (d.capability(c.sessionId, 'agentRequestTimestamps') === 'absent')
296
+ continue;
297
+ const requests = requestsBySession.get(c.sessionId) ?? [];
298
+ const count = requests.length - lowerBound(requests, c.tsMs + 1, (r) => r.tsMs);
299
+ if (count >= 5) {
300
+ survived.add(c.sessionId);
301
+ turnsAfter.push(count);
302
+ }
303
+ }
304
+ let closest = null;
305
+ for (const r of d.agentRequests) {
306
+ if (d.capability(r.sessionId, 'tokenBreakdown') === 'absent')
307
+ continue;
308
+ const fill = contextFill(r);
309
+ if (fill !== null && (closest === null || fill > closest))
310
+ closest = fill;
311
+ }
312
+ const cliffEligible = compactions.length > 0 && d.capabilities.compactions === 'present';
313
+ const agentEvents = [...d.agentRequests.filter((e) => d.capability(e.sessionId, 'agentRequestTimestamps') !== 'absent'),
314
+ ...d.toolCalls.filter((e) => d.capability(e.sessionId, 'toolNames') !== 'absent')].sort((a, b) => a.tsMs - b.tsMs);
315
+ const humanByRoot = groupBy(d.humanPrompts.filter((p) => d.capability(p.sessionId, 'humanPromptTimestamps') !== 'absent'), (p) => d.rootId(p.sessionId));
316
+ const unattendedSpans = [];
317
+ for (const [id, agents] of groupBy(agentEvents, (e) => e.sessionId)) {
318
+ const prompts = humanByRoot.get(d.rootId(id));
319
+ if (!prompts?.length)
320
+ continue;
321
+ for (const span of makeActiveSpans(agents.map((e) => e.tsMs), undefined, d.bounds)) {
322
+ const before = lowerBound(prompts, span.start + 1, (p) => p.tsMs) - 1;
323
+ for (let i = Math.max(0, before); i < prompts.length && prompts[i].tsMs < span.end; i++) {
324
+ const start = Math.max(span.start, prompts[i].tsMs + 30 * MINUTE_MS);
325
+ const end = Math.min(span.end, prompts[i + 1]?.tsMs ?? Infinity);
326
+ if (start < end)
327
+ unattendedSpans.push({ start, end });
328
+ }
329
+ }
330
+ }
331
+ const unattended = unionSpans(unattendedSpans);
332
+ const totalHours = spanMinutes(unattended) / 60;
333
+ const unattendedEligible = totalHours >= 2 && d.coverage('humanPromptTimestamps').usable >= 0.1;
334
+ const hasOvernightUnattended = unattended.some((span) => {
335
+ const startHour = d.local(span.start).hour;
336
+ const endHour = d.local(span.end).hour;
337
+ return startHour >= 22 || startHour < 5 || endHour >= 22 || endHour < 5;
338
+ });
339
+ const factor = d.active.parallelismFactor ?? 0;
340
+ return {
341
+ eligible: orchestraEligible || cliffEligible || closest !== null || factor >= 1.2 || unattendedEligible,
342
+ orchestra: {
343
+ eligible: orchestraEligible, totalSpawns, maxConcurrent, peakDateLabel,
344
+ copy: orchestraEligible ? `${totalSpawns.toLocaleString('en-US')} subagents spun up${maxConcurrent ? `, peaking at ${maxConcurrent} running at once` : ''}.`
345
+ : 'Too few subagent spawns logged for an orchestra view.',
346
+ },
347
+ cliffDiving: {
348
+ eligible: cliffEligible || closest !== null, totalCompactions: compactions.length, survivedSessions: survived.size,
349
+ medianTurnsAfter: turnsAfter.length ? median(turnsAfter) : null, closestCallPct: closest,
350
+ copy: cliffEligible ? `Hit context compaction ${compactions.length.toLocaleString('en-US')} times — and kept rolling in ${survived.size.toLocaleString('en-US')} sessions right after.`
351
+ : closest !== null ? `Closest call: ≈ ${estimate(closest)}% of the model context window full.` : 'No compaction or context-fill logs recovered.',
352
+ },
353
+ parallelism: {
354
+ eligible: factor >= 1.2, factor, agentHours: d.active.agentActiveMinutes / 60, wallClockHours: d.active.wallClockActiveMinutes / 60,
355
+ copy: factor >= 1.2 ? `Ran at ≈ ${estimate(factor)}× parallelism — stacking agent-hours well past your own wall clock.` : factor ? 'Mostly one thread at a time — clean single-file focus.' : 'No active spans recovered.',
356
+ },
357
+ unattended: {
358
+ eligible: unattendedEligible, totalHours, longestRunMinutes: unattended.reduce((max, s) => Math.max(max, spanMinutes([s])), 0),
359
+ copy: unattendedEligible
360
+ ? isNocturnal || hasOvernightUnattended
361
+ ? `≈ ${estimate(totalHours)} hours of agent work ran 30+ min after your last prompt. Somebody pulled the night shift and it wasn’t you.`
362
+ : `≈ ${estimate(totalHours)} hours of agent work ran 30+ min after your last prompt.`
363
+ : 'No long unattended runs logged.',
364
+ },
365
+ };
366
+ }
367
+ function migration(weekly) {
368
+ let incumbent = null;
369
+ for (const [i, counts] of weekly.entries()) {
370
+ const total = [...counts.values()].reduce((a, b) => a + b, 0);
371
+ const leader = [...counts].sort(([ka, a], [kb, b]) => b - a || ka.localeCompare(kb))[0];
372
+ if (!leader || leader[1] / total < 0.5)
373
+ continue;
374
+ const [family] = leader;
375
+ if (incumbent === null)
376
+ incumbent = family;
377
+ if (family === incumbent || i + 4 > weekly.length)
378
+ continue;
379
+ const stable = weekly.slice(i, i + 4).every((week) => {
380
+ const count = week.get(family) ?? 0;
381
+ const volume = [...week.values()].reduce((a, b) => a + b, 0);
382
+ return count > 0 && count / volume >= 0.5 && [...week.values()].every((n) => n <= count);
383
+ });
384
+ if (stable) {
385
+ const since = weekly.slice(i);
386
+ const volume = since.reduce((n, w) => n + [...w.values()].reduce((a, b) => a + b, 0), 0);
387
+ return { index: i, from: incumbent, to: family, share: since.reduce((n, w) => n + (w.get(family) ?? 0), 0) / volume };
388
+ }
389
+ }
390
+ return null;
391
+ }
392
+ export function buildEvolution(d) {
393
+ const familyLabels = {
394
+ 'claude-opus': 'Claude Opus', 'claude-sonnet': 'Claude Sonnet', 'claude-haiku': 'Claude Haiku',
395
+ 'gpt-codex': 'GPT Codex', 'gpt-5': 'GPT-5', 'gpt-sol': 'GPT Sol', 'openai-o': 'OpenAI o-series',
396
+ 'gemini-pro': 'Gemini Pro', 'gemini-flash': 'Gemini Flash', 'gemini-neon': 'Gemini Neon',
397
+ 'deepseek': 'DeepSeek', 'deepseek-pro': 'DeepSeek Pro', 'deepseek-flash': 'DeepSeek Flash', 'gpt-oss': 'GPT-OSS',
398
+ };
399
+ const weeklyModels = d.weeks.map(() => new Map());
400
+ const modelGroups = new Map();
401
+ const requestBySession = groupBy(d.agentRequests, (r) => r.sessionId);
402
+ for (const r of d.agentRequests) {
403
+ if (!d.trendCovered(r.sessionId, 'modelIds'))
404
+ continue;
405
+ const { family } = normalizeModelId(r.modelId, r.provider);
406
+ if (family === 'unknown')
407
+ continue;
408
+ const counts = weeklyModels[d.weekIndex(r.tsMs)];
409
+ if (counts)
410
+ counts.set(family, (counts.get(family) ?? 0) + 1);
411
+ const group = modelGroups.get(family) ?? [];
412
+ group.push(r);
413
+ modelGroups.set(family, group);
414
+ }
415
+ const families = [...modelGroups].map(([family, requests]) => {
416
+ const sessionShares = groupBy(requests, (r) => r.sessionId);
417
+ let estimatedHours = 0;
418
+ for (const [id, group] of sessionShares) {
419
+ estimatedHours += spanMinutes(d.active.perSession.get(id) ?? []) * group.length / (requestBySession.get(id)?.length ?? group.length) / 60;
420
+ }
421
+ return {
422
+ family, displayName: familyLabels[family] ?? normalizeModelId(requests[0].modelId).displayName,
423
+ weeklyShares: weeklyModels.map((w) => (w.get(family) ?? 0) / ([...w.values()].reduce((a, b) => a + b, 0) || 1)),
424
+ totalRequests: requests.length, estimatedHours, firstSeenDate: d.local(requests[0].tsMs).date,
425
+ };
426
+ }).sort((a, b) => b.totalRequests - a.totalRequests || a.family.localeCompare(b.family));
427
+ const hasRetentionCliff = d.capturedWindow.perHarness.some((h) => h.likelyTruncated);
428
+ const completeModels = !hasRetentionCliff && d.sessions.every((s) => d.trendCovered(s.sessionId, 'modelIds'));
429
+ const modelMove = completeModels ? migration(weeklyModels) : null;
430
+ const prompts = d.humanPrompts.filter((p) => d.trendCovered(p.sessionId, 'humanPromptTimestamps'));
431
+ const weeklyHarnesses = d.weeks.map(() => new Map());
432
+ for (const p of prompts) {
433
+ const w = weeklyHarnesses[d.weekIndex(p.tsMs)];
434
+ if (w)
435
+ w.set(p.harness, (w.get(p.harness) ?? 0) + 1);
436
+ }
437
+ const completePrompts = !hasRetentionCliff && d.parentSessions.every((s) => d.trendCovered(s.sessionId, 'humanPromptTimestamps'));
438
+ const harnessMove = completePrompts ? migration(weeklyHarnesses) : null;
439
+ const usedHarnesses = new Set(d.sessions.map((s) => s.harness));
440
+ const harnessShares = [...groupBy(prompts, (p) => p.harness)].map(([harness, p]) => ({
441
+ harness, displayName: HARNESS_NAMES[harness], share: p.length / prompts.length, prompts: p.length,
442
+ })).sort((a, b) => b.prompts - a.prompts || a.harness.localeCompare(b.harness));
443
+ const loyaltyIndex = harnessShares.length ? 1 - normalizedEntropy(harnessShares.map((s) => s.prompts)) : 0;
444
+ const switchDays = [...groupBy(d.events, (e) => d.codingDate(e.tsMs)).values()]
445
+ .filter((e) => new Set(e.map((x) => x.harness)).size >= 2).length;
446
+ const fullWeeks = d.weeks.filter((w) => d.capturedWindow.startDate !== null && d.capturedWindow.endDate !== null &&
447
+ w >= d.capturedWindow.startDate && addDays(w, 6) <= d.capturedWindow.endDate);
448
+ const weekActivity = new Map();
449
+ for (const [date, minutes] of d.codingMinutes) {
450
+ const week = monday(date);
451
+ weekActivity.set(week, (weekActivity.get(week) ?? 0) + minutes);
452
+ }
453
+ const promptSeries = completePrompts && prompts.length > 0;
454
+ const comparableTime = !hasRetentionCliff && d.sessions.every((s) => d.trendCovered(s.sessionId, 'agentRequestTimestamps'));
455
+ const series = fullWeeks.map((w) => promptSeries
456
+ ? [...(weeklyHarnesses[d.weeks.indexOf(w)]?.values() ?? [])].reduce((a, b) => a + b, 0)
457
+ : weekActivity.get(w) ?? 0);
458
+ const turn = (promptSeries || comparableTime) ? permutationTurningPoint(series, d.seed) : null;
459
+ const detected = !!turn && turn.pValue < 0.05 && (turn.ratio >= 1.5 || turn.ratio <= 0.67);
460
+ const week = detected ? fullWeeks[turn.split] : null;
461
+ const spawnTime = d.toolCalls.find((t) => t.isSubagentSpawn)?.tsMs ?? d.sessions.find((s) => s.isSubagent)?.startTsMs;
462
+ const firsts = [
463
+ ...(modelMove ? [{ week: d.weeks[modelMove.index], label: 'model migration' }] : []),
464
+ ...(harnessMove ? [{ week: d.weeks[harnessMove.index], label: 'harness switch' }] : []),
465
+ ...(spawnTime === undefined ? [] : [{ week: monday(d.local(spawnTime).date), label: 'first recorded subagent' }]),
466
+ ...[...groupBy(d.parentSessions, (s) => s.harness).values()].slice(1)
467
+ .map((s) => ({ week: monday(d.local(s[0].startTsMs).date), label: `first use of ${HARNESS_NAMES[s[0].harness]}` })),
468
+ ];
469
+ const first = week ? firsts.find((f) => Math.abs(dayDistance(f.week, week)) <= 7) : undefined;
470
+ return {
471
+ eligible: d.capturedWindow.daysSpanned >= 14 && (families.length > 0 || usedHarnesses.size > 1 || !!turn),
472
+ modelRiver: {
473
+ weeks: d.weeks, families,
474
+ migration: {
475
+ detected: !!modelMove, weekStart: modelMove ? d.weeks[modelMove.index] : null,
476
+ fromFamily: modelMove?.from ?? null, toFamily: modelMove?.to ?? null, shareAfter: modelMove?.share ?? null,
477
+ copy: modelMove ? `Switched lanes from ${familyLabels[modelMove.from]} to ${familyLabels[modelMove.to]} — held 50%+ of requests for four straight weeks.`
478
+ : hasRetentionCliff ? 'Earlier logs were clipped by local retention, so model-migration detection is skipped.'
479
+ : 'Stuck with the same core model lineup — no big mid-year plot twist.',
480
+ },
481
+ },
482
+ harnessPolyglot: {
483
+ harnessCount: usedHarnesses.size, loyaltyIndex, switchDays, defectionWeek: harnessMove ? d.weeks[harnessMove.index] : null,
484
+ shares: harnessShares,
485
+ copy: harnessShares.length
486
+ ? harnessShares.length > 1
487
+ ? `Split prompts across ${harnessShares.length} harnesses, switching mid-day on ${switchDays} coding days.`
488
+ : `All-in on ${harnessShares[0].displayName} across the captured window.`
489
+ : 'Session metadata identifies your harnesses; prompt shares were not logged.',
490
+ },
491
+ turningPoint: {
492
+ eligible: !!turn, detected, weekStart: week, ratio: turn && Number.isFinite(turn.ratio) ? turn.ratio : null,
493
+ pValue: turn?.pValue ?? null, coOccurringFirst: first?.label ?? null,
494
+ copy: detected ? `Activity shifted the week of ${week} — weekly ${promptSeries ? 'prompts' : 'active minutes'} changed noticeably${first ? `, right around your ${first.label}` : ''}.`
495
+ : turn ? 'Steady cadence week to week — no sudden inflection point.'
496
+ : hasRetentionCliff ? 'Local retention clipped earlier logs, so turning-point detection is skipped.'
497
+ : 'Not enough full weeks in view to test for a turning point yet.',
498
+ },
499
+ };
500
+ }
501
+ export function buildScale(d) {
502
+ const measured = d.agentRequests.filter((r) => d.capability(r.sessionId, 'tokenBreakdown') !== 'absent');
503
+ const cacheAbsent = d.capabilities.cacheTokens === 'absent';
504
+ const tokens = measured.length && d.coverage('tokenBreakdown').usable >= 0.1 ? measured.reduce((acc, r) => {
505
+ const hasCache = !cacheAbsent && d.capability(r.sessionId, 'cacheTokens') !== 'absent';
506
+ const reread = hasCache ? r.cacheRead : 0;
507
+ const fresh = r.inputUncached + (hasCache ? r.cacheWrite5m + r.cacheWrite1h : 0);
508
+ acc.written += r.output;
509
+ acc.readFresh += fresh;
510
+ acc.rereadCache += reread;
511
+ if (d.capability(r.sessionId, 'reasoningTokens') !== 'absent')
512
+ acc.reasoning += r.reasoning;
513
+ acc.totalProcessed += r.output + fresh + reread;
514
+ return acc;
515
+ }, { written: 0, readFresh: 0, rereadCache: 0, reasoning: 0, totalProcessed: 0 }) : null;
516
+ const cached = cacheAbsent ? [] : measured.filter((r) => d.capability(r.sessionId, 'cacheTokens') === 'present');
517
+ const cacheInput = cached.reduce((n, r) => n + r.inputUncached + r.cacheWrite5m + r.cacheWrite1h + r.cacheRead, 0);
518
+ const cacheRead = cached.reduce((n, r) => n + r.cacheRead, 0);
519
+ const cacheEligible = cacheInput > 0 && d.capabilities.cacheTokens === 'present';
520
+ const hitRate = cacheInput ? cacheRead / cacheInput : 0;
521
+ const pricing = computePricing(d.agentRequests, (r) => d.capability(r.sessionId, 'tokenBreakdown') !== 'absent');
522
+ const pricedCache = cacheEligible ? (cached.length === measured.length ? pricing : computePricing(cached)) : null;
523
+ const net = pricedCache?.netSavingsUsd ?? null;
524
+ const written = tokens?.written ?? 0;
525
+ const anchor = pickWrittenAnchor(written);
526
+ return {
527
+ tokens,
528
+ scale: {
529
+ eligible: !!tokens, mode: tokens ? cacheEligible ? 'three-piles' : 'two-piles' : 'volume-only', writtenAnchor: anchor,
530
+ readToWriteRatio: written && tokens ? (tokens.readFresh + (cacheAbsent ? 0 : tokens.rereadCache)) / written : null,
531
+ typingYearsEstimate: written ? written * WORDS_PER_TOKEN / (40 * 60 * 2000) : null,
532
+ readingMonthsEstimate: written ? written * WORDS_PER_TOKEN / (238 * 60 * 160) : null,
533
+ cacheMastery: {
534
+ eligible: cacheEligible, hitRate, netSavingsUsd: net,
535
+ copy: cacheEligible ? `${pct(hitRate)} of what your agents read came straight from cache.${net === null ? '' : net < 0 ? ' Short threads meant cache writes cost more than reads saved.' : net > 0 ? ' Solid context reuse lowered the list-price API estimate.' : ' Priced cache and no-cache estimates came out even.'}`
536
+ : 'No cache-token breakdown available in these logs.',
537
+ },
538
+ apiEquivalent: {
539
+ eligible: pricing.pricedRequestCount > 0, pricingCatalogDate: PRICING_CATALOG_DATE,
540
+ actualEquivalentUsd: pricing.actualEquivalentUsd, noCacheCounterfactualUsd: cacheEligible ? pricing.noCacheCounterfactualUsd : null,
541
+ pricedCoverageShare: pricing.pricedCoverageShare, unpricedRequestCount: pricing.unpricedRequestCount,
542
+ disclaimer: `API list-price equivalent as of ${PRICING_CATALOG_DATE}. A token estimate separate from billing, subscriptions, negotiated terms, and separately metered tools or storage.`,
543
+ },
544
+ },
545
+ };
546
+ }
547
+ export function buildWinks(d) {
548
+ const winks = [];
549
+ const add = (id, chapter, text) => winks.push({ id, chapter, epistemic: 'observed', text });
550
+ const first = d.humanPrompts[0];
551
+ const clock = (ts) => formatClock(d.local(ts).minuteOfDay);
552
+ if (first)
553
+ add('first-words', 'rhythm', `First recorded prompt, ${d.local(first.tsMs).date} at ${clock(first.tsMs)} local.${first.tsMs - d.bounds.start < 6 * 60 * MINUTE_MS ? ' Midnight barely cleared the runway.' : ''}`);
554
+ const latestClock = d.humanPrompts.reduce((latest, p) => !latest || d.local(p.tsMs).minuteOfDay > d.local(latest.tsMs).minuteOfDay ? p : latest, undefined);
555
+ if (latestClock)
556
+ add('last-call', 'rhythm', `Latest local clock reading for a human prompt was ${clock(latestClock.tsMs)}.`);
557
+ const reasoning = d.agentRequests.filter((r) => d.capability(r.sessionId, 'reasoningTokens') !== 'absent');
558
+ const thought = reasoning.reduce((n, r) => n + r.reasoning, 0);
559
+ const spoken = reasoning.reduce((n, r) => n + Math.max(0, r.output - r.reasoning), 0);
560
+ if (reasoning.length >= 30 && thought && spoken)
561
+ add('thinking-talking', 'scale', `Reported reasoning tokens and other output tokens had a ratio of ${estimate(thought / spoken)} to 1.`);
562
+ const interrupts = d.interrupts.filter((i) => d.capability(i.sessionId, 'interrupts') !== 'absent');
563
+ const interruptPrompts = d.humanPrompts.filter((p) => d.capability(p.sessionId, 'interrupts') !== 'absent');
564
+ if (interrupts.length && interruptPrompts.length)
565
+ add('interrupter', 'craft', `${interrupts.length} interrupts entered the record, or ${estimate(100 * interrupts.length / interruptPrompts.length)} per 100 covered prompts.`);
566
+ const projects = groupBy(d.parentSessions.filter((s) => s.projectHmac), (s) => s.projectHmac);
567
+ if (projects.size) {
568
+ const groups = [...projects.values()];
569
+ const single = groups.filter((s) => s.length === 1).length;
570
+ const biggest = groups.reduce((max, sessions) => Math.max(max, sessions.length), -Infinity);
571
+ const longest = groups.reduce((max, sessions) => {
572
+ const days = dayDistance(d.local(sessions[0].startTsMs).date, d.local(sessions.at(-1).startTsMs).date) + 1;
573
+ return Math.max(max, days);
574
+ }, -Infinity);
575
+ add('project-constellation', 'evolution', `${projects.size} recorded projects, ${single} with one session. The largest accounted for ${pct(biggest / d.parentSessions.length)} of sessions. The longest span between recorded starts covered ${longest} calendar days.`);
576
+ }
577
+ const dayOne = d.agentRequests.find((r) => {
578
+ if (d.capability(r.sessionId, 'modelIds') === 'absent')
579
+ return false;
580
+ const release = normalizeModelId(r.modelId, r.provider).releaseDate;
581
+ if (!release)
582
+ return false;
583
+ const days = dayDistance(release, new Date(r.tsMs).toISOString().slice(0, 10));
584
+ return days >= 0 && days <= 3;
585
+ });
586
+ if (dayOne)
587
+ add('model-day-one', 'evolution', `${normalizeModelId(dayOne.modelId).displayName} first appeared in the recorder within three UTC calendar days of its public release.`);
588
+ return winks;
589
+ }