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,115 @@
1
+ // Separates natural language from pasted code, logs, stack traces, diffs and harness-injected wrappers.
2
+ // Line-level heuristics, no model. Anything that is not confidently prose is dropped: a lost word is cheap,
3
+ // a counted line of someone's source code is not.
4
+ // Harness wrappers carry text the human did not type (reminders, command echoes, IDE selections).
5
+ const WRAPPER = /<(\/?)(instructions|task|context|selection|image|file|[a-z][a-z0-9]{0,31}(?:[-_][a-z0-9]{1,32}){1,8})(?:\s[^<>]{0,512})?\/?>/gi;
6
+ const MAX_LINE_CHARS = 8 * 1024;
7
+ const STACK = /^\s*(?:at\s+[\w$.<>[\]]+\s*\(|at\s+\S+:\d+:\d+|Traceback \(most recent call last\)|File ".+", line \d+|\w+(?:Error|Exception|Panic)\b:|panic:|Caused by:|\.\.\. \d+ more$|#\d+\s+0x[0-9a-f]+)/;
8
+ const DIFF = /^(?:\+\+\+ |--- |@@ .* @@|diff --git |index [0-9a-f]+\.\.|[+-](?![+-])\S)/;
9
+ const LOG = /^\s*(?:\[?\d{4}-\d\d-\d\d[ T]\d\d:\d\d|\[?\d\d:\d\d:\d\d(?:\.\d+)?\]?\s|\[?(?:TRACE|DEBUG|INFO|WARN|WARNING|ERROR|FATAL)\]?[\s:])/;
10
+ const SHELL = /^\s*(?:[$#>%]|PS [A-Z]:\\[^>]*>|❯|➜)\s+\S/;
11
+ const MARKUP = /^\s*(?:<\/?[A-Za-z][\w:-]*(?:\s[^>]*)?\/?>|[{}[\]],?\s*$|"[\w-]+"\s*:|[\w-]+:\s*[|>]?$)/;
12
+ const SYMBOLS = /[{}()[\];=<>&|$#@\\*`^~]/g;
13
+ const CODEY_END = /[;{}]\s*$|=>\s*$|^\s*(?:import|export|const|let|var|function|def|class|return|if|for|while|public|private|fn|func|package|#include|SELECT|INSERT|UPDATE|CREATE)\b/;
14
+ function kindOf(line) {
15
+ if (line.length > MAX_LINE_CHARS || (line.length >= 60 && /\S{60,}/.test(line)))
16
+ return 'symbol';
17
+ if (!line.trim())
18
+ return 'blank';
19
+ if (/^(?: {4,}|\t)/.test(line))
20
+ return 'indent';
21
+ if (STACK.test(line))
22
+ return 'stack';
23
+ if (DIFF.test(line))
24
+ return 'diff';
25
+ if (LOG.test(line))
26
+ return 'log';
27
+ if (SHELL.test(line))
28
+ return 'shell';
29
+ if (MARKUP.test(line))
30
+ return 'markup';
31
+ if (CODEY_END.test(line))
32
+ return 'symbol';
33
+ const symbols = line.match(SYMBOLS)?.length ?? 0;
34
+ if (symbols) {
35
+ const visible = line.replace(/\s+/g, '').length;
36
+ if (visible >= 8 && symbols / visible > 0.15)
37
+ return 'symbol';
38
+ }
39
+ return 'prose';
40
+ }
41
+ export function splitProse(text) {
42
+ const kinds = {};
43
+ let wrapperBlocks = 0;
44
+ let otherChars = 0;
45
+ let unwrapped = '';
46
+ let offset = 0;
47
+ let start = 0;
48
+ const tags = [];
49
+ for (const match of text.includes('<') ? text.matchAll(WRAPPER) : []) {
50
+ const [tag, closing, rawName] = match;
51
+ const name = rawName.toLowerCase();
52
+ const selfClosing = tag.endsWith('/>');
53
+ const index = match.index;
54
+ if (closing && tags.at(-1) !== name) {
55
+ return { prose: [], kinds, proseChars: 0, otherChars: text.length, wrapperBlocks };
56
+ }
57
+ if (!closing && !tags.length) {
58
+ unwrapped += text.slice(offset, index) + '\n';
59
+ wrapperBlocks++;
60
+ start = index;
61
+ }
62
+ if (selfClosing && !tags.length) {
63
+ offset = index + tag.length;
64
+ otherChars += offset - start;
65
+ }
66
+ else if (!closing && !selfClosing) {
67
+ tags.push(name);
68
+ }
69
+ else if (closing && tags.at(-1) === name) {
70
+ tags.pop();
71
+ if (!tags.length) {
72
+ offset = index + tag.length;
73
+ otherChars += offset - start;
74
+ }
75
+ }
76
+ }
77
+ if (tags.length)
78
+ otherChars += text.length - start;
79
+ else
80
+ unwrapped += text.slice(offset);
81
+ const prose = [];
82
+ let proseChars = 0;
83
+ let fence;
84
+ const lines = unwrapped.split(/\r?\n/);
85
+ // Diff markers only count when several lines agree; a single "- item" is a bullet.
86
+ let diffish = 0;
87
+ if (lines.length >= 3) {
88
+ for (const line of lines)
89
+ if (DIFF.test(line) && ++diffish === 3)
90
+ break;
91
+ }
92
+ for (const line of lines) {
93
+ const marker = /^\s*(`{3,}|~{3,})(.*)$/.exec(line);
94
+ if (marker && (!fence || marker[1].startsWith(fence) && marker[2].trim() === '')) {
95
+ fence = fence ? undefined : marker[1];
96
+ kinds.fence = (kinds.fence ?? 0) + 1;
97
+ otherChars += line.length;
98
+ continue;
99
+ }
100
+ let kind = fence ? 'fence' : kindOf(line);
101
+ if (kind === 'diff' && diffish < 3)
102
+ kind = 'prose';
103
+ kinds[kind] = (kinds[kind] ?? 0) + 1;
104
+ if (kind === 'prose') {
105
+ // Inline code spans are identifiers or snippets, never words of the prompt.
106
+ const cleaned = line.replace(/`[^`]*`/g, '\uE000');
107
+ prose.push(cleaned);
108
+ proseChars += cleaned.length;
109
+ }
110
+ else if (kind !== 'blank') {
111
+ otherChars += line.length;
112
+ }
113
+ }
114
+ return { prose, kinds, proseChars, otherChars, wrapperBlocks };
115
+ }
@@ -0,0 +1,301 @@
1
+ import { localTimestamp } from '../time.js';
2
+ import { ContentAnalyzer } from './analyzer.js';
3
+ const STACK = '\n' + 'at replay (src.ts:18:4)\n'.repeat(12);
4
+ const PROFILES = {
5
+ 'night-owl': {
6
+ seed: 0x0b1, sessions: 26, months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], startHours: { 21: 2, 22: 7, 23: 2 },
7
+ gapMinutes: 3, sessionShape: 1.3, goOnRun: 6,
8
+ once: [{ session: 0, text: 'the status is in https://fixture.example.invalid/demo' }],
9
+ user: [
10
+ { category: 'please', level: 58, templates: ['please rebuild the amber image', 'rerun the replay please', 'please look over these frames' + STACK] },
11
+ { category: 'thanks', level: 17, templates: ['thanks for the second pass', 'thank you, that fixed the amber build', 'cheers'] },
12
+ { category: 'sorry-user', level: 22, templates: ['sorry, I pasted the old log', 'my bad, that was the staging log', 'oops, ignore that trace'] },
13
+ { category: 'swear-mild', level: 39, templates: ['damn, the replay hangs', 'the amber build crashed, damn', 'heck, the parser broke'] },
14
+ { category: 'swear-strong', level: 31, templates: ['fuck, the amber build is red', 'wtf is this trace', 'this flaky replay is shit'] },
15
+ { category: 'why', level: 54, templates: ['why is the parser failing?', 'why did that run fail?', 'why does the replay hang at midnight?'] },
16
+ { category: 'not-working', level: 46, templates: ['the test suite is still failing', 'the parser is still failing', 'the replay still fails at step four', 'the replay is broken'] },
17
+ { category: 'again-still', level: 35, templates: ['same error on the replay', 'run that once again', 'the replay hangs again'] },
18
+ { category: 'instruction', level: 68, templates: ['check the amber build logs', 'make sure the amber build loads', 'make sure the amber build is reproducible', 'CHECK THE LAST BUILD', 'read the replay log first'] },
19
+ { category: 'go-on', level: 148, templates: ['continue', 'keep going'], weights: [0.92, 0.08] },
20
+ { category: 'undo', level: 25, templates: ['revert the interrupted build', 'roll back the replay patch', 'undo the last edit'] },
21
+ { category: 'exasperation', level: 11, templates: ['ugh, the replay hangs', 'come on, one more run'] },
22
+ { category: 'praise', level: 8, templates: ['nice work on the replay', 'lgtm'] },
23
+ { category: null, level: 42, templates: ['the replay hangs at midnight', 'rerun the amber build with logs', 'the amber build loads in a minute'] },
24
+ ],
25
+ agent: [
26
+ { category: 'agent-agree', level: 290, templates: ["You're absolutely right.", 'Great question.', 'Good catch.'], weights: [0.74, 0.17, 0.09] },
27
+ { category: 'agent-sorry', level: 63, templates: ['I apologize for the noise.', 'Sorry about that.', 'My mistake.'] },
28
+ { category: 'agent-confident', level: 121, templates: ['The second pass is production ready!', 'All tests pass.', 'Perfect!'] },
29
+ { category: 'agent-praise', level: 44, templates: ['Great work on the replay!', 'Happy to help.'] },
30
+ { category: 'agent-narration', level: 205, templates: ['Let me rerun the build.', 'I see the issue.'] },
31
+ ],
32
+ agentFill: ['The patch now loads.', 'The replay is green.', 'Here is the diff summary.', 'The frames point at the parser.'],
33
+ },
34
+ polyglot: {
35
+ seed: 0x9a1, sessions: 14, months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], startHours: { 13: 2, 14: 4, 15: 2, 16: 1 },
36
+ gapMinutes: 4, sessionShape: 1.6,
37
+ user: [
38
+ { category: 'please', level: 40, templates: ['please trace the output 🧪', 'проверь этот пример пожалуйста 🔍', 'please run the rainbow parser on the sample 🚀'] },
39
+ { category: 'thanks', level: 15, templates: ['thank you, the rainbow parser works ✨', 'merci pour les correctifs ✨', 'thanks for the fixture 🙌', 'danke für die hilfe 🙌', '谢谢 🙌'] },
40
+ { category: 'why', level: 12, templates: ['why does the rainbow parser drop accents?', '看看这个测试为什么失败 🔍'] },
41
+ { category: 'instruction', level: 30, templates: ['check the rainbow parser output 🚀', 'make sure the rainbow parser keeps spaces'] },
42
+ { category: 'go-on', level: 27, templates: ['continue'] },
43
+ { category: null, level: 46, templates: ['rainbow parser handles mixed scripts', 'rainbow parser should accept spaces', 'the rainbow parser needs new tests', 'этот парсер теряет пробелы', '这个解析器很快'] },
44
+ ],
45
+ agent: [
46
+ { category: 'agent-agree', level: 168, templates: ['Great question.', "You're right."], weights: [0.8, 0.2] },
47
+ { category: 'agent-confident', level: 118, templates: ['Excellent work!', 'All tests pass.'] },
48
+ { category: 'agent-praise', level: 37, templates: ['Great work!', 'Glad it helps.'] },
49
+ { category: 'agent-narration', level: 52, templates: ['Let me add a fixture.'] },
50
+ ],
51
+ agentFill: ['The batch passed ✅ ✅ 🚀', 'The parser keeps the accents ✅', 'Here is the output.'],
52
+ },
53
+ specialist: {
54
+ seed: 0x5e1, sessions: 15, months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], startHours: { 8: 2, 9: 6, 10: 2 },
55
+ gapMinutes: 5, sessionShape: 1.4,
56
+ user: [
57
+ { category: 'please', level: 1, templates: ['please review the boundary once more'] },
58
+ { category: 'instruction', level: 38, templates: ['make sure the dependency boundary holds', 'make sure the dependency boundary is explicit'] },
59
+ { category: 'why', level: 9, templates: ['why did the dependency boundary move?'] },
60
+ { category: 'not-working', level: 12, templates: ['the dependency boundary is still failing', 'the dependency boundary is broken'] },
61
+ { category: 'again-still', level: 4, templates: ['same error on the boundary'] },
62
+ { category: 'undo', level: 15, templates: ['undo the previous rewrite', 'revert the boundary rework'] },
63
+ { category: 'go-on', level: 31, templates: ['continue'] },
64
+ { category: null, level: 40, templates: ['dependency boundary needs independent checks', 'dependency boundary stays deterministic', 'grep the replay'] },
65
+ ],
66
+ agent: [
67
+ { category: 'agent-agree', level: 152, templates: ["You're absolutely right.", 'Good point.'], weights: [0.86, 0.14] },
68
+ { category: 'agent-confident', level: 139, templates: ['All tests pass.', 'The harness is robust.'] },
69
+ { category: 'agent-narration', level: 48, templates: ['Let me trace the imports.'] },
70
+ ],
71
+ agentFill: ['The harness stays deterministic.', 'The boundary holds.', 'Here is the import graph.'],
72
+ },
73
+ partial: {
74
+ seed: 0x7a1, sessions: 7, months: [2, 3, 4, 5, 6, 7, 8], startHours: { 13: 1, 14: 3, 15: 1 },
75
+ gapMinutes: 4, sessionShape: 1.8,
76
+ user: [
77
+ { category: 'please', level: 13, templates: ['please keep the quiet branch small', 'please review the quiet branch'] },
78
+ { category: 'thanks', level: 6, templates: ['thank you for the patch'] },
79
+ { category: 'why', level: 5, templates: ['why does the preview repeat?'] },
80
+ { category: 'not-working', level: 4, templates: ['the quiet branch is still failing', 'the quiet branch is broken'] },
81
+ { category: 'again-still', level: 2, templates: ['same error on the quiet branch'] },
82
+ { category: 'go-on', level: 9, templates: ['continue'] },
83
+ { category: 'undo', level: 3, templates: ['undo the previous edit'] },
84
+ { category: null, level: 16, templates: ['quiet branch needs a clean build', 'the quiet branch keeps failing', 'rebuild the quiet branch'] },
85
+ ],
86
+ agent: [
87
+ { category: 'agent-agree', level: 61, templates: ['Good catch.', 'Great question.'], weights: [0.85, 0.15] },
88
+ { category: 'agent-narration', level: 30, templates: ['I see the issue.'] },
89
+ ],
90
+ agentFill: ['The patch now loads.', 'The branch builds.'],
91
+ },
92
+ starter: {
93
+ seed: 0x5a1, sessions: 3, months: [11], startHours: { 14: 1 },
94
+ gapMinutes: 6, sessionShape: 50,
95
+ user: [
96
+ { category: 'please', level: 2, templates: ['please open the sample'] },
97
+ { category: 'thanks', level: 1, templates: ['thanks'] },
98
+ { category: null, level: 11, templates: ['tiny preview', 'open the tiny preview', 'tiny preview works'] },
99
+ ],
100
+ agent: [],
101
+ agentFill: ['The preview is ready.'],
102
+ },
103
+ };
104
+ // mulberry32: small, fast, deterministic.
105
+ function rng(seed) {
106
+ let a = seed >>> 0;
107
+ return () => {
108
+ a = (a + 0x6d2b79f5) >>> 0;
109
+ let t = a;
110
+ t = Math.imul(t ^ (t >>> 15), t | 1);
111
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
112
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
113
+ };
114
+ }
115
+ const normal = (random) => Math.sqrt(-2 * Math.log(1 - random())) * Math.cos(2 * Math.PI * random());
116
+ const pick = (random, items, weights) => {
117
+ let r = random() * weights.reduce((a, b) => a + b, 0);
118
+ for (let i = 0; i < items.length; i++)
119
+ if ((r -= weights[i]) < 0)
120
+ return items[i];
121
+ return items.at(-1);
122
+ };
123
+ const zipf = (n) => Array.from({ length: n }, (_, i) => 1 / (i + 1) ** 1.3);
124
+ function shuffle(random, items) {
125
+ for (let i = items.length - 1; i > 0; i--) {
126
+ const j = Math.floor(random() * (i + 1));
127
+ [items[i], items[j]] = [items[j], items[i]];
128
+ }
129
+ return items;
130
+ }
131
+ const GO_ON_ONLY = /^(continue|keep going)$/;
132
+ function draft(profile) {
133
+ const p = PROFILES[profile];
134
+ const random = rng(p.seed);
135
+ // Each group's size: lognormal around the profile's level (levels of 1 or 2 stay exact: "barely says please").
136
+ const size = (group) => group.level <= 2 ? group.level
137
+ : Math.max(1, Math.round(group.level * Math.exp(0.18 * normal(random))));
138
+ const draw = (group, count) => {
139
+ const weights = group.weights ?? zipf(group.templates.length).map(w => w * Math.exp(0.25 * normal(random)));
140
+ return Array.from({ length: count }, () => pick(random, group.templates, weights));
141
+ };
142
+ const goOn = [];
143
+ const thanks = [];
144
+ const rest = [];
145
+ for (const group of p.user) {
146
+ const texts = draw(group, size(group));
147
+ if (group.category === 'go-on')
148
+ goOn.push(...texts);
149
+ else if (group.category === 'thanks')
150
+ thanks.push(...texts);
151
+ else
152
+ rest.push(...texts);
153
+ }
154
+ // Heavy-tailed session weights (Pareto). Starter's large shape keeps it even.
155
+ const weights = Array.from({ length: p.sessions }, () => (1 - random()) ** (-1 / p.sessionShape));
156
+ const order = weights.map((w, i) => [w, i]).sort((a, b) => b[0] - a[0]).map(([, i]) => i);
157
+ const bySession = () => pick(random, order, order.map(s => weights[s]));
158
+ const prompts = Array.from({ length: p.sessions }, () => []);
159
+ // Every session gets at least one ordinary prompt; the rest follow the weights.
160
+ shuffle(random, rest);
161
+ rest.forEach((text, i) => prompts[i < p.sessions ? i : bySession()].push(text));
162
+ for (const session of prompts)
163
+ shuffle(random, session);
164
+ for (const { session, text } of p.once ?? [])
165
+ prompts[session].splice(Math.floor(random() * (prompts[session].length + 1)), 0, text);
166
+ // Thank-yous close sessions: longer sessions are likelier to end on one.
167
+ const isThanks = (text) => text !== undefined && thanks.includes(text);
168
+ for (const text of thanks) {
169
+ const list = prompts[pick(random, order, order.map(s => weights[s] * (prompts[s].length + 1)))];
170
+ list.splice(isThanks(list.at(-1)) ? Math.floor(random() * list.length) : list.length, 0, text);
171
+ }
172
+ // Go-ahead prompts never sit next to each other, except one planted run in the heaviest session.
173
+ // The planted run is one-word go-aheads only ("keep going" is not one word, so it would end the streak).
174
+ const planted = [];
175
+ for (let i = goOn.length - 1; i >= 0 && planted.length < (p.goOnRun ?? 0); i--) {
176
+ if (goOn[i] === 'continue')
177
+ planted.push(...goOn.splice(i, 1));
178
+ }
179
+ const safeGaps = (list) => list.map((_, i) => i)
180
+ .filter(i => i > 0 && i < list.length && !GO_ON_ONLY.test(list[i - 1]) && !GO_ON_ONLY.test(list[i]));
181
+ for (const text of goOn) {
182
+ const list = prompts[bySession()];
183
+ const gaps = safeGaps(list);
184
+ list.splice(gaps.length ? gaps[Math.floor(random() * gaps.length)] : 0, 0, text);
185
+ }
186
+ if (planted.length) {
187
+ const list = prompts[order[0]];
188
+ const gaps = safeGaps(list);
189
+ list.splice(gaps[Math.floor(gaps.length / 2)] ?? 0, 0, ...planted);
190
+ }
191
+ // Agent replies: one per prompt, 1 to 3 sentences, from the drawn category sentences plus neutral fill.
192
+ const total = prompts.reduce((n, list) => n + list.length, 0);
193
+ const sentences = p.agent.flatMap(group => draw(group, size(group)));
194
+ const lengths = Array.from({ length: total }, () => 1 + Math.floor(random() * 3));
195
+ while (lengths.reduce((a, b) => a + b, 0) < sentences.length)
196
+ lengths[Math.floor(random() * total)]++;
197
+ shuffle(random, sentences);
198
+ const agree = new Set(p.agent.find(group => group.category === 'agent-agree')?.templates ?? []);
199
+ let next = 0;
200
+ const flat = lengths.map(length => {
201
+ const reply = Array.from({ length }, () => next < sentences.length ? sentences[next++] : pick(random, p.agentFill, p.agentFill.map(() => 1)));
202
+ // Agreement reads as an opener: when a reply has one, it comes first.
203
+ return reply.sort((a, b) => Number(agree.has(b)) - Number(agree.has(a)));
204
+ });
205
+ return { prompts, replies: prompts.map(list => list.map(() => flat.shift())) };
206
+ }
207
+ function* records(profile, timezone, planned) {
208
+ const p = PROFILES[profile];
209
+ const random = rng(p.seed ^ 0x7153);
210
+ const hours = Object.keys(p.startHours).map(Number);
211
+ for (let i = 0; i < p.sessions; i++) {
212
+ const month = p.months[i % p.months.length];
213
+ const day = profile === 'starter' ? 18 + i * 3 : 1 + Math.floor(random() * 27);
214
+ const date = `2026-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
215
+ const hour = pick(random, hours, hours.map(h => p.startHours[h]));
216
+ let t = localTimestamp(date, hour * 60 + Math.floor(random() * 20), timezone);
217
+ const session = `synthetic-session-${i}`;
218
+ for (const [j, text] of planned.prompts[i].entries()) {
219
+ yield { ts: t, session, role: 'user', text };
220
+ yield { ts: t + 30_000, session, role: 'agent', text: planned.replies[i][j].join(' ') };
221
+ t += Math.max(1, Math.round(p.gapMinutes * -Math.log(1 - random()))) * 60_000;
222
+ }
223
+ }
224
+ }
225
+ function lexiconTotals(recs) {
226
+ const analyzer = new ContentAnalyzer({ timezone: 'UTC', messageBudgetMs: Infinity, totalBudgetMs: Infinity });
227
+ for (const record of recs)
228
+ analyzer.add(record);
229
+ return new Map(analyzer.finish().lexicon.map(row => [row.id, row.total]));
230
+ }
231
+ const finalPlans = new Map();
232
+ // The drawn corpus, adjusted until no two lexicon categories share a total. The totals are measured with the real
233
+ // matcher (some phrases count in two categories by design, like "make sure" and "sure"). A tie is broken by adding
234
+ // one occurrence of a template that hits only that category, so the guarantee holds by construction.
235
+ export function demoPlan(profile) {
236
+ const cached = finalPlans.get(profile);
237
+ if (cached)
238
+ return cached;
239
+ const p = PROFILES[profile];
240
+ const planned = draft(profile);
241
+ const pure = new Map();
242
+ const isPure = (category, role, text) => {
243
+ const key = `${category}\0${role}\0${text}`;
244
+ if (!pure.has(key)) {
245
+ const totals = lexiconTotals([{ ts: Date.UTC(2026, 0, 5, 12), session: 'pure', role, text }]);
246
+ pure.set(key, totals.size === 1 && totals.get(category) === 1);
247
+ }
248
+ return pure.get(key);
249
+ };
250
+ const heaviest = planned.prompts.reduce((best, list, i) => list.length > planned.prompts[best].length ? i : best, 0);
251
+ for (let round = 0; round < 200; round++) {
252
+ const totals = lexiconTotals(records(profile, 'UTC', planned));
253
+ const owner = new Map();
254
+ let clash;
255
+ for (const [id, n] of totals) {
256
+ if (owner.has(n)) {
257
+ clash = [id, owner.get(n)];
258
+ break;
259
+ }
260
+ owner.set(n, id);
261
+ }
262
+ if (!clash) {
263
+ finalPlans.set(profile, planned);
264
+ return planned;
265
+ }
266
+ let fixed = false;
267
+ for (const category of clash) {
268
+ const user = p.user.find(group => group.category === category)?.templates.find(text => isPure(category, 'user', text));
269
+ if (user) {
270
+ const list = planned.prompts[heaviest];
271
+ const at = list.findIndex((text, i) => i > 0 && !GO_ON_ONLY.test(text) && !GO_ON_ONLY.test(list[i - 1]));
272
+ list.splice(at > 0 ? at : list.length, 0, user);
273
+ planned.replies[heaviest].splice(at > 0 ? at : list.length, 0, [p.agentFill[0]]);
274
+ fixed = true;
275
+ break;
276
+ }
277
+ const agent = p.agent.find(group => group.category === category)?.templates.find(text => isPure(category, 'agent', text));
278
+ if (agent) {
279
+ const reply = planned.replies.flat().find(sentences => !sentences.includes(agent));
280
+ if (reply) {
281
+ reply.push(agent);
282
+ fixed = true;
283
+ break;
284
+ }
285
+ }
286
+ }
287
+ if (!fixed)
288
+ throw new Error('DEMO_TOTALS_NOT_DISTINCT');
289
+ }
290
+ throw new Error('DEMO_TOTALS_NOT_DISTINCT');
291
+ }
292
+ export function* demoContentCorpus(profile, timezone) {
293
+ yield* records(profile, timezone, demoPlan(profile));
294
+ }
295
+ export function buildDemoContent(profile, timezone) {
296
+ // No time budgets: the fixtures must not depend on how loaded the machine is.
297
+ const analyzer = new ContentAnalyzer({ timezone, messageBudgetMs: Infinity, totalBudgetMs: Infinity });
298
+ for (const record of demoContentCorpus(profile, timezone))
299
+ analyzer.add(record);
300
+ return analyzer.finish();
301
+ }
@@ -0,0 +1,54 @@
1
+ // Bounded heavy-hitter counter: Space-Saving (Metwally, Agrawal, El Abbadi, ICDT 2005) with batched eviction.
2
+ // The table may grow to 2·capacity; then it is pruned to the top `capacity` entries in one sort, and the largest
3
+ // evicted count becomes the floor that new entries inherit as both count and error.
4
+ // Guarantees for every reported key: trueCount <= count and trueCount >= count - error.
5
+ // Privacy gates always use the lower bound (count - error), so approximation can only hide a phrase, never surface one.
6
+ //
7
+ // Distinct counts are lower bounds capped at 32. Adapters may interleave sessions or replay days.
8
+ const DISTINCT_CAP = 32;
9
+ export class SpaceSaving {
10
+ table = new Map();
11
+ floor = 0;
12
+ evictions = 0;
13
+ capacity;
14
+ constructor(capacity) { this.capacity = capacity; }
15
+ add(key, session, day, capitalized = false) {
16
+ let entry = this.table.get(key);
17
+ if (!entry) {
18
+ entry = { count: this.floor, error: this.floor, sessions: [], days: [], capitalized: 0 };
19
+ this.table.set(key, entry);
20
+ }
21
+ entry.count++;
22
+ if (capitalized)
23
+ entry.capitalized++;
24
+ if (entry.sessions.length < DISTINCT_CAP && !entry.sessions.includes(session))
25
+ entry.sessions.push(session);
26
+ if (entry.days.length < DISTINCT_CAP && !entry.days.includes(day))
27
+ entry.days.push(day);
28
+ if (this.table.size >= this.capacity * 2)
29
+ this.prune();
30
+ }
31
+ prune() {
32
+ const sorted = [...this.table.entries()].sort((a, b) => b[1].count - a[1].count);
33
+ for (let i = this.capacity; i < sorted.length; i++) {
34
+ this.floor = Math.max(this.floor, sorted[i][1].count);
35
+ this.table.delete(sorted[i][0]);
36
+ this.evictions++;
37
+ }
38
+ }
39
+ /** Lower bound of the true count when the key is absent: zero; present: count - error. */
40
+ lower(key) {
41
+ const entry = this.table.get(key);
42
+ return entry ? entry.count - entry.error : 0;
43
+ }
44
+ /** Upper bound of the true count: present → count; absent → floor (it may have been evicted). */
45
+ upper(key) {
46
+ return this.table.get(key)?.count ?? this.floor;
47
+ }
48
+ top(limit, filter = () => true) {
49
+ return [...this.table.entries()]
50
+ .filter(([key, entry]) => filter(key, entry))
51
+ .sort((a, b) => (b[1].count - b[1].error) - (a[1].count - a[1].error))
52
+ .slice(0, limit);
53
+ }
54
+ }