coauthored 0.0.0-stage → 1.0.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 (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-BkhZFxG9.css +1 -0
  65. package/dist/web/assets/MartianMono-VF-CmJ1nXx9.woff2 +0 -0
  66. package/dist/web/assets/app-Dw1a5h5V.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-D6HyoJCB.js +46 -0
  78. package/dist/web/assets/chunk-DrEayQLY.js +1 -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,75 @@
1
+ const models = new Map();
2
+ function register(provider, family, id, displayName, contextWindowTokens, releaseDate) {
3
+ models.set(id, { provider, family, displayName, contextWindowTokens, ...(releaseDate ? { releaseDate } : {}) });
4
+ }
5
+ for (const [tier, version, window, release] of [
6
+ ['opus', '4', 200_000, '2025-05-22'], ['opus', '4.1', 200_000, '2025-08-05'],
7
+ ['opus', '4.5', 200_000, '2025-11-24'], ['opus', '4.6', 1_000_000, '2026-02-05'],
8
+ ['sonnet', '4', 200_000, '2025-05-22'], ['sonnet', '4.5', 200_000, '2025-09-29'],
9
+ ['sonnet', '4.6', 1_000_000, '2026-02-17'], ['sonnet', '5', 1_000_000, '2026-06-30'],
10
+ ['haiku', '4.5', 200_000, '2025-10-15'], ['haiku', '5.5', 1_000_000, '2026-10-07'],
11
+ ['opus', '5.5', 1_000_000, '2026-09-22'], ['sonnet', '5.5', 1_000_000, '2026-09-28'],
12
+ ]) {
13
+ register('anthropic', `claude-${tier}`, `claude-${tier}-${version}`, `Claude ${tier[0].toUpperCase()}${tier.slice(1)} ${version}`, window, release);
14
+ }
15
+ for (const [id, label, family, window, release] of [
16
+ ['gpt-5-codex', 'GPT-5-Codex', 'gpt-codex', 400_000, '2025-09-15'],
17
+ ['gpt-5.2-codex', 'GPT-5.2-Codex', 'gpt-codex', 400_000, '2025-12-18'],
18
+ ['gpt-5.3-codex', 'GPT-5.3-Codex', 'gpt-codex', 400_000, '2026-02-05'],
19
+ ['gpt-5.4', 'GPT-5.4', 'gpt-5', 1_050_000, '2026-03-05'],
20
+ ['gpt-5.5', 'GPT-5.5', 'gpt-5', 1_050_000, '2026-04-23'],
21
+ ['gpt-6.1-sol', 'GPT-6.1 Sol', 'gpt-sol', 1_050_000, '2026-09-29'],
22
+ ['gpt-6.2-sol', 'GPT-6.2 Sol', 'gpt-sol', 1_050_000, '2026-11-17'],
23
+ ['o3', 'OpenAI o3', 'openai-o', 200_000, '2025-04-16'],
24
+ ['o4-mini', 'OpenAI o4-mini', 'openai-o', 200_000, '2025-04-16'],
25
+ ])
26
+ register('openai', family, id, label, window, release);
27
+ register('google', 'gemini-pro', 'gemini-2.5-pro', 'Gemini 2.5 Pro', 1_048_576, '2025-06-17');
28
+ register('google', 'gemini-flash', 'gemini-2.5-flash', 'Gemini 2.5 Flash', 1_048_576, '2025-06-17');
29
+ register('google', 'gemini-flash', 'gemini-3-flash-preview', 'Gemini 3 Flash', 1_048_576, '2025-12-17');
30
+ register('google', 'gemini-pro', 'gemini-3.1-pro-preview', 'Gemini 3.1 Pro', 1_048_576, '2026-02-19');
31
+ register('google', 'gemini-neon', 'gemini-4-neon', 'Gemini 4 Neon', 1_048_576, '2026-11-18');
32
+ register('deepseek', 'deepseek', 'deepseek-v3.2-exp', 'DeepSeek V3.2-Exp', 131_072, '2025-09-29');
33
+ register('deepseek', 'deepseek', 'deepseek-v3.2', 'DeepSeek V3.2', 131_072, '2025-12-01');
34
+ register('deepseek', 'deepseek-pro', 'deepseek-v4-pro', 'DeepSeek V4 Pro', 1_048_576);
35
+ register('deepseek', 'deepseek-flash', 'deepseek-flash', 'DeepSeek Flash', 1_048_576);
36
+ register('together', 'gpt-oss', 'gpt-oss-120b', 'GPT-OSS 120B', 131_072, '2025-08-05');
37
+ const nativeProviders = new Set(['anthropic', 'openai', 'google', 'deepseek', 'together']);
38
+ export function modelKey(raw) {
39
+ const id = raw.trim().toLowerCase()
40
+ .replace(/^openrouter\//, '')
41
+ .replace(/^(models\/|(?:anthropic|openai|google|deepseek|together)\/)/, '')
42
+ .replace(/^(?:(?:us|eu|apac|global)\.)?anthropic\./, '')
43
+ .replace(/-v\d+:\d+$/, '')
44
+ .replace(/@(20\d{6})$/, '-$1')
45
+ .replace(/(?:\[1m\]|-1m)$/, '')
46
+ .replace(/-(?:20\d{2}-\d{2}-\d{2}|20\d{6})$/, '')
47
+ .replace(/-latest$/, '');
48
+ if (id === 'deepseek-v4-flash' || id === 'deepseek-v4.1-flash-1017')
49
+ return 'deepseek-flash';
50
+ if (id === 'deepseek-v4-pro-0813')
51
+ return 'deepseek-v4-pro';
52
+ return id.replace(/^(claude)-(opus|sonnet|haiku)-(\d+)-(\d+)$/, '$1-$2-$3.$4')
53
+ .replace(/^claude-(\d+)[.-](\d+)-(opus|sonnet|haiku)$/, 'claude-$3-$1.$2')
54
+ .replace(/^claude-(\d+)-(opus|sonnet|haiku)$/, 'claude-$2-$1');
55
+ }
56
+ export function normalizeModelId(raw, providerHint = '') {
57
+ const id = modelKey(raw);
58
+ const known = models.get(id);
59
+ if (known)
60
+ return { ...known };
61
+ const claude = /^claude-(opus|sonnet|haiku)-(\d+(?:\.\d+)?)$/.exec(id);
62
+ if (claude) {
63
+ const [, tier, version] = claude;
64
+ return { provider: 'anthropic', family: `claude-${tier}`, displayName: `Claude ${tier[0].toUpperCase()}${tier.slice(1)} ${version}`, contextWindowTokens: null };
65
+ }
66
+ const provider = providerHint.toLowerCase();
67
+ return { provider: nativeProviders.has(provider) ? provider : 'unknown', family: 'unknown', displayName: 'Unlisted model', contextWindowTokens: null };
68
+ }
69
+ export function contextFill(request) {
70
+ if (request.contextFillTokens === undefined)
71
+ return null;
72
+ const limit = normalizeModelId(request.modelId, request.provider).contextWindowTokens;
73
+ const input = request.contextFillTokens;
74
+ return limit && Number.isFinite(input) && input > 0 ? Math.min(100, Math.max(0, 100 * input / limit)) : null;
75
+ }
@@ -0,0 +1,121 @@
1
+ import { modelKey, normalizeModelId } from './models.js';
2
+ export const PRICING_CATALOG_DATE = '2026-12-03';
3
+ const anthropic = 'https://platform.claude.com/docs/en/about-claude/pricing';
4
+ const openai = 'https://developers.openai.com/api/docs/pricing';
5
+ const google = 'https://aistudio.google.com/docs/pricing';
6
+ const deepseek = 'https://api-docs.deepseek.com/quick_start/pricing/';
7
+ export const PRICING_CATALOG = {
8
+ 'claude-opus-4': { provider: 'anthropic', source: anthropic, rates: [15000, 75000, 1500, 18750, 30000] },
9
+ 'claude-opus-4.1': { provider: 'anthropic', source: anthropic, rates: [15000, 75000, 1500, 18750, 30000] },
10
+ 'claude-opus-4.5': { provider: 'anthropic', source: anthropic, rates: [5000, 25000, 500, 6250, 10000] },
11
+ 'claude-opus-4.6': { provider: 'anthropic', source: anthropic, rates: [5000, 25000, 500, 6250, 10000] },
12
+ 'claude-opus-5.5': { provider: 'anthropic', source: anthropic, rates: [4000, 20000, 200, 5000, 8000] },
13
+ 'claude-sonnet-4': { provider: 'anthropic', source: anthropic, rates: [3000, 15000, 300, 3750, 6000], long: { above: 200000, rates: [6000, 22500, 600, 7500, 12000] } },
14
+ 'claude-sonnet-4.5': { provider: 'anthropic', source: anthropic, rates: [3000, 15000, 300, 3750, 6000], long: { above: 200000, rates: [6000, 22500, 600, 7500, 12000] } },
15
+ 'claude-sonnet-4.6': { provider: 'anthropic', source: anthropic, rates: [3000, 15000, 300, 3750, 6000] },
16
+ 'claude-sonnet-5': { provider: 'anthropic', source: anthropic, rates: [2000, 10000, 200, 2500, 4000] },
17
+ 'claude-sonnet-5.5': { provider: 'anthropic', source: anthropic, rates: [2000, 10000, 100, 2500, 4000] },
18
+ 'claude-haiku-4.5': { provider: 'anthropic', source: anthropic, rates: [1000, 5000, 100, 1250, 2000] },
19
+ 'claude-haiku-5.5': { provider: 'anthropic', source: anthropic, rates: [100, 500, 10, 125, 200], long: { above: 100000, rates: [500, 2500, 50, 625, 1000] } },
20
+ 'gpt-5-codex': { provider: 'openai', source: 'https://developers.openai.com/api/docs/models/gpt-5-codex', rates: [1250, 10000, 125] },
21
+ 'gpt-5.2-codex': { provider: 'openai', source: 'https://developers.openai.com/api/docs/models/gpt-5.2-codex', rates: [1750, 14000, 175] },
22
+ 'gpt-5.3-codex': { provider: 'openai', source: 'https://developers.openai.com/api/docs/models/gpt-5.3-codex', rates: [1750, 14000, 175] },
23
+ 'gpt-5.4': { provider: 'openai', source: openai, rates: [2500, 15000, 250], long: { above: 272000, rates: [5000, 22500, 500] } },
24
+ 'gpt-5.5': { provider: 'openai', source: 'https://developers.openai.com/api/docs/models/gpt-5.5', rates: [5000, 30000, 500], long: { above: 272000, rates: [10000, 45000, 1000] } },
25
+ 'gpt-6.1-sol': { provider: 'openai', source: openai, rates: [2000, 10000, 100, 2500, 5000] },
26
+ 'gpt-6.2-sol': { provider: 'openai', source: openai, rates: [2000, 10000, 100, 2500, 5000] },
27
+ o3: { provider: 'openai', source: openai, rates: [2000, 8000, 500], effectiveFrom: '2025-06-10' },
28
+ 'o3-launch-rate': { provider: 'openai', source: 'https://community.openai.com/t/o3-is-80-cheaper-and-introducing-o3-pro/1284925', rates: [10000, 40000, 2500], effectiveFrom: '2025-04-16', effectiveUntil: '2025-06-10' },
29
+ 'o4-mini': { provider: 'openai', source: 'https://developers.openai.com/api/docs/models/o4-mini', rates: [1100, 4400, 275] },
30
+ 'gemini-2.5-pro': { provider: 'google', source: google, rates: [1250, 10000, 125], long: { above: 200000, rates: [2500, 15000, 250] } },
31
+ 'gemini-2.5-flash': { provider: 'google', source: google, rates: [300, 2500, 30] },
32
+ 'gemini-3-flash-preview': { provider: 'google', source: google, rates: [500, 3000, 50] },
33
+ 'gemini-3.1-pro-preview': { provider: 'google', source: google, rates: [2000, 12000, 200], long: { above: 200000, rates: [4000, 18000, 400] } },
34
+ 'gemini-4-neon': { provider: 'google', source: 'https://blog.google/innovation-and-ai/models-and-research/gemini-models/introducing-gemini-4-neon/', rates: [3000, 15000, 150] },
35
+ 'deepseek-v3.2-exp': { provider: 'deepseek', source: 'https://api-docs.deepseek.com/news/news250929/', rates: [280, 420, 28], effectiveFrom: '2025-09-29T10:00:00Z', effectiveUntil: '2025-12-01' },
36
+ 'deepseek-v3.2': { provider: 'deepseek', source: 'https://api-docs.deepseek.com/news/news251201/', rates: [280, 420, 28] },
37
+ 'deepseek-v4-pro': { provider: 'deepseek', source: deepseek, rates: [660, 1980, 22], peak: [1320, 3960, 44], effectiveFrom: '2026-08-16T16:00:00Z' },
38
+ 'deepseek-flash': { provider: 'deepseek', source: deepseek, rates: [150, 600, 3], peak: [300, 1200, 6], effectiveFrom: '2026-09-10T04:00:00Z' },
39
+ 'gpt-oss-120b': { provider: 'together', source: 'https://www.together.ai/models/gpt-oss-120b', rates: [150, 600] },
40
+ };
41
+ const CHINA_HOLIDAYS_2026 = [
42
+ ['01-01', '01-03'], ['02-15', '02-23'], ['04-04', '04-06'], ['05-01', '05-05'],
43
+ ['06-19', '06-21'], ['09-25', '09-27'], ['10-01', '10-07'],
44
+ ];
45
+ function isDeepSeekPeak(ts) {
46
+ const date = new Date(ts);
47
+ const hour = date.getUTCHours();
48
+ if (date.getUTCDay() === 0 || date.getUTCDay() === 6 || !((hour >= 1 && hour < 4) || (hour >= 6 && hour < 10)))
49
+ return false;
50
+ const civilDay = new Date(ts + 8 * 3_600_000).toISOString().slice(5, 10);
51
+ return !CHINA_HOLIDAYS_2026.some(([start, end]) => civilDay >= start && civilDay <= end);
52
+ }
53
+ export function priceRequest(request) {
54
+ let id = modelKey(request.modelId);
55
+ const ts = request.tsMs ?? Date.parse(PRICING_CATALOG_DATE);
56
+ if (!Number.isFinite(ts))
57
+ return null;
58
+ if (id === 'o3' && ts < Date.parse('2025-06-10'))
59
+ id = 'o3-launch-rate';
60
+ if (id === 'deepseek-chat' || id === 'deepseek-reasoner') {
61
+ if (ts >= Date.parse('2025-12-01') && ts < Date.parse('2026-04-24'))
62
+ id = 'deepseek-v3.2';
63
+ else if (ts >= Date.parse('2025-09-29T10:00:00Z') && ts < Date.parse('2025-12-01'))
64
+ id = 'deepseek-v3.2-exp';
65
+ }
66
+ const tariff = Object.hasOwn(PRICING_CATALOG, id) ? PRICING_CATALOG[id] : undefined;
67
+ if (!tariff)
68
+ return null;
69
+ const provider = request.provider.trim().toLowerCase();
70
+ const directProvider = { 'google-ai': 'google', gemini: 'google' }[provider] ?? provider;
71
+ if (directProvider !== tariff.provider)
72
+ return null;
73
+ const from = tariff.effectiveFrom ?? normalizeModelId(id).releaseDate;
74
+ if ((from && ts < Date.parse(from)) || (tariff.effectiveUntil && ts >= Date.parse(tariff.effectiveUntil)))
75
+ return null;
76
+ const usesOpenAiWrites = id === 'gpt-6.1-sol' || id === 'gpt-6.2-sol';
77
+ if (usesOpenAiWrites && (request.cacheWrite5m || request.cacheWrite1h))
78
+ return null;
79
+ if (!usesOpenAiWrites && (request.cacheWrite30m || request.cacheWrite12h))
80
+ return null;
81
+ const short = usesOpenAiWrites ? request.cacheWrite30m ?? 0 : request.cacheWrite5m;
82
+ const long = usesOpenAiWrites ? request.cacheWrite12h ?? 0 : request.cacheWrite1h;
83
+ const tokens = [request.inputUncached, request.output, request.cacheRead, short, long];
84
+ if (!tokens.every((value) => Number.isSafeInteger(value) && value >= 0))
85
+ return null;
86
+ const input = request.inputUncached + request.cacheRead + short + long;
87
+ if (tariff.peak && new Date(ts).getUTCFullYear() !== 2026)
88
+ return null;
89
+ const rates = tariff.long && input > tariff.long.above ? tariff.long.rates
90
+ : tariff.peak && isDeepSeekPeak(ts) ? tariff.peak : tariff.rates;
91
+ let actualMilliMicros = 0n;
92
+ for (const [i, count] of tokens.entries()) {
93
+ const rate = rates[i];
94
+ if (count && rate === undefined)
95
+ return null;
96
+ actualMilliMicros += BigInt(count) * BigInt(rate ?? 0);
97
+ }
98
+ const inputTokens = BigInt(request.inputUncached) + BigInt(request.cacheRead) + BigInt(short) + BigInt(long);
99
+ const noCacheMilliMicros = inputTokens * BigInt(rates[0]) + BigInt(request.output) * BigInt(rates[1]);
100
+ return { actualMilliMicros, noCacheMilliMicros, netSavingsMilliMicros: noCacheMilliMicros - actualMilliMicros };
101
+ }
102
+ export const milliMicrosToUsd = (amount) => Number(amount) / 1_000_000_000;
103
+ export function computePricing(requests, measured = () => true) {
104
+ let actualMilliMicros = 0n, noCacheMilliMicros = 0n, pricedRequestCount = 0;
105
+ for (const request of requests) {
106
+ const price = measured(request) ? priceRequest(request) : null;
107
+ if (!price)
108
+ continue;
109
+ actualMilliMicros += price.actualMilliMicros;
110
+ noCacheMilliMicros += price.noCacheMilliMicros;
111
+ pricedRequestCount++;
112
+ }
113
+ return {
114
+ actualMilliMicros, noCacheMilliMicros, netSavingsMilliMicros: noCacheMilliMicros - actualMilliMicros,
115
+ actualEquivalentUsd: milliMicrosToUsd(actualMilliMicros),
116
+ noCacheCounterfactualUsd: pricedRequestCount ? milliMicrosToUsd(noCacheMilliMicros) : null,
117
+ netSavingsUsd: pricedRequestCount ? milliMicrosToUsd(noCacheMilliMicros - actualMilliMicros) : null,
118
+ unpricedRequestCount: requests.length - pricedRequestCount,
119
+ pricedRequestCount, pricedCoverageShare: requests.length ? pricedRequestCount / requests.length : 0,
120
+ };
121
+ }
@@ -0,0 +1,115 @@
1
+ import { estimate, fnv1a, pct } from './dataset.js';
2
+ export function recorderIdentity(seed, year, cancelled = false) {
3
+ const code = (seed >>> 0).toString(36).toUpperCase().padStart(4, '0').slice(-4);
4
+ const registration = `N-${code}`;
5
+ const docketNumber = `CR-${year}-${code}`;
6
+ const statsSeedHex = (seed >>> 0).toString(16).padStart(8, '0') + fnv1a(docketNumber, seed).toString(16).padStart(8, '0');
7
+ return {
8
+ registration, docketNumber, statsSeedHex,
9
+ deadWaxInscription: `${registration} · ${docketNumber} · RECORDER RETURNED TO CREW`,
10
+ exitCodeNote: cancelled
11
+ ? { displayCode: 130, reason: 'Readout stopped at the crew’s request.' }
12
+ : { displayCode: 0, reason: 'Local readout complete.' },
13
+ };
14
+ }
15
+ export function writeDetermination(evidence) {
16
+ const { year, format, craft, delegation, evolution, scale, totals, capturedWindow } = evidence;
17
+ const orchestra = delegation.orchestra;
18
+ const turning = evolution.turningPoint;
19
+ const readEdit = craft.readEditRatio;
20
+ const truncated = capturedWindow.perHarness.some((h) => h.likelyTruncated);
21
+ let headline, basis;
22
+ if (format === 'empty') {
23
+ headline = 'No logs found. Radio silence is still a stat.';
24
+ basis = 'Nothing in the selected calendar window matched a supported session log.';
25
+ }
26
+ else if (format === 'preliminary') {
27
+ headline = 'Just getting started. Early sessions are on the tape.';
28
+ basis = `${totals.sessions} sessions across ${capturedWindow.activeDays} active days so far.`;
29
+ }
30
+ else if (orchestra.eligible && orchestra.maxConcurrent >= 2) {
31
+ headline = `Running up to ${orchestra.maxConcurrent} agents at once like it’s a normal Tuesday.`;
32
+ basis = `${orchestra.totalSpawns.toLocaleString('en-US')} subagent launches logged, peaking at ${orchestra.maxConcurrent} active in parallel.`;
33
+ }
34
+ else if (turning.detected && evolution.modelRiver.migration.detected) {
35
+ headline = 'Swapped stacks mid-year and shifted into a higher gear.';
36
+ basis = `Model switch started the week of ${evolution.modelRiver.migration.weekStart}; weekly volume shifted the week of ${turning.weekStart} (p ≈ ${estimate(turning.pValue)}).`;
37
+ }
38
+ else if (readEdit !== null && readEdit >= 3) {
39
+ headline = `You read ${estimate(readEdit)}× more than you edit. Actually reading the codebase before touching it.`;
40
+ basis = `${estimate(readEdit)} investigate calls for every modify call across the tool stream.`;
41
+ }
42
+ else if (scale.cacheMastery.eligible && scale.cacheMastery.hitRate >= 0.8) {
43
+ headline = `Built one deep context and lived in it (${pct(scale.cacheMastery.hitRate)} cache hits).`;
44
+ basis = `Prompt cache reads covered ${pct(scale.cacheMastery.hitRate)} of measured input tokens.`;
45
+ }
46
+ else if (evidence.rhythm.solarNoon.chronotype === 'Nocturnal' && evidence.rhythm.solarNoon.peakTimeFormatted) {
47
+ headline = `Starting fresh sessions around ${evidence.rhythm.solarNoon.peakTimeFormatted} like tomorrow can wait.`;
48
+ basis = `Human prompt clock centered on ${evidence.rhythm.solarNoon.peakTimeFormatted} local time.`;
49
+ }
50
+ else if (truncated) {
51
+ headline = 'Half-missing tape from 30-day log cleanup — here’s the stretch that survived.';
52
+ basis = `Captured window spans ${capturedWindow.daysSpanned} days; at least one tool rotated older logs out.`;
53
+ }
54
+ else {
55
+ headline = 'Steady, predictable tape — no sudden spikes or surprises.';
56
+ basis = totals.humanPrompts
57
+ ? `${totals.sessions.toLocaleString('en-US')} sessions and ${totals.humanPrompts.toLocaleString('en-US')} prompts made it onto the tape.`
58
+ : `${totals.sessions.toLocaleString('en-US')} sessions made it onto the tape.`;
59
+ }
60
+ const next = year + 1;
61
+ let safetyRecommendations;
62
+ if (format === 'empty') {
63
+ safetyRecommendations = [
64
+ { id: 'R-1', text: 'Point --input at your tool log directory or check whether local retention cleared older transcripts.' },
65
+ { id: 'R-2', text: 'Verify that your target year and timezone match the dates of your recorded coding sessions.' },
66
+ ];
67
+ }
68
+ else if (format === 'preliminary') {
69
+ safetyRecommendations = [
70
+ { id: 'R-1', text: 'Check back after a few more weeks of coding — full archetype scoring kicks in past 10 sessions.' },
71
+ { id: 'R-2', text: `Review your tool’s retention settings now if you want all of ${next} preserved locally.` },
72
+ ];
73
+ }
74
+ else if (truncated) {
75
+ safetyRecommendations = [
76
+ { id: 'R-1', text: `Raise your local transcript retention limit for ${next} so 30-day rotation does not clip half the year.` },
77
+ { id: 'R-2', text: 'Enable full token and tool telemetry where supported if you want cache and tool-mix breakdowns.' },
78
+ ];
79
+ }
80
+ else if (orchestra.eligible && orchestra.maxConcurrent >= 2) {
81
+ safetyRecommendations = [
82
+ { id: 'R-1', text: `With up to ${orchestra.maxConcurrent} agents active together, keep clear branch or worktree boundaries so edits do not collide.` },
83
+ { id: 'R-2', text: evidence.rhythm.solarNoon.chronotype === 'Nocturnal'
84
+ ? 'Late-night marathons stack up fast — set a hard stop before compaction loops stretch into dawn.'
85
+ : 'Check in on long parallel runs before context compaction resets their working assumptions.' },
86
+ ];
87
+ }
88
+ else if (evolution.harnessPolyglot.harnessCount >= 2 && (turning.detected || evolution.modelRiver.migration.detected)) {
89
+ safetyRecommendations = [
90
+ { id: 'R-1', text: `You split work across ${evolution.harnessPolyglot.harnessCount} harnesses — keep shared instructions in repo-level files so every tool gets the same context.` },
91
+ { id: 'R-2', text: 'Review model-routing defaults after stack switches so lighter tasks do not stay pinned to heavyweight models.' },
92
+ ];
93
+ }
94
+ else if (readEdit !== null && readEdit >= 3) {
95
+ safetyRecommendations = [
96
+ { id: 'R-1', text: 'Keep leading with read-heavy recon — your agents clearly mirror thorough codebase investigation.' },
97
+ { id: 'R-2', text: scale.cacheMastery.eligible && scale.cacheMastery.hitRate >= 0.85
98
+ ? 'Your long threads earn high cache reuse; keep related follow-ups in the same session until context fills.'
99
+ : 'Watch context fill on multi-hour sessions so compaction does not drop earlier findings.' },
100
+ ];
101
+ }
102
+ else {
103
+ safetyRecommendations = [
104
+ { id: 'R-1', text: `Check local retention settings across your coding tools if you want a complete ${next} record.` },
105
+ { id: 'R-2', text: 'Keep long-running tasks scoped to clean checkpoints so sessions stay easy to steer.' },
106
+ ];
107
+ }
108
+ if (scale.cacheMastery.netSavingsUsd !== null && scale.cacheMastery.netSavingsUsd < 0) {
109
+ safetyRecommendations.push({ id: 'R-3', text: 'Batch quick one-off questions into a running thread so prompt cache writes pay for themselves.' });
110
+ }
111
+ return {
112
+ probableCause: { epistemic: 'interpretation', headline, evidence: basis },
113
+ safetyRecommendations,
114
+ };
115
+ }
@@ -0,0 +1,162 @@
1
+ import { classifyOperator } from './archetypes.js';
2
+ import { estimate, formatCompactTokens, formatDuration, formatShortDate, formatUsd, HARNESS_NAMES, NEVER_READ, pct, prepareDataset, safeLabel } from './dataset.js';
3
+ import { buildFdr, buildMainEvent } from './fdr.js';
4
+ import { buildHelicorder, peakAndQuiet } from './helicorder.js';
5
+ import { buildCraft, buildDelegation, buildEvolution, buildRhythm, buildScale, buildWinks } from './insights.js';
6
+ import { modelKey } from './models.js';
7
+ import { PRICING_CATALOG_DATE } from './pricing.js';
8
+ import { recorderIdentity, writeDetermination } from './probable-cause.js';
9
+ import { buildContentChapter } from './content/analyzer.js';
10
+ import { ACTIVE_GAP_MINUTES } from './time.js';
11
+ const FORMATS = {
12
+ zero: 'empty', micro: 'preliminary', small: 'factual', medium: 'factual',
13
+ large: 'final-with-appendices', massive: 'final-with-appendices',
14
+ };
15
+ function density(count, days) {
16
+ if (!count)
17
+ return 'zero';
18
+ if (count <= 10 || days <= 5)
19
+ return 'micro';
20
+ if (count <= 60)
21
+ return 'small';
22
+ if (count <= 400)
23
+ return 'medium';
24
+ return count < 1500 ? 'large' : 'massive';
25
+ }
26
+ const METHODS = [
27
+ { metric: 'Captured window', epistemic: 'observed', formula: 'Local calendar dates from recovered events and clipped session bounds inside January 1 through the instant before the following January 1. No annualization.' },
28
+ { metric: 'Active time and parallelism', epistemic: 'estimated', formula: 'Merge per-session human prompts, model requests, and tool calls at gaps of at most 10 minutes, with one minute for isolated events. A session start is used when event timestamps are missing. The union is wall time. Summed session spans divided by the union gives parallelism. Sensitivity repeats the method at 5 and 15 minutes.' },
29
+ { metric: 'Solar Noon', epistemic: 'observed', formula: 'Circular mean and resultant length in the selected IANA zone. Evenly spaced samples cap each 04:00-based coding day at 30 timestamps. A human chronotype requires 40 prompts on at least five days. An agent clock can stand in when the human clock is unavailable.' },
30
+ { metric: 'Witching Hour', epistemic: 'observed', formula: 'Observed cell divided by the expected count from weekday and hour marginals. Use the highest lift above the cell minimum or the raw maximum when no cell qualifies.' },
31
+ { metric: 'Night, streak, and exhale', epistemic: 'estimated', formula: 'Night spans overlap local 22:00–05:00 and include at least three prompts. Streak and exhale use 04:00-based coding days with at least one human prompt and five active minutes.' },
32
+ { metric: 'Weekday and weekend', epistemic: 'observed', formula: 'Two-sided Mann–Whitney U with normal approximation, tie and continuity correction on active-day minutes. Effect is the ratio of means. Requires p < 0.05 and a ratio of at least 1.4 or at most 0.7.' },
33
+ { metric: 'Tool shape and leash', epistemic: 'observed', formula: 'Investigation calls divided by modify calls. Recovery checks the next three calls in the session for a measured success of the same family. Leash counts actions until the next prompt or end of the session tree, with the 90th quantile interpolated.' },
34
+ { metric: 'Compaction and delegation', epistemic: 'estimated', formula: 'Survival requires at least five later requests in the same session. Context fill divides measured input by the published model window. A sweep of half-open child active spans gives peak concurrency. Unattended activity is the wall-clock union at least 30 minutes after the most recent prompt in its session tree.' },
35
+ { metric: 'Turning point and migration', epistemic: 'observed', formula: 'Search each split with four complete weeks on either side using absolute log ratio of means. Repeat the full search on 1,000 deterministic shuffles. A turning point needs p < 0.05 and a ratio of at least 1.5 or at most 0.67. Migration requires the new family to hold at least half for four consecutive weeks.' },
36
+ { metric: 'Harness loyalty', epistemic: 'observed', formula: 'One minus Shannon entropy normalized by the log of the number of harnesses with measured human prompts.' },
37
+ { metric: 'Written scale', epistemic: 'estimated', formula: 'Only output tokens enter the text comparison. Reading and typing assume 0.75 English words per token, 40 typing words per minute, 238 silent reading words per minute, 2,000 working hours per year and 160 per month.' },
38
+ { metric: 'API list-price equivalent', epistemic: 'estimated', formula: 'Apply dated Standard text rates to disjoint request token buckets in integer thousandths of a micro-dollar. Unresolved provider routes, models, rates or cache durations are excluded. Counterfactual prices the same priced input as uncached and holds output fixed. Report coverage is measured in requests.' },
39
+ { metric: 'Classification', epistemic: 'interpretation', formula: 'Ten versioned formulas use editorial calibration anchors and capability gates. A score of at least 0.50 qualifies. A fixed order resolves scores within 0.03 of the maximum.' },
40
+ { metric: 'Flight recorder traces', epistemic: 'observed', formula: 'Helicorder amplitude divides each local half-hour count by the largest bucket. FDR points aggregate metadata by local Monday week. CVR entries use fixed labels and elapsed time only.' },
41
+ ];
42
+ export function buildWrappedReport(dataset, options = {}) {
43
+ const generatedAtIso = new Date(options.generatedAtIso ?? Date.now()).toISOString();
44
+ const d = prepareDataset(dataset, Date.parse(generatedAtIso));
45
+ const densityTier = density(d.parentSessions.length, d.capturedWindow.activeDays);
46
+ const format = FORMATS[densityTier];
47
+ let night = null;
48
+ const rhythm = buildRhythm(d, options.content ? span => { night = span; } : undefined);
49
+ const craft = buildCraft(d);
50
+ const delegation = buildDelegation(d, rhythm.solarNoon.chronotype === 'Nocturnal');
51
+ const evolution = buildEvolution(d);
52
+ const { scale, tokens } = buildScale(d);
53
+ const { startTsMs: mainEventStart, sessionId: mainSession, ...mainEvent } = buildMainEvent(d, options.content ? true : options.contentAttempted ? 'attempted' : false);
54
+ const peakMinute = rhythm.solarNoon.clockSource === 'human' ? rhythm.solarNoon.peakMinuteOfDay : null;
55
+ const rhythmHour = peakMinute === null ? null : Math.floor(peakMinute / 60);
56
+ const content = options.content && ('finish' in options.content ?
57
+ buildContentChapter(options.content, { data: d, night, mainSession, rhythmHour }) : options.content);
58
+ const helicorder = buildHelicorder(d, rhythm, mainEventStart, evolution);
59
+ const archetype = classifyOperator(d, densityTier, rhythm, craft, delegation, evolution);
60
+ const { wallClockActiveMinutes, wallClockSensitivity5m, wallClockSensitivity15m, agentActiveMinutes, parallelismFactor, } = d.active;
61
+ const totals = {
62
+ sessions: d.parentSessions.length, subagentSessions: d.sessions.length - d.parentSessions.length,
63
+ humanPrompts: d.humanPrompts.length, agentRequests: d.agentRequests.length, toolCalls: d.toolCalls.length,
64
+ compactions: d.compactions.length, interrupts: d.interrupts.length,
65
+ distinctProjects: new Set(d.parentSessions.map((s) => s.projectHmac).filter(Boolean)).size,
66
+ harnessesUsed: d.capturedWindow.perHarness.length,
67
+ modelsUsed: new Set(d.agentRequests.filter((r) => d.capability(r.sessionId, 'modelIds') !== 'absent')
68
+ .map((r) => modelKey(r.modelId)).filter((id) => id && id !== 'unknown')).size,
69
+ wallClockActiveMinutes, wallClockSensitivity5m, wallClockSensitivity15m, agentActiveMinutes, parallelismFactor, tokens,
70
+ };
71
+ const findings = [];
72
+ const finding = (epistemic, statement, datum, methodNote) => {
73
+ if (findings.length < 6)
74
+ findings.push({
75
+ id: `F-${findings.length + 1}`, epistemic, statement, datum, ...(methodNote ? { methodNote } : {}),
76
+ });
77
+ };
78
+ const shareableStats = [];
79
+ const share = (id, label, value, epistemic, defaultSelected = false, sensitiveByDefault = false) => shareableStats.push({ id, label, value: String(value), epistemic, defaultSelected, sensitiveByDefault });
80
+ if (totals.sessions) {
81
+ const formatted = totals.sessions.toLocaleString('en-US');
82
+ finding('observed', `${formatted} sessions on the tape.`, formatted);
83
+ share('sessions', 'Recorded sessions', formatted, 'observed', true);
84
+ }
85
+ if (rhythm.solarNoon.peakTimeFormatted && rhythm.solarNoon.clockSource === 'human') {
86
+ finding('observed', rhythm.solarNoon.copy, rhythm.solarNoon.peakTimeFormatted);
87
+ share('solar-noon', 'Human prompt clock', rhythm.solarNoon.peakTimeFormatted, 'observed', false, true);
88
+ }
89
+ if (delegation.orchestra.eligible) {
90
+ const formatted = delegation.orchestra.totalSpawns.toLocaleString('en-US');
91
+ finding('observed', delegation.orchestra.copy, formatted);
92
+ share('launches', 'Subagent launches', formatted, 'observed', true);
93
+ }
94
+ if (evolution.turningPoint.detected) {
95
+ finding('observed', evolution.turningPoint.copy, evolution.turningPoint.weekStart);
96
+ }
97
+ if (scale.cacheMastery.eligible) {
98
+ const hit = pct(scale.cacheMastery.hitRate);
99
+ finding('observed', `${hit} of what your agents read was already cached.`, hit);
100
+ share('cache-share', 'Cache reads', hit, 'observed');
101
+ }
102
+ if (tokens?.written && d.capabilities.tokenBreakdown === 'present') {
103
+ const compact = formatCompactTokens(tokens.written);
104
+ finding('observed', `Your agents wrote ${compact} tokens.`, compact);
105
+ share('written', 'Written tokens', compact, 'observed', true);
106
+ }
107
+ if (totals.wallClockActiveMinutes > 0 && format !== 'empty') {
108
+ share('active-time', 'Wall-clock active time', `≈ ${estimate(totals.wallClockActiveMinutes / 60)} h`, 'estimated', true);
109
+ }
110
+ if (delegation.parallelism.eligible)
111
+ share('parallelism', 'Parallelism factor', `≈ ${estimate(delegation.parallelism.factor)}×`, 'estimated');
112
+ if (scale.apiEquivalent.eligible) {
113
+ share('api-equivalent', 'API list-price equivalent', formatUsd(scale.apiEquivalent.actualEquivalentUsd), 'estimated', false, true);
114
+ }
115
+ if (rhythm.streaks.longestStreakRange)
116
+ share('streak', 'Longest coding streak', `${rhythm.streaks.longestStreakDays} days`, 'observed');
117
+ const { peak, quiet } = peakAndQuiet(d);
118
+ if (peak && d.capturedWindow.activeDays >= 5) {
119
+ const dur = formatDuration(peak.minutes);
120
+ const dayLabel = formatShortDate(peak.date);
121
+ finding('estimated', `Biggest coding day: ≈ ${dur} on ${dayLabel}.`, `≈ ${dur} (${dayLabel})`);
122
+ }
123
+ if (quiet && d.capabilities.humanPromptTimestamps === 'present') {
124
+ const weekLabel = formatShortDate(quiet.date);
125
+ const countLabel = quiet.prompts.toLocaleString('en-US');
126
+ finding('observed', `Quietest full week on the tape: ${countLabel} prompts, week of ${weekLabel}.`, `${countLabel} prompts`);
127
+ }
128
+ if (scale.writtenAnchor && d.capabilities.tokenBreakdown === 'present') {
129
+ finding('interpretation', scale.writtenAnchor.metaphorCopy, scale.writtenAnchor.anchorTitle, scale.writtenAnchor.methodNote);
130
+ }
131
+ if (format === 'empty')
132
+ finding('observed', 'No sessions showed up in this calendar window.', 'None recorded');
133
+ const identity = recorderIdentity(d.seed, d.year, options.cancelled);
134
+ const determination = writeDetermination({ year: d.year, format, rhythm, craft, delegation, evolution, scale, totals, capturedWindow: d.capturedWindow });
135
+ const receipt = {
136
+ algorithmVersion: '1.0.0', pricingCatalogDate: PRICING_CATALOG_DATE, activeTimeGapMinutes: ACTIVE_GAP_MINUTES, externalBytesSent: 0,
137
+ extractedFieldCategories: ['Session and event timestamps', 'Recorder and public model identifiers', 'Token counters', 'Tool families and status flags', 'Compaction and interrupt markers', 'Local project grouping'],
138
+ discardedFieldCategories: [...(content ? NEVER_READ.slice(2) : NEVER_READ), 'Local file paths', 'Project grouping identifiers', 'Raw session and request identifiers'],
139
+ ...(content ? { content: content.receipt } : {}),
140
+ sources: [...dataset.summaries].sort((a, b) => a.candidateId.localeCompare(b.candidateId)).map((s, i) => ({
141
+ candidateId: /^rec_[a-zA-Z0-9_-]{1,32}$/.test(s.candidateId) ? s.candidateId : `rec_source_${i + 1}`,
142
+ harness: s.harness, displayName: HARNESS_NAMES[s.harness],
143
+ adapterVersion: /^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,31}$/.test(s.adapterVersion) ? safeLabel(s.adapterVersion, 'unknown', 32) : 'unknown',
144
+ snapshotMethod: s.snapshotMethod, filesSeen: s.filesSeen, filesOk: s.filesOk, filesQuarantined: s.filesQuarantined,
145
+ linesSeen: s.linesSeen, linesSkipped: s.linesSkipped, bytesRead: s.bytesRead,
146
+ failureCodes: s.failureCodes.filter((code) => /^[A-Z][A-Z_0-9-]{1,49}$/.test(code)).sort(),
147
+ })),
148
+ absentCapabilities: Object.entries(d.capabilities).filter(([, status]) => status === 'absent').map(([key]) => key),
149
+ methods: METHODS.map((method) => ({ ...method })),
150
+ };
151
+ return {
152
+ schemaVersion: '1.1.0', generatorVersion: safeLabel(options.generatorVersion, '1.0.0', 32),
153
+ generatedAtIso,
154
+ isDemo: options.isDemo ?? !!options.demoProfileId, ...(options.demoProfileId ? { demoProfileId: options.demoProfileId } : {}),
155
+ year: d.year, timezone: d.timezone,
156
+ investigatorLabel: safeLabel(options.investigatorInitials ?? options.investigatorLabel, 'the crew'),
157
+ ...identity, format, densityTier, capturedWindow: d.capturedWindow, capabilities: d.capabilities, totals, helicorder,
158
+ fdrChannels: buildFdr(d, evolution), rhythm, craft, delegation, mainEvent, evolution, scale,
159
+ findings, ...determination, archetype, winks: buildWinks(d), shareableStats, receipt,
160
+ ...(content ? { content } : {}),
161
+ };
162
+ }
@@ -0,0 +1,91 @@
1
+ import { mulberry32 } from './dataset.js';
2
+ /** Two-sided normal approximation with midranks, ties and continuity correction. */
3
+ export function mannWhitneyU(a, b) {
4
+ if (!a.length || !b.length)
5
+ return null;
6
+ const combined = [...a.map((value) => ({ value, first: true })), ...b.map((value) => ({ value, first: false }))]
7
+ .sort((x, y) => x.value - y.value);
8
+ let rankSum = 0, ties = 0;
9
+ for (let i = 0; i < combined.length;) {
10
+ let j = i + 1;
11
+ while (j < combined.length && combined[j].value === combined[i].value)
12
+ j++;
13
+ const rank = (i + 1 + j) / 2;
14
+ for (let k = i; k < j; k++)
15
+ if (combined[k].first)
16
+ rankSum += rank;
17
+ const t = j - i;
18
+ ties += t ** 3 - t;
19
+ i = j;
20
+ }
21
+ const product = a.length * b.length;
22
+ const uA = rankSum - a.length * (a.length + 1) / 2;
23
+ const u = Math.min(uA, product - uA);
24
+ const n = combined.length;
25
+ const variance = product / 12 * (n + 1 - ties / (n * (n - 1)));
26
+ if (variance <= 0)
27
+ return { u, uA, pValue: 1 };
28
+ const z = Math.max(0, product / 2 - u - 0.5) / Math.sqrt(variance);
29
+ if (z === 0)
30
+ return { u, uA, pValue: 1 };
31
+ // A&S 7.1.26 approximation to the complementary error function.
32
+ const x = z / Math.SQRT2;
33
+ const t = 1 / (1 + 0.3275911 * x);
34
+ const rawP = (((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t) * Math.exp(-x * x);
35
+ const pValue = Math.min(1, Math.max(0, rawP));
36
+ return { u, uA, pValue };
37
+ }
38
+ function strongestSplit(values) {
39
+ const total = values.reduce((a, b) => a + b, 0);
40
+ let prefix = 0;
41
+ let best = { split: 4, ratio: 1, score: 0, before: 0, after: 0 };
42
+ for (let i = 1; i <= values.length - 4; i++) {
43
+ prefix += values[i - 1];
44
+ if (i < 4)
45
+ continue;
46
+ const before = prefix / i;
47
+ const after = Math.max(0, total - prefix) / (values.length - i);
48
+ if (before <= 0 || after <= 0)
49
+ continue;
50
+ const ratio = after / before;
51
+ const score = Math.abs(Math.log(ratio));
52
+ if (score > best.score)
53
+ best = { split: i, ratio, score, before, after };
54
+ }
55
+ return best;
56
+ }
57
+ /** Each shuffle repeats the complete split search to account for selecting its maximum. */
58
+ export function permutationTurningPoint(values, seed) {
59
+ if (values.length < 12)
60
+ return null;
61
+ const result = strongestSplit(values);
62
+ const random = mulberry32(seed);
63
+ const shuffled = [...values];
64
+ let atLeastAsStrong = 0;
65
+ for (let trial = 0; trial < 1000; trial++) {
66
+ for (let i = shuffled.length - 1; i > 0; i--) {
67
+ const j = Math.floor(random() * (i + 1));
68
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
69
+ }
70
+ if (strongestSplit(shuffled).score >= result.score - 1e-12)
71
+ atLeastAsStrong++;
72
+ }
73
+ return { ...result, pValue: (atLeastAsStrong + 1) / 1001 };
74
+ }
75
+ export function normalizedEntropy(counts) {
76
+ const observed = counts.filter((value) => value > 0);
77
+ if (observed.length < 2)
78
+ return 0;
79
+ const total = observed.reduce((a, b) => a + b, 0);
80
+ return Math.min(1, -observed.reduce((sum, count) => {
81
+ const p = count / total;
82
+ return sum + p * Math.log(p);
83
+ }, 0) / Math.log(observed.length));
84
+ }
85
+ export function gini(values) {
86
+ const sorted = [...values].sort((a, b) => a - b);
87
+ const sum = sorted.reduce((a, b) => a + b, 0);
88
+ if (!sum)
89
+ return 0;
90
+ return sorted.reduce((acc, value, i) => acc + (2 * (i + 1) - sorted.length - 1) * value, 0) / (sorted.length * sum);
91
+ }