chompyy 0.4.7 → 0.6.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 (161) hide show
  1. package/README.md +40 -6
  2. package/dist/advice.js +2 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/appstate.js +72 -5
  6. package/dist/away.js +44 -5
  7. package/dist/blueprint.js +3 -7
  8. package/dist/board.js +4 -0
  9. package/dist/cli.js +328 -15
  10. package/dist/codexquota.js +106 -0
  11. package/dist/codexusage.js +10 -0
  12. package/dist/config.js +2 -0
  13. package/dist/context.js +30 -0
  14. package/dist/costs.js +1 -0
  15. package/dist/daytime.js +68 -0
  16. package/dist/demon.js +20 -0
  17. package/dist/didwork.js +46 -0
  18. package/dist/label.js +33 -0
  19. package/dist/learning.js +35 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +60 -0
  22. package/dist/nudge.js +47 -18
  23. package/dist/pacing.js +16 -1
  24. package/dist/questions.js +71 -0
  25. package/dist/recap.js +74 -0
  26. package/dist/receipt.js +48 -0
  27. package/dist/recipe.js +79 -0
  28. package/dist/send.js +46 -20
  29. package/dist/stamps.js +14 -0
  30. package/dist/taste.js +67 -7
  31. package/dist/triggers.js +5 -0
  32. package/dist/unkeep.js +220 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6953 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/package.json +11 -3
