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,67 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { lstat, readdir, stat, unlink, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { getCodeburnCacheDir } from './cache-dir.js';
5
+ import { CODEX_CACHE_VERSION } from './codex-cache.js';
6
+ import { CURSOR_CACHE_VERSION } from './cursor-cache.js';
7
+ import { CACHE_VERSION } from './session-cache.js';
8
+ const SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000;
9
+ const STALE_AFTER_MS = 14 * 24 * 60 * 60 * 1000;
10
+ const STAMP_FILE = 'cache-sweep.stamp';
11
+ /// `<family>.v<n>.json`, plus the two shapes a family's own history takes: the
12
+ /// pre-versioning `<family>.json` and the `<family>.json.v<n>.bak` copies.
13
+ /// The family part admits no digits or dots, so `status-snapshot.<hash>.json`
14
+ /// and every credential file fall outside it.
15
+ const CACHE_FILENAME = /^([a-z-]+)(?:\.v(\d+))?\.json(?:\.v(\d+)\.bak)?$/;
16
+ /// Only caches that re-derive in full from the session files. daily-cache and
17
+ /// hermes-session-ledger are left out on purpose: they hold sealed days whose
18
+ /// sources may be gone, and a version bump reads every older copy to carry them.
19
+ function currentVersions() {
20
+ return {
21
+ 'session-cache': CACHE_VERSION,
22
+ 'codex-results': CODEX_CACHE_VERSION,
23
+ 'cursor-results': CURSOR_CACHE_VERSION,
24
+ };
25
+ }
26
+ /// True only for a KNOWN cache family at a version this binary has moved past
27
+ /// (the unversioned legacy name counts as the oldest version there is).
28
+ export function isSupersededCacheFile(name) {
29
+ const match = CACHE_FILENAME.exec(name);
30
+ if (!match)
31
+ return false;
32
+ const current = currentVersions()[match[1]];
33
+ if (current === undefined)
34
+ return false;
35
+ const version = match[2] ?? match[3];
36
+ return version === undefined || Number(version) < current;
37
+ }
38
+ /// Delete cache files a version bump left behind — a single superseded
39
+ /// session-cache runs to 100MB+ and nothing ever reclaimed them. Deliberately
40
+ /// timid: known filenames only, strictly older versions only, plain files
41
+ /// only (never a directory or a symlink), inside the resolved cache dir only,
42
+ /// and only once a file has gone untouched for a fortnight — an older CLI or
43
+ /// menubar still in use keeps writing its own files, so they survive.
44
+ export async function sweepSupersededCacheFiles(now = Date.now()) {
45
+ try {
46
+ const dir = getCodeburnCacheDir();
47
+ const stamp = join(dir, STAMP_FILE);
48
+ const lastSweep = await stat(stamp).then(s => s.mtimeMs, () => 0);
49
+ if (now - lastSweep < SWEEP_INTERVAL_MS)
50
+ return;
51
+ // Stamped before the pass, so a failure mid-sweep waits for tomorrow
52
+ // rather than retrying on every save.
53
+ await writeFile(stamp, '');
54
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
55
+ if (!entry.isFile() || !isSupersededCacheFile(entry.name))
56
+ continue;
57
+ const path = join(dir, entry.name);
58
+ const stats = await lstat(path).catch(() => null);
59
+ if (!stats?.isFile() || now - stats.mtimeMs < STALE_AFTER_MS)
60
+ continue;
61
+ await unlink(path).catch(() => { });
62
+ }
63
+ }
64
+ catch {
65
+ // Housekeeping never fails a save.
66
+ }
67
+ }
@@ -0,0 +1,209 @@
1
+ import { isReadShapedBashCommand } from './bash-utils.js';
2
+ const TEST_PATTERNS = /\b(test|pytest|vitest|jest|mocha|spec|coverage|npm\s+test|npx\s+vitest|npx\s+jest)\b/i;
3
+ const GIT_PATTERNS = /\bgit\s+(push|pull|commit|merge|rebase|checkout|branch|stash|log|diff|status|add|reset|cherry-pick|tag)\b/i;
4
+ const BUILD_PATTERNS = /\b(npm\s+run\s+build|npm\s+publish|pip\s+install|docker|deploy|make\s+build|npm\s+run\s+dev|npm\s+start|pm2|systemctl|brew|cargo\s+build)\b/i;
5
+ const INSTALL_PATTERNS = /\b(npm\s+install|pip\s+install|brew\s+install|apt\s+install|cargo\s+add)\b/i;
6
+ const DEBUG_KEYWORDS = /\b(fix|bug|error|broken|failing|crash|issue|debug|traceback|exception|stack\s*trace|not\s+working|wrong|unexpected|status\s+code|404|500|401|403)\b/i;
7
+ const FEATURE_KEYWORDS = /\b(add|create|implement|new|build|feature|introduce|set\s*up|scaffold|generate|make\s+(?:a|me|the)|write\s+(?:a|me|the))\b/i;
8
+ const REFACTOR_KEYWORDS = /\b(refactor|clean\s*up|rename|reorganize|simplify|extract|restructure|move|migrate|split)\b/i;
9
+ const BRAINSTORM_KEYWORDS = /\b(brainstorm|idea|what\s+if|explore|think\s+about|approach|strategy|design|consider|how\s+should|what\s+would|opinion|suggest|recommend)\b/i;
10
+ const RESEARCH_KEYWORDS = /\b(research|investigate|look\s+into|find\s+out|check|search|analyze|review|understand|explain|how\s+does|what\s+is|show\s+me|list|compare)\b/i;
11
+ const FILE_PATTERNS = /\.(py|js|ts|tsx|jsx|json|yaml|yml|toml|sql|sh|go|rs|java|rb|php|css|html|md|csv|xml)\b/i;
12
+ const SCRIPT_PATTERNS = /\b(run\s+\S+\.\w+|execute|scrip?t|curl|api\s+\S+|endpoint|request\s+url|fetch\s+\S+|query|database|db\s+\S+)\b/i;
13
+ const URL_PATTERN = /https?:\/\/\S+/i;
14
+ export const EDIT_TOOLS = new Set(['Edit', 'Write', 'FileEditTool', 'FileWriteTool', 'NotebookEdit', 'cursor:edit', 'cursor:strreplace', 'cursor:write', 'edit', 'write']);
15
+ const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'FileReadTool', 'GrepTool', 'GlobTool']);
16
+ // Claude Code on Windows runs shell commands through a tool named PowerShell.
17
+ export const BASH_TOOLS = new Set(['Bash', 'BashTool', 'PowerShell', 'PowerShellTool']);
18
+ const TASK_TOOLS = new Set(['TaskCreate', 'TaskUpdate', 'TaskGet', 'TaskList', 'TaskOutput', 'TaskStop', 'TodoWrite']);
19
+ const SEARCH_TOOLS = new Set(['WebSearch', 'WebFetch', 'ToolSearch']);
20
+ function hasEditTools(tools) {
21
+ return tools.some(t => EDIT_TOOLS.has(t));
22
+ }
23
+ function hasReadTools(tools) {
24
+ return tools.some(t => READ_TOOLS.has(t));
25
+ }
26
+ function hasBashTool(tools) {
27
+ return tools.some(t => BASH_TOOLS.has(t));
28
+ }
29
+ function hasTaskTools(tools) {
30
+ return tools.some(t => TASK_TOOLS.has(t));
31
+ }
32
+ function hasSearchTools(tools) {
33
+ return tools.some(t => SEARCH_TOOLS.has(t));
34
+ }
35
+ function hasMcpTools(tools) {
36
+ return tools.some(t => t.startsWith('mcp__'));
37
+ }
38
+ function hasSkillTool(tools) {
39
+ return tools.some(t => t === 'Skill');
40
+ }
41
+ function getAllTools(turn) {
42
+ return turn.assistantCalls.flatMap(c => c.tools);
43
+ }
44
+ function getAllSkills(turn) {
45
+ return turn.assistantCalls.flatMap(c => c.skills ?? []);
46
+ }
47
+ function classifyByToolPattern(turn) {
48
+ const tools = getAllTools(turn);
49
+ if (tools.length === 0)
50
+ return null;
51
+ if (turn.assistantCalls.some(c => c.hasPlanMode))
52
+ return 'planning';
53
+ if (turn.assistantCalls.some(c => c.hasAgentSpawn))
54
+ return 'delegation';
55
+ const hasEdits = hasEditTools(tools);
56
+ const hasReads = hasReadTools(tools);
57
+ const hasBash = hasBashTool(tools);
58
+ const hasTasks = hasTaskTools(tools);
59
+ const hasSearch = hasSearchTools(tools);
60
+ const hasMcp = hasMcpTools(tools);
61
+ const hasSkill = hasSkillTool(tools);
62
+ if (hasBash && !hasEdits) {
63
+ const userMsg = turn.userMessage;
64
+ if (TEST_PATTERNS.test(userMsg))
65
+ return 'testing';
66
+ if (GIT_PATTERNS.test(userMsg))
67
+ return 'git';
68
+ if (BUILD_PATTERNS.test(userMsg))
69
+ return 'build/deploy';
70
+ if (INSTALL_PATTERNS.test(userMsg))
71
+ return 'build/deploy';
72
+ }
73
+ if (hasEdits)
74
+ return 'coding';
75
+ if (hasBash && hasReads)
76
+ return 'exploration';
77
+ if (hasBash)
78
+ return 'coding';
79
+ if (hasSearch || hasMcp)
80
+ return 'exploration';
81
+ if (hasReads && !hasEdits)
82
+ return 'exploration';
83
+ if (hasTasks && !hasEdits)
84
+ return 'planning';
85
+ if (hasSkill)
86
+ return 'general';
87
+ return null;
88
+ }
89
+ /// Picks the category whose keyword pattern matches earliest in the message.
90
+ /// On a tie (same start index) the candidate listed first in `candidates` wins,
91
+ /// so callers control tie-break priority by ordering. Returns null when no
92
+ /// pattern matches. The first-match heuristic fixes the long-standing problem
93
+ /// where "add error handling" was tagged Debugging because the DEBUG regex was
94
+ /// checked before FEATURE; now FEATURE wins because "add" appears before
95
+ /// "error". Issue #196.
96
+ function firstMatchingCategory(text, candidates) {
97
+ let best = null;
98
+ for (let i = 0; i < candidates.length; i++) {
99
+ const c = candidates[i];
100
+ const m = c.regex.exec(text);
101
+ if (!m)
102
+ continue;
103
+ if (!best || m.index < best.index || (m.index === best.index && i < best.order)) {
104
+ best = { index: m.index, order: i, category: c.category };
105
+ }
106
+ }
107
+ return best?.category ?? null;
108
+ }
109
+ function refineByKeywords(category, userMessage) {
110
+ if (category === 'coding') {
111
+ // Tie-break order (when two keywords match at the same index): refactoring
112
+ // first because its words are the most specific, then feature, then debug.
113
+ return firstMatchingCategory(userMessage, [
114
+ { regex: REFACTOR_KEYWORDS, category: 'refactoring' },
115
+ { regex: FEATURE_KEYWORDS, category: 'feature' },
116
+ { regex: DEBUG_KEYWORDS, category: 'debugging' },
117
+ ]) ?? 'coding';
118
+ }
119
+ if (category === 'exploration') {
120
+ if (RESEARCH_KEYWORDS.test(userMessage))
121
+ return 'exploration';
122
+ if (DEBUG_KEYWORDS.test(userMessage))
123
+ return 'debugging';
124
+ return 'exploration';
125
+ }
126
+ return category;
127
+ }
128
+ function classifyConversation(userMessage) {
129
+ if (BRAINSTORM_KEYWORDS.test(userMessage))
130
+ return 'brainstorming';
131
+ if (RESEARCH_KEYWORDS.test(userMessage))
132
+ return 'exploration';
133
+ // Same first-match-wins logic as refineByKeywords so a chat-only message
134
+ // starting with a feature verb does not flip to debugging because of an
135
+ // incidental "error" or "fix" word later in the same sentence.
136
+ const debugOrFeature = firstMatchingCategory(userMessage, [
137
+ { regex: FEATURE_KEYWORDS, category: 'feature' },
138
+ { regex: DEBUG_KEYWORDS, category: 'debugging' },
139
+ ]);
140
+ if (debugOrFeature)
141
+ return debugOrFeature;
142
+ if (FILE_PATTERNS.test(userMessage))
143
+ return 'coding';
144
+ if (SCRIPT_PATTERNS.test(userMessage))
145
+ return 'coding';
146
+ if (URL_PATTERN.test(userMessage))
147
+ return 'exploration';
148
+ return 'conversation';
149
+ }
150
+ function countRetries(turn) {
151
+ const steps = [];
152
+ for (const call of turn.assistantCalls) {
153
+ if (call.toolSequence && call.toolSequence.length > 0) {
154
+ steps.push(...call.toolSequence);
155
+ }
156
+ else if (call.tools.length > 0) {
157
+ steps.push(call.tools.map(t => ({ tool: t })));
158
+ }
159
+ }
160
+ const lastEditStep = new Map();
161
+ let lastVerifyStep = -1;
162
+ let retries = 0;
163
+ steps.forEach((step, i) => {
164
+ for (const call of step) {
165
+ if (BASH_TOOLS.has(call.tool)) {
166
+ // A read-shaped shell command (rg/cat/git log) is a lookup, not a
167
+ // verification of the previous edit: edit -> grep -> edit is research,
168
+ // and counting it as a retry penalized bash-first workflows (#941).
169
+ // A command we cannot classify keeps the old behavior.
170
+ if (!call.command || !isReadShapedBashCommand(call.command)) {
171
+ lastVerifyStep = i;
172
+ }
173
+ }
174
+ if (EDIT_TOOLS.has(call.tool)) {
175
+ const fileKey = call.file ?? '__no_file__';
176
+ const prevStep = lastEditStep.get(fileKey);
177
+ if (prevStep !== undefined && lastVerifyStep > prevStep && lastVerifyStep < i) {
178
+ retries++;
179
+ }
180
+ lastEditStep.set(fileKey, i);
181
+ }
182
+ }
183
+ });
184
+ return retries;
185
+ }
186
+ function turnHasEdits(turn) {
187
+ return turn.assistantCalls.some(c => c.tools.some(t => EDIT_TOOLS.has(t)));
188
+ }
189
+ export function classifyTurn(turn) {
190
+ const tools = getAllTools(turn);
191
+ let category;
192
+ if (tools.length === 0) {
193
+ category = classifyConversation(turn.userMessage);
194
+ }
195
+ else {
196
+ const toolCategory = classifyByToolPattern(turn);
197
+ if (toolCategory) {
198
+ category = refineByKeywords(toolCategory, turn.userMessage);
199
+ }
200
+ else {
201
+ category = classifyConversation(turn.userMessage);
202
+ }
203
+ }
204
+ const result = { ...turn, category, retries: countRetries(turn), hasEdits: turnHasEdits(turn) };
205
+ const skills = getAllSkills(turn);
206
+ if (skills.length > 0)
207
+ result.subCategory = skills[0];
208
+ return result;
209
+ }
@@ -0,0 +1,223 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import { mkdir, readFile, rename, stat, writeFile } from 'fs/promises';
4
+ import { homedir } from 'os';
5
+ import { dirname, join, resolve } from 'path';
6
+ import { behavioralCallWeight } from './behavioral-weight.js';
7
+ import { readExistingTextFile } from './cache-dir.js';
8
+ import { getConfigDir } from './config.js';
9
+ import { getClaudeConfigDirs } from './providers/claude.js';
10
+ import { readClaudePlan } from './quota/claude.js';
11
+ import { inferSessionProvider } from './session-output.js';
12
+ export const UNATTRIBUTED = 'unattributed';
13
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
+ export function identityLogPath() {
15
+ return join(getConfigDir(), 'identity-log.v1.json');
16
+ }
17
+ // 12 hex (48 bits) keeps a few local accounts apart without storing anything that maps back to the raw id.
18
+ function shortHash(uuid) {
19
+ return createHash('sha256').update(uuid).digest('hex').slice(0, 12);
20
+ }
21
+ function cleanUuid(value) {
22
+ return typeof value === 'string' && UUID_RE.test(value.trim()) ? value.trim().toLowerCase() : undefined;
23
+ }
24
+ function cleanName(value) {
25
+ const name = typeof value === 'string' ? value.trim() : '';
26
+ return name && name.length <= 256 && !/[\x00-\x1f\x7f]/.test(name) ? name : undefined;
27
+ }
28
+ function claudeJsonCandidates(configDir) {
29
+ return resolve(configDir) === resolve(join(homedir(), '.claude'))
30
+ ? [join(homedir(), '.claude.json'), join(configDir, '.claude.json')]
31
+ : [join(configDir, '.claude.json')];
32
+ }
33
+ export async function readClaudeAccount(file) {
34
+ try {
35
+ const account = JSON.parse(await readFile(file, 'utf-8'))?.oauthAccount;
36
+ const accountUuid = cleanUuid(account?.accountUuid);
37
+ if (!accountUuid)
38
+ return null;
39
+ return { accountUuid, organizationUuid: cleanUuid(account?.organizationUuid), organizationName: cleanName(account?.organizationName) };
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ export async function readIdentityLog() {
46
+ const file = await readExistingTextFile(identityLogPath());
47
+ if (file.status === 'absent')
48
+ return { version: 1, entries: [], labels: {} };
49
+ if (file.status === 'unreadable')
50
+ return null;
51
+ try {
52
+ const parsed = JSON.parse(file.text);
53
+ return parsed?.version === 1 && Array.isArray(parsed.entries) ? { ...parsed, labels: parsed.labels ?? {} } : null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ async function writeIdentityLog(log) {
60
+ const path = identityLogPath();
61
+ await mkdir(dirname(path), { recursive: true });
62
+ const tmp = `${path}.${randomBytes(8).toString('hex')}.tmp`;
63
+ await writeFile(tmp, JSON.stringify(log, null, 2) + '\n', { mode: 0o600 });
64
+ await rename(tmp, path);
65
+ }
66
+ const observedStats = new Map();
67
+ export async function observeClaudeIdentities(now = new Date()) {
68
+ for (const configDir of await getClaudeConfigDirs()) {
69
+ const files = claudeJsonCandidates(configDir);
70
+ const key = (await Promise.all(files.map(f => stat(f).then(s => `${s.mtimeMs}:${s.size}`, () => '-')))).join('|');
71
+ if (observedStats.get(configDir) === key)
72
+ continue;
73
+ observedStats.set(configDir, key);
74
+ let account = null;
75
+ for (const file of files)
76
+ if ((account = await readClaudeAccount(file)))
77
+ break;
78
+ if (!account)
79
+ continue;
80
+ const log = await readIdentityLog();
81
+ if (!log)
82
+ return;
83
+ const accountHash = shortHash(account.accountUuid);
84
+ const orgHash = account.organizationUuid ? shortHash(account.organizationUuid) : undefined;
85
+ const plan = await readClaudePlan(configDir);
86
+ const last = log.entries.filter(e => e.configDir === configDir).at(-1);
87
+ if (last?.accountHash === accountHash && last.orgHash === orgHash && (!plan || last.plan === plan))
88
+ continue;
89
+ log.entries.push({ accountHash, ...(orgHash ? { orgHash } : {}), label: account.organizationName ?? '', ...(plan ? { plan } : {}), observedAt: now.toISOString(), configDir });
90
+ await writeIdentityLog(log);
91
+ }
92
+ }
93
+ export async function recordClaudePlan(configDir, name, now = new Date()) {
94
+ const plan = cleanName(name);
95
+ if (!plan)
96
+ return;
97
+ await observeClaudeIdentities(now);
98
+ const log = await readIdentityLog();
99
+ const last = log?.entries.filter(e => e.configDir === configDir).at(-1);
100
+ if (!log || !last || last.plan === plan)
101
+ return;
102
+ log.entries.push({ ...last, plan, observedAt: now.toISOString() });
103
+ await writeIdentityLog(log);
104
+ }
105
+ /** An identity is one account in one organization, or the account when Claude reports no organization. */
106
+ export function identityId(entry) {
107
+ return entry.orgHash ? entry.orgHash.slice(0, 6) + entry.accountHash.slice(0, 6) : entry.accountHash;
108
+ }
109
+ function identityIds(log) {
110
+ return [...new Set(log.entries.map(identityId))];
111
+ }
112
+ export async function multipleIdentities() {
113
+ const log = await readIdentityLog().catch(() => null);
114
+ return !!log && identityIds(log).length >= 2;
115
+ }
116
+ function baseLabel(log, hash) {
117
+ const entries = log.entries.filter(e => identityId(e) === hash);
118
+ const orgHash = entries.at(-1)?.orgHash;
119
+ return log.labels[hash] || (orgHash && log.labels[orgHash]) || entries.filter(e => e.label).at(-1)?.label || hash;
120
+ }
121
+ export function identityLabel(log, hash) {
122
+ if (hash === UNATTRIBUTED)
123
+ return UNATTRIBUTED;
124
+ const label = baseLabel(log, hash);
125
+ const account = log.entries.find(e => identityId(e) === hash)?.accountHash;
126
+ const shared = identityIds(log).some(id => id !== hash && baseLabel(log, id) === label);
127
+ return shared && account ? `${label} (${account.slice(0, 4)})` : label;
128
+ }
129
+ function identityResolver(log) {
130
+ const marks = log.entries.map(e => ({ configDir: e.configDir, at: Date.parse(e.observedAt), hash: identityId(e) }));
131
+ const known = new Map();
132
+ return (configDir, timestamp) => {
133
+ const at = Date.parse(timestamp);
134
+ let hash = UNATTRIBUTED;
135
+ for (const mark of marks)
136
+ if (mark.configDir === configDir && mark.at <= at)
137
+ hash = mark.hash;
138
+ let identity = known.get(hash);
139
+ if (!identity) {
140
+ const plan = log.entries.filter(e => identityId(e) === hash && e.plan).at(-1)?.plan;
141
+ known.set(hash, identity = { hash, label: identityLabel(log, hash), ...(plan ? { plan } : {}) });
142
+ }
143
+ return identity;
144
+ };
145
+ }
146
+ export function identityAt(log, configDir, startedAt) {
147
+ return identityResolver(log)(configDir, startedAt);
148
+ }
149
+ function sessionConfigDir(session) {
150
+ return session.source?.kind === 'claude-config' ? session.source.path : undefined;
151
+ }
152
+ let appliedResolver;
153
+ /** Observes, then stamps every Claude session with the account active at its start. Without `always`, a log of fewer than two accounts leaves sessions untouched. */
154
+ export async function applyClaudeIdentities(projects, always = false) {
155
+ await observeClaudeIdentities().catch(() => { });
156
+ const log = await readIdentityLog().catch(() => null);
157
+ if (!log || (!always && identityIds(log).length < 2))
158
+ return projects;
159
+ const resolver = appliedResolver = identityResolver(log);
160
+ const attribute = (session) => inferSessionProvider(session) !== 'claude' ? session : {
161
+ ...session,
162
+ identity: resolver(sessionConfigDir(session), session.firstTimestamp),
163
+ };
164
+ return projects.map(project => ({
165
+ ...project,
166
+ sessions: project.sessions.map(attribute),
167
+ ...(project.subagentAnchors ? { subagentAnchors: project.subagentAnchors.map(attribute) } : {}),
168
+ }));
169
+ }
170
+ /** Per-identity totals, each call credited to the account active at its own time; undefined when fewer than `min` identities. */
171
+ export function identitySplit(projects, min = 2) {
172
+ const rows = new Map();
173
+ const credit = (session, identity, cost, calls) => {
174
+ const row = rows.get(identity.hash) ?? { ...identity, cost: 0, calls: 0, sessions: 0, ids: new Set() };
175
+ row.cost += cost;
176
+ row.calls += calls;
177
+ if (!session.isSidechain)
178
+ row.ids.add(session.sessionId);
179
+ rows.set(identity.hash, row);
180
+ };
181
+ for (const session of projects.flatMap(project => project.sessions)) {
182
+ if (!session.identity)
183
+ continue;
184
+ const calls = (session.turns ?? []).flatMap(turn => turn.assistantCalls);
185
+ if (!appliedResolver || calls.length === 0)
186
+ credit(session, session.identity, session.totalCostUSD, session.apiCalls);
187
+ else
188
+ for (const call of calls)
189
+ credit(session, appliedResolver(sessionConfigDir(session), call.timestamp), call.costUSD, behavioralCallWeight(call));
190
+ }
191
+ if (rows.size < min)
192
+ return undefined;
193
+ return [...rows.values()]
194
+ .map(({ ids, ...row }) => ({ ...row, sessions: ids.size }))
195
+ .sort((a, b) => b.cost - a.cost);
196
+ }
197
+ /** Resolves an identity hash or label (case-insensitive) to its identity hash; an organization hash or a shared label resolves to every account it covers. */
198
+ export async function resolveIdentity(value) {
199
+ if (value === UNATTRIBUTED)
200
+ return [UNATTRIBUTED];
201
+ const log = await readIdentityLog();
202
+ if (!log)
203
+ return null;
204
+ const hashes = identityIds(log);
205
+ const lower = value.toLowerCase();
206
+ const one = hashes.find(h => h === value) ?? hashes.find(h => identityLabel(log, h).toLowerCase() === lower);
207
+ if (one)
208
+ return [one];
209
+ const group = hashes.filter(h => log.entries.some(e => e.orgHash === value && identityId(e) === h) || baseLabel(log, h).toLowerCase() === lower);
210
+ return group.length > 0 ? group : null;
211
+ }
212
+ export async function setIdentityLabel(hash, name) {
213
+ const log = await readIdentityLog();
214
+ if (!log)
215
+ throw new Error(`cannot read ${identityLogPath()}`);
216
+ if (!identityIds(log).includes(hash) && !log.entries.some(e => e.orgHash === hash))
217
+ throw new Error(`no Claude identity ${hash} in the identity log; see \`codeburn identity list\``);
218
+ const label = cleanName(name);
219
+ if (!label)
220
+ throw new Error('label must be 1-256 printable characters');
221
+ log.labels[hash] = label;
222
+ await writeIdentityLog(log);
223
+ }