claude-mycelium 2.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 (207) hide show
  1. package/.claude/settings.local.json +14 -0
  2. package/README.md +304 -0
  3. package/dist/coordination/gradient-cache.d.ts +48 -0
  4. package/dist/coordination/gradient-cache.d.ts.map +1 -0
  5. package/dist/coordination/gradient-cache.js +145 -0
  6. package/dist/coordination/gradient-cache.js.map +1 -0
  7. package/dist/coordination/index.d.ts +10 -0
  8. package/dist/coordination/index.d.ts.map +1 -0
  9. package/dist/coordination/index.js +10 -0
  10. package/dist/coordination/index.js.map +1 -0
  11. package/dist/core/agent-executor.d.ts +31 -0
  12. package/dist/core/agent-executor.d.ts.map +1 -0
  13. package/dist/core/agent-executor.js +257 -0
  14. package/dist/core/agent-executor.js.map +1 -0
  15. package/dist/core/change-applier.d.ts +10 -0
  16. package/dist/core/change-applier.d.ts.map +1 -0
  17. package/dist/core/change-applier.js +32 -0
  18. package/dist/core/change-applier.js.map +1 -0
  19. package/dist/core/gradient.d.ts +60 -0
  20. package/dist/core/gradient.d.ts.map +1 -0
  21. package/dist/core/gradient.js +191 -0
  22. package/dist/core/gradient.js.map +1 -0
  23. package/dist/core/index.d.ts +24 -0
  24. package/dist/core/index.d.ts.map +1 -0
  25. package/dist/core/index.js +24 -0
  26. package/dist/core/index.js.map +1 -0
  27. package/dist/core/mode-selector.d.ts +44 -0
  28. package/dist/core/mode-selector.d.ts.map +1 -0
  29. package/dist/core/mode-selector.js +208 -0
  30. package/dist/core/mode-selector.js.map +1 -0
  31. package/dist/core/signals/centrality.d.ts +44 -0
  32. package/dist/core/signals/centrality.d.ts.map +1 -0
  33. package/dist/core/signals/centrality.js +264 -0
  34. package/dist/core/signals/centrality.js.map +1 -0
  35. package/dist/core/signals/churn.d.ts +41 -0
  36. package/dist/core/signals/churn.d.ts.map +1 -0
  37. package/dist/core/signals/churn.js +188 -0
  38. package/dist/core/signals/churn.js.map +1 -0
  39. package/dist/core/signals/complexity.d.ts +29 -0
  40. package/dist/core/signals/complexity.d.ts.map +1 -0
  41. package/dist/core/signals/complexity.js +169 -0
  42. package/dist/core/signals/complexity.js.map +1 -0
  43. package/dist/core/signals/debt.d.ts +27 -0
  44. package/dist/core/signals/debt.d.ts.map +1 -0
  45. package/dist/core/signals/debt.js +80 -0
  46. package/dist/core/signals/debt.js.map +1 -0
  47. package/dist/core/signals/errors.d.ts +32 -0
  48. package/dist/core/signals/errors.d.ts.map +1 -0
  49. package/dist/core/signals/errors.js +73 -0
  50. package/dist/core/signals/errors.js.map +1 -0
  51. package/dist/core/signals/index.d.ts +19 -0
  52. package/dist/core/signals/index.d.ts.map +1 -0
  53. package/dist/core/signals/index.js +19 -0
  54. package/dist/core/signals/index.js.map +1 -0
  55. package/dist/cost/cost-tracker.d.ts +90 -0
  56. package/dist/cost/cost-tracker.d.ts.map +1 -0
  57. package/dist/cost/cost-tracker.js +305 -0
  58. package/dist/cost/cost-tracker.js.map +1 -0
  59. package/dist/cost/index.d.ts +56 -0
  60. package/dist/cost/index.d.ts.map +1 -0
  61. package/dist/cost/index.js +111 -0
  62. package/dist/cost/index.js.map +1 -0
  63. package/dist/index.d.ts +35 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +40 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/llm/anthropic-client.d.ts +52 -0
  68. package/dist/llm/anthropic-client.d.ts.map +1 -0
  69. package/dist/llm/anthropic-client.js +310 -0
  70. package/dist/llm/anthropic-client.js.map +1 -0
  71. package/dist/llm/index.d.ts +27 -0
  72. package/dist/llm/index.d.ts.map +1 -0
  73. package/dist/llm/index.js +34 -0
  74. package/dist/llm/index.js.map +1 -0
  75. package/dist/prompts/complexity-reducer.d.ts +7 -0
  76. package/dist/prompts/complexity-reducer.d.ts.map +1 -0
  77. package/dist/prompts/complexity-reducer.js +55 -0
  78. package/dist/prompts/complexity-reducer.js.map +1 -0
  79. package/dist/prompts/debt-payer.d.ts +7 -0
  80. package/dist/prompts/debt-payer.d.ts.map +1 -0
  81. package/dist/prompts/debt-payer.js +55 -0
  82. package/dist/prompts/debt-payer.js.map +1 -0
  83. package/dist/prompts/error-reducer.d.ts +7 -0
  84. package/dist/prompts/error-reducer.d.ts.map +1 -0
  85. package/dist/prompts/error-reducer.js +54 -0
  86. package/dist/prompts/error-reducer.js.map +1 -0
  87. package/dist/prompts/index.d.ts +22 -0
  88. package/dist/prompts/index.d.ts.map +1 -0
  89. package/dist/prompts/index.js +112 -0
  90. package/dist/prompts/index.js.map +1 -0
  91. package/dist/prompts/stabilizer.d.ts +7 -0
  92. package/dist/prompts/stabilizer.d.ts.map +1 -0
  93. package/dist/prompts/stabilizer.js +55 -0
  94. package/dist/prompts/stabilizer.js.map +1 -0
  95. package/dist/prompts/types.d.ts +14 -0
  96. package/dist/prompts/types.d.ts.map +1 -0
  97. package/dist/prompts/types.js +5 -0
  98. package/dist/prompts/types.js.map +1 -0
  99. package/dist/trace/index.d.ts +51 -0
  100. package/dist/trace/index.d.ts.map +1 -0
  101. package/dist/trace/index.js +60 -0
  102. package/dist/trace/index.js.map +1 -0
  103. package/dist/trace/trace-event.d.ts +72 -0
  104. package/dist/trace/trace-event.d.ts.map +1 -0
  105. package/dist/trace/trace-event.js +244 -0
  106. package/dist/trace/trace-event.js.map +1 -0
  107. package/dist/types/index.d.ts +206 -0
  108. package/dist/types/index.d.ts.map +1 -0
  109. package/dist/types/index.js +6 -0
  110. package/dist/types/index.js.map +1 -0
  111. package/dist/utils/ci-provider.d.ts +43 -0
  112. package/dist/utils/ci-provider.d.ts.map +1 -0
  113. package/dist/utils/ci-provider.js +130 -0
  114. package/dist/utils/ci-provider.js.map +1 -0
  115. package/dist/utils/config.d.ts +31 -0
  116. package/dist/utils/config.d.ts.map +1 -0
  117. package/dist/utils/config.js +85 -0
  118. package/dist/utils/config.js.map +1 -0
  119. package/dist/utils/error-provider.d.ts +51 -0
  120. package/dist/utils/error-provider.d.ts.map +1 -0
  121. package/dist/utils/error-provider.js +123 -0
  122. package/dist/utils/error-provider.js.map +1 -0
  123. package/dist/utils/file-utils.d.ts +18 -0
  124. package/dist/utils/file-utils.d.ts.map +1 -0
  125. package/dist/utils/file-utils.js +95 -0
  126. package/dist/utils/file-utils.js.map +1 -0
  127. package/dist/utils/index.d.ts +10 -0
  128. package/dist/utils/index.d.ts.map +1 -0
  129. package/dist/utils/index.js +10 -0
  130. package/dist/utils/index.js.map +1 -0
  131. package/dist/utils/logger.d.ts +36 -0
  132. package/dist/utils/logger.d.ts.map +1 -0
  133. package/dist/utils/logger.js +74 -0
  134. package/dist/utils/logger.js.map +1 -0
  135. package/docs/IMPLEMENTATION-STATUS.md +199 -0
  136. package/docs/PHASE-0-COMPLETE.md +252 -0
  137. package/docs/PHASE-1-COMPLETE.md +204 -0
  138. package/docs/PHASE-2-COMPLETE.md +233 -0
  139. package/docs/PHASE2_COMPLETION_CHECKLIST.md +290 -0
  140. package/docs/PHASE2_INTEGRATION_SUMMARY.md +255 -0
  141. package/docs/PHASE2_QUICK_REFERENCE.md +365 -0
  142. package/docs/PHASE2_TEST_RESULTS.md +282 -0
  143. package/docs/ROADMAP.md +746 -0
  144. package/docs/SNAPSHOT.md +376 -0
  145. package/docs/adrs/ADR-001-signal-computation.md +76 -0
  146. package/docs/adrs/ADR-002-inhibitor-signals.md +108 -0
  147. package/docs/adrs/ADR-003-llm-integration.md +156 -0
  148. package/docs/adrs/ADR-004-process-architecture.md +175 -0
  149. package/docs/adrs/ADR-005-testing-strategy.md +243 -0
  150. package/docs/pitch.md +94 -0
  151. package/docs/specs/fourth-spec.md +1973 -0
  152. package/docs/specs/initial-spec.md +2096 -0
  153. package/docs/specs/second-spec.md +2690 -0
  154. package/package.json +50 -0
  155. package/src/coordination/gradient-cache.ts +185 -0
  156. package/src/coordination/index.ts +10 -0
  157. package/src/core/agent-executor.ts +327 -0
  158. package/src/core/change-applier.ts +338 -0
  159. package/src/core/gradient.ts +258 -0
  160. package/src/core/index.ts +24 -0
  161. package/src/core/mode-selector.ts +243 -0
  162. package/src/core/signals/centrality.ts +328 -0
  163. package/src/core/signals/churn.ts +239 -0
  164. package/src/core/signals/complexity.ts +206 -0
  165. package/src/core/signals/debt.ts +111 -0
  166. package/src/core/signals/errors.ts +93 -0
  167. package/src/core/signals/index.ts +19 -0
  168. package/src/cost/cost-tracker.ts +410 -0
  169. package/src/cost/index.ts +143 -0
  170. package/src/index.ts +43 -0
  171. package/src/llm/anthropic-client.ts +415 -0
  172. package/src/llm/index.ts +43 -0
  173. package/src/prompts/complexity-reducer.ts +59 -0
  174. package/src/prompts/debt-payer.ts +59 -0
  175. package/src/prompts/error-reducer.ts +58 -0
  176. package/src/prompts/index.ts +128 -0
  177. package/src/prompts/stabilizer.ts +59 -0
  178. package/src/prompts/types.ts +15 -0
  179. package/src/trace/README.md +178 -0
  180. package/src/trace/index.ts +88 -0
  181. package/src/trace/trace-event.ts +324 -0
  182. package/src/types/index.ts +271 -0
  183. package/src/utils/ci-provider.ts +145 -0
  184. package/src/utils/config.ts +95 -0
  185. package/src/utils/error-provider.ts +138 -0
  186. package/src/utils/file-utils.ts +111 -0
  187. package/src/utils/index.ts +10 -0
  188. package/src/utils/logger.ts +94 -0
  189. package/test-8d713cc8-f4b7-403d-8153-57573172b94c.ts +3 -0
  190. package/tests/coordination/gradient-cache.test.ts +270 -0
  191. package/tests/core/agent-executor.test.ts +217 -0
  192. package/tests/core/change-applier.test.ts +336 -0
  193. package/tests/core/gradient.test.ts +263 -0
  194. package/tests/core/mode-selector.test.ts +239 -0
  195. package/tests/core/signals/centrality.test.ts +512 -0
  196. package/tests/core/signals/churn.test.ts +355 -0
  197. package/tests/core/signals/complexity.test.ts +284 -0
  198. package/tests/core/signals/debt.test.ts +437 -0
  199. package/tests/core/signals/errors.test.ts +350 -0
  200. package/tests/cost/cost-tracker.test.ts +475 -0
  201. package/tests/integration/phase2.test.ts +405 -0
  202. package/tests/llm/anthropic-client.test.ts +437 -0
  203. package/tests/prompts/prompts.test.ts +266 -0
  204. package/tests/trace/trace-event.test.ts +666 -0
  205. package/tests/utils/file-utils.test.ts +148 -0
  206. package/tsconfig.json +24 -0
  207. package/vitest.config.ts +28 -0
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Signal System - Index
3
+ *
4
+ * Exports all 5 signals for gradient calculation.
5
+ * Each signal returns a normalized score (0.0 - 1.0).
6
+ *
7
+ * Per ADR-001 and second-spec §2:
8
+ * - complexity: Cyclomatic complexity via AST
9
+ * - churn: Git commit frequency over 30 days
10
+ * - centrality: Import graph fan-in/fan-out
11
+ * - debt: ESLint errors and warnings
12
+ * - errors: Runtime error tracking
13
+ */
14
+ export * from './complexity.js';
15
+ export * from './churn.js';
16
+ export * from './centrality.js';
17
+ export * from './debt.js';
18
+ export * from './errors.js';
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/signals/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Represents a cost calculation for an agent run
3
+ */
4
+ export interface CostCalculation {
5
+ inputTokens: number;
6
+ outputTokens: number;
7
+ model: string;
8
+ costUSD: number;
9
+ }
10
+ /**
11
+ * Statistics about costs
12
+ */
13
+ export interface CostStats {
14
+ total: number;
15
+ byModel: Record<string, number>;
16
+ byFile: Record<string, number>;
17
+ totalInputTokens: number;
18
+ totalOutputTokens: number;
19
+ runCount: number;
20
+ }
21
+ /**
22
+ * Calculates the cost in USD for given token counts and model
23
+ * @param inputTokens Number of input tokens
24
+ * @param outputTokens Number of output tokens
25
+ * @param model Model identifier
26
+ * @returns CostCalculation with the computed cost
27
+ */
28
+ export declare function calculateCost(inputTokens: number, outputTokens: number, model: string): CostCalculation;
29
+ /**
30
+ * Records a cost calculation to the costs.jsonl file
31
+ * @param cost The cost calculation to record
32
+ * @param file Optional file path associated with this cost
33
+ */
34
+ export declare function recordCost(cost: CostCalculation, file?: string): Promise<void>;
35
+ /**
36
+ * Gets the total cost since a given date (or all time if not specified)
37
+ * @param since Optional date to filter from
38
+ * @returns Total cost in USD
39
+ */
40
+ export declare function getTotalCost(since?: Date): Promise<number>;
41
+ /**
42
+ * Gets the total cost for a specific file since a given date
43
+ * @param file File path to filter by
44
+ * @param since Optional date to filter from
45
+ * @returns Total cost in USD for that file
46
+ */
47
+ export declare function getCostByFile(file: string, since?: Date): Promise<number>;
48
+ /**
49
+ * Formats a cost amount as a USD currency string
50
+ * @param usd Cost in USD
51
+ * @returns Formatted string like "$0.0234"
52
+ */
53
+ export declare function formatCost(usd: number): string;
54
+ /**
55
+ * Gets comprehensive cost statistics
56
+ * @param since Optional date to filter from
57
+ * @returns Cost statistics including totals, by model, and by file
58
+ */
59
+ export declare function getCostStats(since?: Date): Promise<CostStats>;
60
+ /**
61
+ * Gets cost stats for a specific date
62
+ * @param date Date to get stats for (uses entire day)
63
+ * @returns Cost statistics for that date
64
+ */
65
+ export declare function getCostStatsForDate(date: Date): Promise<CostStats>;
66
+ /**
67
+ * Gets cost trends over time
68
+ * @param days Number of days to analyze
69
+ * @returns Array of daily cost totals
70
+ */
71
+ export declare function getCostTrend(days?: number): Promise<Array<{
72
+ date: string;
73
+ cost: number;
74
+ runs: number;
75
+ }>>;
76
+ /**
77
+ * Gets cost per model breakdown
78
+ * @param since Optional date to filter from
79
+ * @returns Record of model -> cost breakdown
80
+ */
81
+ export declare function getCostByModel(since?: Date): Promise<Record<string, {
82
+ cost: number;
83
+ runs: number;
84
+ avgCost: number;
85
+ }>>;
86
+ /**
87
+ * Clears all cost records (for testing)
88
+ */
89
+ export declare function clearCosts(): Promise<void>;
90
+ //# sourceMappingURL=cost-tracker.d.ts.map
@@ -0,0 +1 @@
1
+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mB,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,CAuCxE;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,IAAI,GAAE,MAAU,GAAG,OAAO,CAAC,KAAK,CAAC;IAClE,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd,CAAC,CAAC,CA8BF;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE;IACzE,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC,CAAC,CA6BF;AAED;;GAEG;AACH,wBAAsB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAMhD"}
@@ -0,0 +1,305 @@
1
+ import * as path from 'path';
2
+ import { fileExists, readFile, writeFile, appendFile, ensureDir, } from '../utils/file-utils';
3
+ import { logDebug, createLogger } from '../utils/logger';
4
+ const logger = createLogger({ module: 'cost-tracker' });
5
+ /**
6
+ * Pricing for Claude models as of January 2026
7
+ * Input and output prices per 1K tokens
8
+ */
9
+ const PRICING = {
10
+ 'claude-sonnet-4-5-20250929': {
11
+ input: 0.003,
12
+ output: 0.015,
13
+ },
14
+ 'claude-opus-4-5-20251101': {
15
+ input: 0.015,
16
+ output: 0.075,
17
+ },
18
+ 'claude-haiku-3-5': {
19
+ input: 0.0008,
20
+ output: 0.004,
21
+ },
22
+ // Legacy model support
23
+ 'claude-sonnet-4-20250514': {
24
+ input: 0.003,
25
+ output: 0.015,
26
+ },
27
+ 'claude-haiku-4-20250514': {
28
+ input: 0.0008,
29
+ output: 0.004,
30
+ },
31
+ };
32
+ /**
33
+ * Get the costs file path (respects test environment)
34
+ */
35
+ function getCostsFilePath() {
36
+ const agentMetaDir = process.env.AGENT_META || '.agent-meta';
37
+ return path.join(agentMetaDir, 'costs.jsonl');
38
+ }
39
+ /**
40
+ * Ensures the cost tracking directory exists
41
+ */
42
+ function ensureCostsDir() {
43
+ const dir = path.dirname(getCostsFilePath());
44
+ ensureDir(dir);
45
+ }
46
+ /**
47
+ * Calculates the cost in USD for given token counts and model
48
+ * @param inputTokens Number of input tokens
49
+ * @param outputTokens Number of output tokens
50
+ * @param model Model identifier
51
+ * @returns CostCalculation with the computed cost
52
+ */
53
+ export function calculateCost(inputTokens, outputTokens, model) {
54
+ const pricing = PRICING[model];
55
+ if (!pricing) {
56
+ logger.warn(`Unknown model: ${model}. Cost calculation will be 0.`, {
57
+ model,
58
+ });
59
+ return {
60
+ inputTokens,
61
+ outputTokens,
62
+ model,
63
+ costUSD: 0,
64
+ };
65
+ }
66
+ // Calculate cost: (tokens / 1000) * price_per_1k_tokens
67
+ const inputCost = (inputTokens / 1000) * pricing.input;
68
+ const outputCost = (outputTokens / 1000) * pricing.output;
69
+ const totalCost = inputCost + outputCost;
70
+ // Round to 6 decimal places
71
+ const costUSD = Math.round(totalCost * 1000000) / 1000000;
72
+ return {
73
+ inputTokens,
74
+ outputTokens,
75
+ model,
76
+ costUSD,
77
+ };
78
+ }
79
+ /**
80
+ * Records a cost calculation to the costs.jsonl file
81
+ * @param cost The cost calculation to record
82
+ * @param file Optional file path associated with this cost
83
+ */
84
+ export async function recordCost(cost, file) {
85
+ ensureCostsDir();
86
+ const record = {
87
+ timestamp: new Date().toISOString(),
88
+ model: cost.model,
89
+ inputTokens: cost.inputTokens,
90
+ outputTokens: cost.outputTokens,
91
+ costUSD: cost.costUSD,
92
+ file,
93
+ };
94
+ const line = JSON.stringify(record);
95
+ appendFile(getCostsFilePath(), line + '\n');
96
+ logDebug(`Recorded cost`, {
97
+ costUSD: cost.costUSD,
98
+ model: cost.model,
99
+ file,
100
+ });
101
+ }
102
+ /**
103
+ * Reads all cost records from the JSONL file
104
+ * @returns Array of cost records
105
+ */
106
+ function readCostRecords() {
107
+ ensureCostsDir();
108
+ const costsFile = getCostsFilePath();
109
+ if (!fileExists(costsFile)) {
110
+ return [];
111
+ }
112
+ const content = readFile(costsFile);
113
+ const lines = content.split('\n').filter((line) => line.trim());
114
+ return lines.map((line) => {
115
+ try {
116
+ return JSON.parse(line);
117
+ }
118
+ catch (err) {
119
+ logger.warn(`Failed to parse cost record`, { line });
120
+ return null;
121
+ }
122
+ }).filter((record) => record !== null);
123
+ }
124
+ /**
125
+ * Gets the total cost since a given date (or all time if not specified)
126
+ * @param since Optional date to filter from
127
+ * @returns Total cost in USD
128
+ */
129
+ export async function getTotalCost(since) {
130
+ const records = readCostRecords();
131
+ let filtered = records;
132
+ if (since) {
133
+ const sinceTime = since.getTime();
134
+ filtered = records.filter((r) => new Date(r.timestamp).getTime() >= sinceTime);
135
+ }
136
+ return filtered.reduce((sum, record) => sum + record.costUSD, 0);
137
+ }
138
+ /**
139
+ * Gets the total cost for a specific file since a given date
140
+ * @param file File path to filter by
141
+ * @param since Optional date to filter from
142
+ * @returns Total cost in USD for that file
143
+ */
144
+ export async function getCostByFile(file, since) {
145
+ const records = readCostRecords();
146
+ let filtered = records.filter((r) => r.file === file);
147
+ if (since) {
148
+ const sinceTime = since.getTime();
149
+ filtered = filtered.filter((r) => new Date(r.timestamp).getTime() >= sinceTime);
150
+ }
151
+ return filtered.reduce((sum, record) => sum + record.costUSD, 0);
152
+ }
153
+ /**
154
+ * Formats a cost amount as a USD currency string
155
+ * @param usd Cost in USD
156
+ * @returns Formatted string like "$0.0234"
157
+ */
158
+ export function formatCost(usd) {
159
+ return `$${usd.toFixed(4)}`;
160
+ }
161
+ /**
162
+ * Gets comprehensive cost statistics
163
+ * @param since Optional date to filter from
164
+ * @returns Cost statistics including totals, by model, and by file
165
+ */
166
+ export async function getCostStats(since) {
167
+ const records = readCostRecords();
168
+ let filtered = records;
169
+ if (since) {
170
+ const sinceTime = since.getTime();
171
+ filtered = records.filter((r) => new Date(r.timestamp).getTime() >= sinceTime);
172
+ }
173
+ const byModel = {};
174
+ const byFile = {};
175
+ let totalInputTokens = 0;
176
+ let totalOutputTokens = 0;
177
+ for (const record of filtered) {
178
+ // Total
179
+ byModel[record.model] = (byModel[record.model] || 0) + record.costUSD;
180
+ // By file
181
+ if (record.file) {
182
+ byFile[record.file] = (byFile[record.file] || 0) + record.costUSD;
183
+ }
184
+ // Token totals
185
+ totalInputTokens += record.inputTokens;
186
+ totalOutputTokens += record.outputTokens;
187
+ }
188
+ const total = Object.values(byModel).reduce((sum, cost) => sum + cost, 0);
189
+ return {
190
+ total,
191
+ byModel,
192
+ byFile,
193
+ totalInputTokens,
194
+ totalOutputTokens,
195
+ runCount: filtered.length,
196
+ };
197
+ }
198
+ /**
199
+ * Gets cost stats for a specific date
200
+ * @param date Date to get stats for (uses entire day)
201
+ * @returns Cost statistics for that date
202
+ */
203
+ export async function getCostStatsForDate(date) {
204
+ const startOfDay = new Date(date);
205
+ startOfDay.setHours(0, 0, 0, 0);
206
+ const endOfDay = new Date(date);
207
+ endOfDay.setHours(23, 59, 59, 999);
208
+ const records = readCostRecords();
209
+ const filtered = records.filter((r) => {
210
+ const time = new Date(r.timestamp).getTime();
211
+ return time >= startOfDay.getTime() && time <= endOfDay.getTime();
212
+ });
213
+ const byModel = {};
214
+ const byFile = {};
215
+ let totalInputTokens = 0;
216
+ let totalOutputTokens = 0;
217
+ for (const record of filtered) {
218
+ byModel[record.model] = (byModel[record.model] || 0) + record.costUSD;
219
+ if (record.file) {
220
+ byFile[record.file] = (byFile[record.file] || 0) + record.costUSD;
221
+ }
222
+ totalInputTokens += record.inputTokens;
223
+ totalOutputTokens += record.outputTokens;
224
+ }
225
+ const total = Object.values(byModel).reduce((sum, cost) => sum + cost, 0);
226
+ return {
227
+ total,
228
+ byModel,
229
+ byFile,
230
+ totalInputTokens,
231
+ totalOutputTokens,
232
+ runCount: filtered.length,
233
+ };
234
+ }
235
+ /**
236
+ * Gets cost trends over time
237
+ * @param days Number of days to analyze
238
+ * @returns Array of daily cost totals
239
+ */
240
+ export async function getCostTrend(days = 7) {
241
+ const records = readCostRecords();
242
+ // Group by day
243
+ const byDay = {};
244
+ for (const record of records) {
245
+ const date = new Date(record.timestamp);
246
+ const dateStr = date.toISOString().split('T')[0]; // YYYY-MM-DD
247
+ if (!byDay[dateStr]) {
248
+ byDay[dateStr] = { cost: 0, count: 0 };
249
+ }
250
+ byDay[dateStr].cost += record.costUSD;
251
+ byDay[dateStr].count += 1;
252
+ }
253
+ // Sort and return last N days
254
+ const sorted = Object.entries(byDay)
255
+ .sort(([dateA], [dateB]) => dateB.localeCompare(dateA))
256
+ .slice(0, days)
257
+ .map(([date, data]) => ({
258
+ date,
259
+ cost: data.cost,
260
+ runs: data.count,
261
+ }))
262
+ .reverse(); // Oldest first
263
+ return sorted;
264
+ }
265
+ /**
266
+ * Gets cost per model breakdown
267
+ * @param since Optional date to filter from
268
+ * @returns Record of model -> cost breakdown
269
+ */
270
+ export async function getCostByModel(since) {
271
+ const records = readCostRecords();
272
+ let filtered = records;
273
+ if (since) {
274
+ const sinceTime = since.getTime();
275
+ filtered = records.filter((r) => new Date(r.timestamp).getTime() >= sinceTime);
276
+ }
277
+ const byModel = {};
278
+ for (const record of filtered) {
279
+ if (!byModel[record.model]) {
280
+ byModel[record.model] = { cost: 0, count: 0 };
281
+ }
282
+ byModel[record.model].cost += record.costUSD;
283
+ byModel[record.model].count += 1;
284
+ }
285
+ const result = {};
286
+ for (const [model, data] of Object.entries(byModel)) {
287
+ result[model] = {
288
+ cost: data.cost,
289
+ runs: data.count,
290
+ avgCost: data.cost / data.count,
291
+ };
292
+ }
293
+ return result;
294
+ }
295
+ /**
296
+ * Clears all cost records (for testing)
297
+ */
298
+ export async function clearCosts() {
299
+ ensureCostsDir();
300
+ const costsFile = getCostsFilePath();
301
+ if (fileExists(costsFile)) {
302
+ writeFile(costsFile, '');
303
+ }
304
+ }
305
+ //# sourceMappingURL=cost-tracker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cost-tracker.js","sourceR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,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,KAAK;SAChC,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU;IAC9B,cAAc,EAAE,CAAC;IACjB,MAAM,SAAS,GAAG,gBAAgB,EAAE,CAAC;IACrC,IAAI,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QAC1B,SAAS,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IAC3B,CAAC;AACH,CAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Cost Module - Token and Cost Tracking
3
+ *
4
+ * Per Phase 2 specification, this module tracks:
5
+ * - Token counts (input/output)
6
+ * - Estimated USD costs based on Claude pricing
7
+ * - Efficiency metrics (improvement per dollar spent)
8
+ * - Daily/monthly cost summaries
9
+ *
10
+ * Claude Pricing (as of 2024):
11
+ * - claude-3-haiku: $0.25/1M input, $1.25/1M output
12
+ * - claude-3-sonnet: $3/1M input, $15/1M output
13
+ * - claude-3-opus: $15/1M input, $75/1M output
14
+ *
15
+ * Usage:
16
+ * ```typescript
17
+ * import { calculateCost } from './cost/index.js';
18
+ * const cost = calculateCost(inputTokens, outputTokens, 'claude-3-sonnet');
19
+ * ```
20
+ */
21
+ import type { CostRecord, CostMetrics } from '../types/index.js';
22
+ /**
23
+ * Calculate cost for an LLM request
24
+ */
25
+ export declare function calculateCost(inputTokens: number, outputTokens: number, model?: string): CostRecord;
26
+ /**
27
+ * Estimate cost based on model type alone
28
+ * Useful for pre-flight estimates
29
+ */
30
+ export declare function estimateCostByModel(approximateTokens?: number, model?: string): number;
31
+ /**
32
+ * Get available models with their pricing
33
+ */
34
+ export declare function getAvailableModels(): Array<{
35
+ id: string;
36
+ name: string;
37
+ pricing: {
38
+ input: number;
39
+ output: number;
40
+ };
41
+ }>;
42
+ /**
43
+ * Calculate efficiency metric
44
+ * Returns improvement (delta) per dollar spent
45
+ */
46
+ export declare function calculateEfficiency(gradientDelta: number, costUSD: number): number;
47
+ /**
48
+ * Get cost metrics summary (placeholder for Phase 3)
49
+ * In Phase 2, we just return an empty structure
50
+ */
51
+ export declare function getCostMetrics(): CostMetrics;
52
+ /**
53
+ * Export cost-related types
54
+ */
55
+ export type { CostRecord, CostMetrics } from '../types/index.js';
56
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cost/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAwBjE;;GAEG;AACH,wBAAgB,aAAa,CAC3B,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,EACpB,KAAK,GAAE,MAAmC,GACzC,UAAU,CAqBZ;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,iBAAiB,GAAE,MAAa,EAChC,KAAK,GAAE,MAAmC,GACzC,MAAM,CASR;AAED;;GAEG;AACH,wBAAgB,kBAAkB,IAAI,KAAK,CAAC;IAC1C,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CAC5C,CAAC,CAMD;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,MAAM,GACd,MAAM,CAMR;AAED;;;GAGG;AACH,wBAAgB,cAAc,IAAI,WAAW,CAS5C;AAED;;GAEG;AACH,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Cost Module - Token and Cost Tracking
3
+ *
4
+ * Per Phase 2 specification, this module tracks:
5
+ * - Token counts (input/output)
6
+ * - Estimated USD costs based on Claude pricing
7
+ * - Efficiency metrics (improvement per dollar spent)
8
+ * - Daily/monthly cost summaries
9
+ *
10
+ * Claude Pricing (as of 2024):
11
+ * - claude-3-haiku: $0.25/1M input, $1.25/1M output
12
+ * - claude-3-sonnet: $3/1M input, $15/1M output
13
+ * - claude-3-opus: $15/1M input, $75/1M output
14
+ *
15
+ * Usage:
16
+ * ```typescript
17
+ * import { calculateCost } from './cost/index.js';
18
+ * const cost = calculateCost(inputTokens, outputTokens, 'claude-3-sonnet');
19
+ * ```
20
+ */
21
+ import { logDebug } from '../utils/logger.js';
22
+ /**
23
+ * Claude model pricing (USD per 1M tokens)
24
+ */
25
+ const MODEL_PRICING = {
26
+ 'claude-3-haiku-20240307': {
27
+ input: 0.25,
28
+ output: 1.25,
29
+ },
30
+ 'claude-3-sonnet-20240229': {
31
+ input: 3.0,
32
+ output: 15.0,
33
+ },
34
+ 'claude-3-opus-20240229': {
35
+ input: 15.0,
36
+ output: 75.0,
37
+ },
38
+ 'claude-3-5-sonnet-20241022': {
39
+ input: 3.0,
40
+ output: 15.0,
41
+ },
42
+ };
43
+ /**
44
+ * Calculate cost for an LLM request
45
+ */
46
+ export function calculateCost(inputTokens, outputTokens, model = 'claude-3-sonnet-20240229') {
47
+ const pricing = MODEL_PRICING[model] || MODEL_PRICING['claude-3-sonnet-20240229'];
48
+ // Calculate costs in USD
49
+ const inputCost = (inputTokens / 1_000_000) * pricing.input;
50
+ const outputCost = (outputTokens / 1_000_000) * pricing.output;
51
+ const totalCost = inputCost + outputCost;
52
+ logDebug('Cost calculated', {
53
+ model,
54
+ input_tokens: inputTokens,
55
+ output_tokens: outputTokens,
56
+ total_cost_usd: totalCost.toFixed(4),
57
+ });
58
+ return {
59
+ tokens_in: inputTokens,
60
+ tokens_out: outputTokens,
61
+ model,
62
+ estimated_usd: Number(totalCost.toFixed(6)),
63
+ };
64
+ }
65
+ /**
66
+ * Estimate cost based on model type alone
67
+ * Useful for pre-flight estimates
68
+ */
69
+ export function estimateCostByModel(approximateTokens = 2000, model = 'claude-3-sonnet-20240229') {
70
+ const pricing = MODEL_PRICING[model] || MODEL_PRICING['claude-3-sonnet-20240229'];
71
+ // Assume roughly equal input/output for estimation
72
+ const halfTokens = approximateTokens / 2;
73
+ const inputCost = (halfTokens / 1_000_000) * pricing.input;
74
+ const outputCost = (halfTokens / 1_000_000) * pricing.output;
75
+ return Number((inputCost + outputCost).toFixed(6));
76
+ }
77
+ /**
78
+ * Get available models with their pricing
79
+ */
80
+ export function getAvailableModels() {
81
+ return Object.entries(MODEL_PRICING).map(([id, pricing]) => ({
82
+ id,
83
+ name: id.split('-').slice(0, 2).join('-'),
84
+ pricing,
85
+ }));
86
+ }
87
+ /**
88
+ * Calculate efficiency metric
89
+ * Returns improvement (delta) per dollar spent
90
+ */
91
+ export function calculateEfficiency(gradientDelta, costUSD) {
92
+ if (costUSD === 0) {
93
+ return 0;
94
+ }
95
+ return gradientDelta / costUSD;
96
+ }
97
+ /**
98
+ * Get cost metrics summary (placeholder for Phase 3)
99
+ * In Phase 2, we just return an empty structure
100
+ */
101
+ export function getCostMetrics() {
102
+ return {
103
+ total_usd: 0,
104
+ total_tokens_in: 0,
105
+ total_tokens_out: 0,
106
+ avg_cost_per_run: 0,
107
+ avg_cost_per_improvement: 0,
108
+ cost_efficiency_trend: 'stable',
109
+ };
110
+ }
111
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cost/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAG9C;;GAEG;AACH,MAAM,aAAa,GAAsD;IACvE,yBAAyB,EAAE;QACzB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,IAAI;KACb;IACD,0BAA0B,EAAE;QAC1B,KAAK,EAAE,GAAG;QACV,MAAM,EAAE,IAAI;KACb;IACD,wBAAwB,EAAE;QACxB,KA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AS,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;IAE7D,OAAO,MAAM,CAAC,CAAC,SAAS,GAAG,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AACrD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,kBAAkB;IAKhC,OAAO,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;QAC3D,EAAE;QACF,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QACzC,OAAO;KACR,CAAC,CAAC,CAAC;AACN,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CACjC,aAAqB,EACrB,OAAe;IAEf,IAAI,OAAO,KAAK,CAAC,EAAE,CAAC;QAClB,OAAO,CAAC,CAAC;IACX,CAAC;IAED,OAAO,aAAa,GAAG,OAAO,CAAC;AACjC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc;IAC5B,OAAO;QACL,SAAS,EAAE,CAAC;QACZ,eAAe,EAAE,CAAC;QAClB,gBAAgB,EAAE,CAAC;QACnB,gBAAgB,EAAE,CAAC;QACnB,wBAAwB,EAAE,CAAC;QAC3B,qBAAqB,EAAE,QAAQ;KAChC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Claude-Mycelium v2.0
3
+ * Main Entry Point
4
+ *
5
+ * Decentralized, gradient-driven agent system for autonomous codebase improvement.
6
+ *
7
+ * Core exports:
8
+ * - Core: Signals, Gradient, Mode Selection
9
+ * - LLM: Anthropic integration
10
+ * - Trace: Event tracking
11
+ * - Cost: Token and cost tracking
12
+ * - Utils: Logging, file I/O, configuration
13
+ * - Types: Complete TypeScript interfaces
14
+ *
15
+ * Per initial-spec and Phase 2 spec.
16
+ *
17
+ * Usage:
18
+ * ```typescript
19
+ * import {
20
+ * calculateGradient,
21
+ * selectMode,
22
+ * createAnthropicClient,
23
+ * recordTraceEvent,
24
+ * calculateCost,
25
+ * } from 'claude-mycelium';
26
+ * ```
27
+ */
28
+ export * from './core/index.js';
29
+ export * from './coordination/index.js';
30
+ export { createAnthropicClient, type LLMRequest, type LLMResponse, LLMError } from './llm/index.js';
31
+ export * from './trace/index.js';
32
+ export * from './cost/index.js';
33
+ export * from './utils/index.js';
34
+ export * from './types/index.js';
35
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,cAAc,iBAAiB,CAAC;AAChC,cAAc,yBAAyB,CAAC;AAIxC,OAAO,EAAE,qBAAqB,EAAE,KAAK,UAAU,EAAE,KAAK,WAAW,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACpG,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAGhC,cAAc,kBAAkB,CAAC;AAGjC,cAAc,kBAAkB,CAAC"}