@@ -0,0 +1,126 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ /**
3
+ * Deterministic local work-unit resolver (CB-2, slice 1 of the CodeBurn
4
+ * main/Teams boundary spec). Groups parsed sessions carrying the #1140
5
+ * provider-recorded `lineage` field into work units: one observed root session
6
+ * plus its directly evidenced delegated children.
7
+ *
8
+ * Rules (spec sections 1 and 3, MAIN-01/MAIN-02):
9
+ * - Only provider-recorded lineage is honored. A session without lineage is its
10
+ * own standalone unit (role `unknown`, never guessed).
11
+ * - One-sided evidence folds: a child that names an in-range parent folds under
12
+ * it even when the parent recorded nothing itself.
13
+ * - Fail closed: a parent id that matches no session in range leaves the child
14
+ * ungrouped for that view; a cycle or self-reference is broken and every
15
+ * participant is marked `unknown`; a duplicate (provider, id) pair is
16
+ * ambiguous and never folds either way.
17
+ * - No inference from time adjacency, shared projects, or directory layout.
18
+ * - Deterministic: the same input set yields byte-identical output regardless
19
+ * of input order.
20
+ *
21
+ * No wire/sync changes and no daily-cache changes live here.
22
+ */
23
+ import { deriveTraceId } from './sync/otlp.js';
24
+ // NUL delimiter: it cannot appear in a provider name or session id, so keys
25
+ // never collide (mirrors the by-PR linkage keying in sessions-report.ts).
26
+ const KEY_SEP = String.fromCharCode(0);
27
+ export function workUnitSessionKey(provider, sessionId) {
28
+ return `${provider}${KEY_SEP}${sessionId}`;
29
+ }
30
+ /// A session is a child edge only when the provider durably recorded both the
31
+ /// child role and the parent id. Any other shape (root, missing parent id, a
32
+ /// future non-`provider-recorded` evidence class) contributes no edge.
33
+ function isRecordedChild(session) {
34
+ return session.lineage?.evidence === 'provider-recorded'
35
+ && session.lineage.role === 'child'
36
+ && typeof session.lineage.parentSessionId === 'string'
37
+ && session.lineage.parentSessionId.length > 0;
38
+ }
39
+ export function resolveWorkUnits(sessions) {
40
+ // Canonical processing order: provider+id, then lineage content as a
41
+ // tie-break so duplicate-id records order identically under any input order.
42
+ const sorted = [...sessions].sort((a, b) => workUnitSessionKey(a.provider, a.sessionId).localeCompare(workUnitSessionKey(b.provider, b.sessionId))
43
+ || JSON.stringify(a.lineage ?? null).localeCompare(JSON.stringify(b.lineage ?? null)));
44
+ const byKey = new Map();
45
+ const ambiguous = new Set();
46
+ for (const session of sorted) {
47
+ const key = workUnitSessionKey(session.provider, session.sessionId);
48
+ if (byKey.has(key))
49
+ ambiguous.add(key);
50
+ else
51
+ byKey.set(key, session);
52
+ }
53
+ // Walk a child's parent chain to the topmost in-range ancestor. Returns null
54
+ // (fail closed) on a missing or ambiguous parent link, a cycle, or a
55
+ // self-reference; the child then stays ungrouped for this view.
56
+ const resolveRoot = (start) => {
57
+ const visited = new Set();
58
+ let current = start;
59
+ while (isRecordedChild(current)) {
60
+ const currentKey = workUnitSessionKey(current.provider, current.sessionId);
61
+ if (visited.has(currentKey))
62
+ return null;
63
+ visited.add(currentKey);
64
+ const parentKey = workUnitSessionKey(current.provider, current.lineage.parentSessionId);
65
+ if (ambiguous.has(parentKey))
66
+ return null;
67
+ const parent = byKey.get(parentKey);
68
+ if (!parent)
69
+ return null;
70
+ current = parent;
71
+ }
72
+ return workUnitSessionKey(current.provider, current.sessionId);
73
+ };
74
+ // Children fold under their resolved root, keyed by the root's session key.
75
+ // A record with an ambiguous (provider, id) key never folds and never roots
76
+ // a fold: two conflicting records share the id, so neither can be trusted.
77
+ const childrenByRootKey = new Map();
78
+ const foldedRecords = new Set();
79
+ for (const session of sorted) {
80
+ const key = workUnitSessionKey(session.provider, session.sessionId);
81
+ if (ambiguous.has(key) || !isRecordedChild(session))
82
+ continue;
83
+ const rootKey = resolveRoot(session);
84
+ if (!rootKey || rootKey === key)
85
+ continue;
86
+ const list = childrenByRootKey.get(rootKey);
87
+ if (list)
88
+ list.push(session);
89
+ else
90
+ childrenByRootKey.set(rootKey, [session]);
91
+ foldedRecords.add(session);
92
+ }
93
+ const units = [];
94
+ const bySession = new Map();
95
+ for (const session of sorted) {
96
+ if (foldedRecords.has(session))
97
+ continue; // emitted with its root's unit
98
+ const key = workUnitSessionKey(session.provider, session.sessionId);
99
+ const children = (childrenByRootKey.get(key) ?? [])
100
+ .map(child => child.sessionId)
101
+ .sort();
102
+ const role = children.length > 0 ? 'root'
103
+ : session.lineage?.evidence === 'provider-recorded' && session.lineage.role === 'root' ? 'root'
104
+ : 'unknown';
105
+ const roles = { [session.sessionId]: role };
106
+ for (const childId of children)
107
+ roles[childId] = 'child';
108
+ const unit = {
109
+ workUnitId: deriveTraceId(session.sessionId),
110
+ rootSessionId: session.sessionId,
111
+ childSessionIds: children,
112
+ roles,
113
+ };
114
+ units.push(unit);
115
+ // Ambiguous duplicate records share one key; registering it would point
116
+ // both records at one arbitrary unit, so presentation leaves them alone.
117
+ if (!ambiguous.has(key)) {
118
+ bySession.set(key, unit.workUnitId);
119
+ for (const child of childrenByRootKey.get(key) ?? []) {
120
+ bySession.set(workUnitSessionKey(child.provider, child.sessionId), unit.workUnitId);
121
+ }
122
+ }
123
+ }
124
+ units.sort((a, b) => a.workUnitId.localeCompare(b.workUnitId));
125
+ return { units, bySession };
126
+ }
@@ -0,0 +1,228 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { homedir } from 'os';
3
+ import { EDIT_TOOLS } from './classifier.js';
4
+ import { userStartedProjects } from './session-population.js';
5
+ import { CATEGORY_LABELS } from './types.js';
6
+ // User-side mirror of compare-stats.ts scanSelfCorrections (which scans the
7
+ // assistant's own apologies). These match a *user* follow-up telling the
8
+ // assistant it got something wrong. Deliberately conservative: bare "wrong" or
9
+ // "undo" are excluded because they show up in ordinary task requests ("fix the
10
+ // wrong output", "undo the migration"), and "revert"/"undo" only match
11
+ // demonstratives ("that", "this", "the last") so an opening request like
12
+ // "revert the migration we shipped" never trips them. Every pattern requires a
13
+ // correction context so praise like "you were right" never counts.
14
+ export const USER_CORRECTION_PATTERNS = [
15
+ /\bthat'?s (?:not|n'?t) (?:what|right|correct|it)\b/i,
16
+ /\bthat'?s (?:wrong|incorrect)\b/i,
17
+ /\bthat is (?:wrong|incorrect|not right)\b/i,
18
+ /\bnot what I (?:meant|wanted|asked|said)\b/i,
19
+ /\bno,? I (?:meant|wanted|said|asked for)\b/i,
20
+ /\byou (?:missed|forgot|misunderstood|broke)\b/i,
21
+ /\brevert (?:that|it|this|your|the last|the change)\b/i,
22
+ /\bundo (?:that|it|this|your|the last|the change)\b/i,
23
+ // "answer" is deliberately absent from the noun list: injected skill/system
24
+ // prose lands in the user-message slot and reads as ordinary writing where
25
+ // "the wrong answer" is an idiom ("a well-composed page is never the wrong
26
+ // answer" counted 4 phantom corrections on real data). The other nouns are
27
+ // concrete work artifacts that prose rarely uses with "wrong".
28
+ /\bwrong (?:file|approach|place|method|function|way|direction)\b/i,
29
+ /\bstill (?:wrong|broken|failing|not working)\b/i,
30
+ ];
31
+ function matchesCorrection(text) {
32
+ return USER_CORRECTION_PATTERNS.some(p => p.test(text));
33
+ }
34
+ export function scanUserCorrections(projects) {
35
+ let corrections = 0;
36
+ let userTurns = 0;
37
+ for (const project of userStartedProjects(projects)) {
38
+ for (const session of project.sessions) {
39
+ // A correction is a FOLLOW-UP by definition: the session's opening
40
+ // prompt cannot be correcting this assistant, however correction-shaped
41
+ // its task text reads ("revert the last release", "you broke it" pasted
42
+ // from a bug report). Skipping it trades a few missed corrections in
43
+ // resumed transcripts for never counting openers — the conservative side.
44
+ let sawPrompt = false;
45
+ for (const turn of session.turns) {
46
+ const msg = turn.userMessage;
47
+ if (!msg || !msg.trim())
48
+ continue;
49
+ userTurns++;
50
+ if (!sawPrompt) {
51
+ sawPrompt = true;
52
+ continue;
53
+ }
54
+ if (matchesCorrection(msg))
55
+ corrections++;
56
+ }
57
+ }
58
+ }
59
+ return { corrections, userTurns, correctionRate: userTurns > 0 ? corrections / userTurns : null };
60
+ }
61
+ function callHasEditTools(tools) {
62
+ return tools.some(t => EDIT_TOOLS.has(t));
63
+ }
64
+ /// Per-session ms from the session's first turn to the first assistant call
65
+ /// that used an edit-family tool. Returns null for sessions that never edited,
66
+ /// so those are excluded from the median rather than counted as zero.
67
+ export function sessionTimeToFirstEditMs(session) {
68
+ const startMs = Date.parse(session.turns[0]?.timestamp ?? '');
69
+ if (Number.isNaN(startMs))
70
+ return null;
71
+ for (const turn of session.turns) {
72
+ for (const call of turn.assistantCalls) {
73
+ if (!callHasEditTools(call.tools))
74
+ continue;
75
+ const editMs = Date.parse(call.timestamp);
76
+ // The FIRST edit is the measurement target; if its timestamp is
77
+ // unparseable the session's time-to-first-edit is unknown. Skipping to
78
+ // the next parseable edit would silently measure a later one.
79
+ if (Number.isNaN(editMs))
80
+ return null;
81
+ // Clamp: out-of-order timestamps across resumed transcripts would
82
+ // otherwise pull the median negative.
83
+ return Math.max(0, editMs - startMs);
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+ export function medianTimeToFirstEditMs(projects) {
89
+ const samples = [];
90
+ for (const project of userStartedProjects(projects)) {
91
+ for (const session of project.sessions) {
92
+ const ms = sessionTimeToFirstEditMs(session);
93
+ if (ms !== null)
94
+ samples.push(ms);
95
+ }
96
+ }
97
+ if (samples.length === 0)
98
+ return null;
99
+ samples.sort((a, b) => a - b);
100
+ const mid = Math.floor(samples.length / 2);
101
+ return samples.length % 2 === 0 ? (samples[mid - 1] + samples[mid]) / 2 : samples[mid];
102
+ }
103
+ /// Forward-slash normalization: tool calls carry model-emitted paths verbatim,
104
+ /// so on Windows they arrive backslashed. Without this the relativize and
105
+ /// basename passes (which split on '/') are no-ops there and the full absolute
106
+ /// path, username included, would ship in a payload that can leave the machine.
107
+ function normalizeSlashes(p) {
108
+ return p.replace(/\\/g, '/');
109
+ }
110
+ function relativizePath(absPath, projectPath) {
111
+ const project = normalizeSlashes(projectPath);
112
+ if (project && (absPath === project || absPath.startsWith(project + '/'))) {
113
+ return absPath.slice(project.length + 1) || absPath;
114
+ }
115
+ const home = normalizeSlashes(homedir());
116
+ if (absPath === home || absPath.startsWith(home + '/'))
117
+ return '~' + absPath.slice(home.length);
118
+ return absPath;
119
+ }
120
+ /// Ranks the files touched most by edit-family tool calls. File paths come from
121
+ /// each call's toolSequence, which the parser/cache retain per edit tool_use
122
+ /// (see parser.ts and session-cache CachedCall.toolSequence). Rank by distinct
123
+ /// sessions first (a file reworked across many sessions is the real churn
124
+ /// signal), then total edit calls.
125
+ export function aggregateFileChurn(projects, limit = 15) {
126
+ const byPath = new Map();
127
+ for (const project of userStartedProjects(projects)) {
128
+ for (const session of project.sessions) {
129
+ for (const turn of session.turns) {
130
+ for (const call of turn.assistantCalls) {
131
+ if (!call.toolSequence)
132
+ continue;
133
+ for (const step of call.toolSequence) {
134
+ for (const tc of step) {
135
+ if (!EDIT_TOOLS.has(tc.tool) || !tc.file)
136
+ continue;
137
+ // Key on the normalized path so the same file emitted with
138
+ // backslashes and forward slashes accumulates as one entry.
139
+ const file = normalizeSlashes(tc.file);
140
+ let acc = byPath.get(file);
141
+ if (!acc) {
142
+ acc = { path: relativizePath(file, project.projectPath), sessions: new Set(), edits: 0 };
143
+ byPath.set(file, acc);
144
+ }
145
+ acc.sessions.add(session.sessionId);
146
+ acc.edits++;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+ }
153
+ return [...byPath.values()]
154
+ .map(a => ({ path: a.path, sessions: a.sessions.size, edits: a.edits }))
155
+ .sort((a, b) => b.sessions - a.sessions || b.edits - a.edits || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
156
+ .slice(0, limit);
157
+ }
158
+ /// Share (0-1) of cost-bearing calls that resolved a price. `unpricedCalls` are
159
+ /// the calls of models with usage but no pricing table entry (findUnpricedModels).
160
+ /// Returns 1 when there is nothing to price (no coverage gap to report).
161
+ export function computePricingCoverage(totalCostBearingCalls, unpricedCalls) {
162
+ if (totalCostBearingCalls <= 0)
163
+ return 1;
164
+ const priced = Math.max(0, totalCostBearingCalls - unpricedCalls);
165
+ return priced / totalCostBearingCalls;
166
+ }
167
+ /// Minimum edit turns before a category's one-shot rate is trusted (shared by
168
+ /// worstOneShotCategory and the coaching gate so they can never disagree).
169
+ export const MIN_ONE_SHOT_EDIT_TURNS = 5;
170
+ /// The task category with the weakest one-shot rate (over enough edit turns to
171
+ /// trust), used by the coaching notes. Rate is a percentage (0-100), matching
172
+ /// model-efficiency and the report's category one-shot figures.
173
+ export function worstOneShotCategory(projects, minEditTurns = MIN_ONE_SHOT_EDIT_TURNS) {
174
+ const acc = new Map();
175
+ for (const project of userStartedProjects(projects)) {
176
+ for (const session of project.sessions) {
177
+ for (const [cat, d] of Object.entries(session.categoryBreakdown)) {
178
+ const e = acc.get(cat) ?? { editTurns: 0, oneShotTurns: 0 };
179
+ e.editTurns += d.editTurns;
180
+ e.oneShotTurns += d.oneShotTurns;
181
+ acc.set(cat, e);
182
+ }
183
+ }
184
+ }
185
+ let worst = null;
186
+ for (const [cat, d] of acc) {
187
+ if (d.editTurns < minEditTurns)
188
+ continue;
189
+ const rate = (d.oneShotTurns / d.editTurns) * 100;
190
+ if (!worst || rate < worst.rate) {
191
+ worst = { category: CATEGORY_LABELS[cat] ?? cat, rate, editTurns: d.editTurns };
192
+ }
193
+ }
194
+ return worst;
195
+ }
196
+ // Coaching-note thresholds. Kept conservative so a note only fires on a signal
197
+ // strong enough to act on.
198
+ const ONE_SHOT_LOW_PERCENT = 60;
199
+ const CORRECTION_HIGH_RATE = 0.15;
200
+ const CORRECTION_MIN_COUNT = 3;
201
+ const CHURN_MIN_SESSIONS = 3;
202
+ const TTFE_SLOW_MS = 5 * 60 * 1000;
203
+ function formatDurationShort(ms) {
204
+ if (ms >= 60_000)
205
+ return `${Math.round(ms / 60_000)}m`;
206
+ return `${Math.round(ms / 1000)}s`;
207
+ }
208
+ /// 1-3 templated one-liners keyed on the strongest workflow signals. Pure
209
+ /// templating on already-computed numbers. Copy is dry and specific and uses no
210
+ /// em-dashes (UI copy house style).
211
+ export function buildCoachingNotes(input) {
212
+ const notes = [];
213
+ const ws = input.worstOneShot;
214
+ if (ws && ws.editTurns >= MIN_ONE_SHOT_EDIT_TURNS && ws.rate < ONE_SHOT_LOW_PERCENT) {
215
+ notes.push(`One-shot rate on ${ws.category} is ${Math.round(ws.rate)}% over ${ws.editTurns} edit turns. Add the constraints up front or split the work into smaller edits.`);
216
+ }
217
+ if (input.correctionRate != null && input.correctionRate >= CORRECTION_HIGH_RATE && (input.corrections ?? 0) >= CORRECTION_MIN_COUNT) {
218
+ notes.push(`You corrected the assistant on ${Math.round(input.correctionRate * 100)}% of prompts (${input.corrections} times). State the requirements in the first message to cut the back and forth.`);
219
+ }
220
+ const cf = input.topReworkedFile;
221
+ if (cf && cf.sessions >= CHURN_MIN_SESSIONS) {
222
+ notes.push(`${cf.path} was reworked across ${cf.sessions} sessions (${cf.edits} edits). A focused pass on it may cost less than the repeated churn.`);
223
+ }
224
+ if (input.medianTimeToFirstEditMs != null && input.medianTimeToFirstEditMs >= TTFE_SLOW_MS) {
225
+ notes.push(`Median time to first edit is ${formatDurationShort(input.medianTimeToFirstEditMs)}. Point the assistant at the target file to cut the exploration before it starts editing.`);
226
+ }
227
+ return notes.slice(0, 3);
228
+ }
@@ -0,0 +1,198 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { execFileSync } from 'child_process';
3
+ import { existsSync, readdirSync } from 'fs';
4
+ export function wslMode(env = process.env) {
5
+ const value = (env['CODEBURN_WSL'] ?? '').trim().toLowerCase();
6
+ return value === 'off' || value === 'all' ? value : 'running';
7
+ }
8
+ /// Windows' CreateProcess searches the current directory before PATH, so
9
+ /// spawning `wsl.exe` by bare name lets anything dropped next to the CLI
10
+ /// impersonate it. Same rule as src/menubar-installer.ts: resolveSystem32Path.
11
+ function wslExePath(env) {
12
+ const root = env['SystemRoot'];
13
+ const base = root && /^[a-zA-Z]:[\\/]/.test(root) ? root.replace(/[\\/]+$/, '') : 'C:\\Windows';
14
+ return `${base}\\System32\\wsl.exe`;
15
+ }
16
+ // Distros that exist to back a container runtime; they hold no user history.
17
+ const UTILITY_DISTROS = /^(docker-desktop|podman-machine|rancher-desktop)/;
18
+ /// `wsl.exe --list --quiet` writes UTF-16LE (no BOM on some builds) with CRLF
19
+ /// line ends; piping it through a UTF-8 decode yields NUL-separated garbage.
20
+ /// Detect the encoding from the interleaved NULs rather than trusting either.
21
+ ///
22
+ /// With nothing installed, wsl.exe prints prose ("Windows Subsystem for Linux
23
+ /// has no installed distributions.", plus install hints) on stdout, and every
24
+ /// one of those lines would otherwise be probed as a distro name over UNC.
25
+ /// A name must therefore be a single token with none of the characters Windows
26
+ /// bans from a path component and no trailing period \u2014 true of every real
27
+ /// distro name, false of every line of that message, in any UI language.
28
+ // ponytail: a distro imported under a name containing a space is skipped.
29
+ // Widen to a wording-based filter only if someone actually reports one.
30
+ const DISTRO_NAME = /^[^\s\\/:*?"<>|]+$/;
31
+ export function parseWslDistros(raw) {
32
+ const text = raw.includes(0) ? raw.toString('utf16le') : raw.toString('utf8');
33
+ return text
34
+ .split(/\r?\n/)
35
+ .map(line => line.replace(/[\0\uFEFF]/g, '').trim())
36
+ .filter(name => DISTRO_NAME.test(name) && !name.endsWith('.') && !UTILITY_DISTROS.test(name));
37
+ }
38
+ // `\\wsl$\` first: it works on every WSL build, while `wsl.localhost` only
39
+ // exists on newer ones. Probing the newer spelling first would send builds
40
+ // without it through MUP -> SMB -> DNS resolution for a host named
41
+ // "wsl.localhost" \u2014 multiple seconds of stall per distro, every process.
42
+ const UNC_PREFIXES = ['\\\\wsl$\\', '\\\\wsl.localhost\\'];
43
+ /// Only the backslash spellings are matched: these paths are produced by
44
+ /// UNC_PREFIXES above and never normalized to forward slashes, and Windows
45
+ /// itself accepts `//wsl$/` only through APIs we do not use.
46
+ export function isWslUncPath(path) {
47
+ return /^\\\\wsl(\$|\.localhost)\\/i.test(path);
48
+ }
49
+ function homesUnder(base) {
50
+ const homes = [];
51
+ try {
52
+ for (const entry of readdirSync(`${base}\\home`, { withFileTypes: true })) {
53
+ if (entry.isDirectory())
54
+ homes.push(`${base}\\home\\${entry.name}`);
55
+ }
56
+ }
57
+ catch { }
58
+ try {
59
+ if (existsSync(`${base}\\root`))
60
+ homes.push(`${base}\\root`);
61
+ }
62
+ catch { }
63
+ return homes;
64
+ }
65
+ function discoverWslHomes() {
66
+ if (process.platform !== 'win32')
67
+ return [];
68
+ const mode = wslMode();
69
+ if (mode === 'off')
70
+ return [];
71
+ // Default is running-only: touching `\\wsl$\<distro>` for a *stopped* distro
72
+ // boots it, which is both intrusive and slow. `CODEBURN_WSL=all` opts in.
73
+ const args = mode === 'all' ? ['--list', '--quiet'] : ['--list', '--quiet', '--running'];
74
+ let raw;
75
+ try {
76
+ raw = execFileSync(wslExePath(process.env), args, {
77
+ timeout: 3000,
78
+ windowsHide: true,
79
+ maxBuffer: 1024 * 1024,
80
+ stdio: ['ignore', 'pipe', 'ignore'],
81
+ });
82
+ }
83
+ catch {
84
+ return [];
85
+ }
86
+ const homes = [];
87
+ for (const distro of parseWslDistros(raw)) {
88
+ for (const prefix of UNC_PREFIXES) {
89
+ const found = homesUnder(prefix + distro);
90
+ if (found.length > 0) {
91
+ homes.push(...found);
92
+ break;
93
+ }
94
+ }
95
+ }
96
+ return homes;
97
+ }
98
+ // Discovery is cached for a short TTL only — never for the process lifetime.
99
+ // In long-lived embedders (the resident serve child, menubar polling) a
100
+ // process-lifetime memo goes stale in both directions: a distro cached as
101
+ // running can be shut down, and touching a stopped distro's \\wsl$ path can
102
+ // HANG win32 fs calls (worse than an error — it is the operation the
103
+ // running-only default exists to avoid); and a distro started after an empty
104
+ // discovery would stay invisible until restart. On expiry the running-distro
105
+ // list is re-probed BEFORE any UNC path is touched, and a failed probe fails
106
+ // closed to native-only discovery — stale homes are never served in place of
107
+ // a fresh probe.
108
+ const WSL_HOMES_TTL_MS = 60_000;
109
+ let cached;
110
+ /// Every WSL home directory to treat as an extra provider root. Cached for
111
+ /// WSL_HOMES_TTL_MS (spawning wsl.exe and walking a 9P share is not free);
112
+ /// past the TTL the running-distro probe re-validates before any UNC access.
113
+ export function wslHomes(now = Date.now()) {
114
+ const mode = wslMode();
115
+ // Toggling the opt-out in a long-lived process must take effect immediately:
116
+ // do not reuse a previously discovered home and then walk its UNC share.
117
+ // Retained cache rows are handled separately by classifyWslCachePath, so
118
+ // clearing discovery here does not erase historical WSL usage.
119
+ if (mode === 'off') {
120
+ if (!cached?.pinned)
121
+ cached = undefined;
122
+ return [];
123
+ }
124
+ if (cached?.pinned)
125
+ return cached.homes;
126
+ // `running` and `all` enumerate different sets. A long-lived caller that
127
+ // changes policy must not reuse the prior mode's roots for the TTL window.
128
+ if (cached !== undefined && cached.mode === mode && now < cached.expiresAt)
129
+ return cached.homes;
130
+ const homes = discoverWslHomes();
131
+ cached = { homes, expiresAt: now + WSL_HOMES_TTL_MS, mode };
132
+ return homes;
133
+ }
134
+ /// Re-check the currently reachable homes before deciding whether an
135
+ /// undiscovered WSL cache path is merely offline or was actually deleted.
136
+ /// Bounded to the same 60s discovery TTL as wslHomes(): a stopped distro stays
137
+ /// stopped, so re-spawning wsl.exe on every full parse — up to ~3s each in the
138
+ /// resident serve/menubar — only to reconfirm "offline" is wasted work. The TTL
139
+ /// already reflects the one transition this check must catch, offline->running.
140
+ export function refreshWslHomes(now = Date.now()) {
141
+ return wslHomes(now);
142
+ }
143
+ /// Test seam: discovery shells out to wsl.exe and stats a 9P share, neither of
144
+ /// which exists on CI. Pinned homes never expire; pass `undefined` to restore
145
+ /// real discovery.
146
+ export function setWslHomes(homes) {
147
+ cached = homes === undefined
148
+ ? undefined
149
+ : { homes, expiresAt: Number.POSITIVE_INFINITY, pinned: true };
150
+ }
151
+ const WSL_CANONICAL_PATH = /^\\\\wsl(?:\$|\.localhost)\\([^\\/]+)(?:[\\/](.*))?$/i;
152
+ function canonicalWslPath(path) {
153
+ const match = WSL_CANONICAL_PATH.exec(path);
154
+ if (!match)
155
+ return undefined;
156
+ const suffix = (match[2] ?? '')
157
+ .replace(/[\\/]+/g, '\\')
158
+ .replace(/^\\+|\\+$/g, '');
159
+ // The distro/share portion is Windows-addressed, but everything below it is
160
+ // a Linux path. Preserve suffix case so homes such as `Alice` and `alice`
161
+ // are never treated as the same active root.
162
+ return `${match[1].toLowerCase()}${suffix ? `\\${suffix}` : ''}`;
163
+ }
164
+ /// Classify a cached WSL source without touching the source path itself.
165
+ /// `active` means the current WSL probe still exposes the owning home;
166
+ /// `offline` means the root is currently absent (normally stopped); and
167
+ /// `disabled` is the explicit read-policy opt-out. The alternate UNC spellings
168
+ /// are canonicalized so a cache written through `\\wsl$` still matches a
169
+ /// current probe that resolved through `\\wsl.localhost`.
170
+ export function classifyWslCachePath(path, homes) {
171
+ if (!isWslUncPath(path))
172
+ return 'not-wsl';
173
+ if (wslMode() === 'off')
174
+ return 'disabled';
175
+ const canonicalPath = canonicalWslPath(path);
176
+ if (!canonicalPath)
177
+ return 'offline';
178
+ const currentHomes = homes ?? wslHomes();
179
+ for (const home of currentHomes) {
180
+ const canonicalHome = canonicalWslPath(home);
181
+ if (canonicalHome && (canonicalPath === canonicalHome || canonicalPath.startsWith(`${canonicalHome}\\`))) {
182
+ return 'active';
183
+ }
184
+ }
185
+ return 'offline';
186
+ }
187
+ /// One line for `codeburn doctor` when Windows probed no WSL roots, so an
188
+ /// opt-out or a missing wsl.exe reads as a reason rather than a silent zero.
189
+ export function wslDoctorNote(platform = process.platform) {
190
+ if (platform !== 'win32')
191
+ return undefined;
192
+ if (wslMode() === 'off')
193
+ return 'WSL scan disabled by CODEBURN_WSL=off; no \\\\wsl$ roots were probed.';
194
+ if (wslHomes().length > 0)
195
+ return undefined;
196
+ return 'No WSL roots probed: no running distro was found, or wsl.exe is unavailable. ' +
197
+ 'Set CODEBURN_WSL=all to include stopped distros (accessing one starts it).';
198
+ }