karajan-code 2.5.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +39 -4
  2. package/package.json +5 -2
  3. package/src/agents/aider-agent.js +1 -2
  4. package/src/agents/base-agent.js +63 -1
  5. package/src/agents/claude-agent.js +3 -4
  6. package/src/agents/codex-agent.js +1 -2
  7. package/src/agents/gemini-agent.js +1 -2
  8. package/src/agents/index.js +11 -2
  9. package/src/agents/opencode-agent.js +1 -2
  10. package/src/brain/decision-tracker.js +123 -0
  11. package/src/brain/decisor.js +243 -0
  12. package/src/brain/solomon-consult.js +171 -0
  13. package/src/budget/comparison.js +96 -0
  14. package/src/checks/binaries.js +123 -0
  15. package/src/checks/ci.js +105 -0
  16. package/src/checks/config-files.js +217 -0
  17. package/src/checks/dir-setup.js +63 -0
  18. package/src/checks/mcp-health.js +157 -0
  19. package/src/checks/node.js +61 -0
  20. package/src/checks/ports.js +110 -0
  21. package/src/checks/rtk.js +36 -0
  22. package/src/checks/runner.js +267 -0
  23. package/src/checks/skills.js +49 -0
  24. package/src/checks/sonar.js +67 -0
  25. package/src/checks/system.js +53 -0
  26. package/src/checks/tokens.js +96 -0
  27. package/src/checks/types.js +105 -0
  28. package/src/cli.js +29 -3
  29. package/src/commands/board.js +23 -0
  30. package/src/commands/doctor.js +130 -362
  31. package/src/commands/resume.js +1 -1
  32. package/src/commands/run.js +2 -1
  33. package/src/commands/skills.js +49 -0
  34. package/src/config/schema.js +222 -0
  35. package/src/config.js +32 -3
  36. package/src/guards/policy-resolver.js +8 -0
  37. package/src/hu/store.js +9 -0
  38. package/src/infrastructure/command-runner.js +44 -0
  39. package/src/infrastructure/environment.js +38 -0
  40. package/src/infrastructure/file-system-service.js +63 -0
  41. package/src/infrastructure/mocks.js +182 -0
  42. package/src/mcp/handlers/management-handlers.js +7 -2
  43. package/src/mcp/tools.js +10 -3
  44. package/src/orchestrator/config-init.js +16 -1
  45. package/src/orchestrator/flow-runner.js +2085 -0
  46. package/src/orchestrator/pipeline-context.js +17 -0
  47. package/src/orchestrator/preflight-checks.js +78 -4
  48. package/src/orchestrator/solomon-escalation.js +55 -0
  49. package/src/orchestrator/stages/stage-executor.js +155 -0
  50. package/src/orchestrator.js +19 -1923
  51. package/src/prompts/architect.js +2 -2
  52. package/src/prompts/coder.js +2 -2
  53. package/src/prompts/prompt-resolver.js +127 -0
  54. package/src/prompts/reviewer.js +2 -2
  55. package/src/roles/agent-role.js +9 -0
  56. package/src/roles/architect-role.js +3 -1
  57. package/src/roles/base-role.js +40 -2
  58. package/src/roles/coder-role.js +3 -1
  59. package/src/roles/security-role.js +12 -0
  60. package/src/roles/tester-role.js +11 -0
  61. package/src/session/journal/decisions-writer.js +200 -0
  62. package/src/session/journal/iteration-logger.js +194 -0
  63. package/src/session/journal/summary-writer.js +176 -0
  64. package/src/session/journal/tree-writer.js +164 -0
  65. package/src/skills/semantic-detector.js +147 -0
  66. package/src/skills/skill-detector.js +186 -8
  67. package/src/skills/skill-loader.js +131 -1
  68. package/src/skills/skills-cache.js +128 -0
  69. package/src/types/agent.js +55 -0
  70. package/src/types/config.js +114 -0
  71. package/src/types/hu.js +47 -0
  72. package/src/types/index.js +38 -0
  73. package/src/types/policy.js +43 -0
  74. package/src/types/session.js +74 -0
  75. package/src/types/solomon.js +87 -0
  76. package/src/types/stage.js +68 -0
  77. package/src/utils/display/event-handlers.js +389 -0
  78. package/src/utils/display/formatters.js +132 -0
  79. package/src/utils/display/header.js +48 -0
  80. package/src/utils/display/session-summary.js +108 -0
  81. package/src/utils/display/solomon.js +42 -0
  82. package/src/utils/port-check.js +45 -0
  83. package/src/utils/port-occupant.js +95 -0
  84. package/src/utils/provider-env.js +116 -0
  85. package/src/utils/with-timeout.js +42 -0
  86. package/templates/roles/architect/anthropic.md +65 -0
  87. package/templates/roles/architect/default.md +63 -0
  88. package/templates/roles/architect/google.md +52 -0
  89. package/templates/roles/architect/openai.md +51 -0
  90. package/templates/roles/architect/opencode.md +50 -0
  91. package/templates/roles/coder/anthropic.md +72 -0
  92. package/templates/roles/coder/default.md +69 -0
  93. package/templates/roles/coder/google.md +78 -0
  94. package/templates/roles/coder/openai.md +59 -0
  95. package/templates/roles/coder/opencode.md +49 -0
  96. package/templates/roles/planner/anthropic.md +50 -0
  97. package/templates/roles/planner/default.md +48 -0
  98. package/templates/roles/planner/google.md +66 -0
  99. package/templates/roles/planner/openai.md +46 -0
  100. package/templates/roles/planner/opencode.md +53 -0
  101. package/templates/roles/reviewer/anthropic.md +61 -0
  102. package/templates/roles/reviewer/default.md +62 -0
  103. package/templates/roles/reviewer/google.md +63 -0
  104. package/templates/roles/reviewer/openai.md +57 -0
  105. package/templates/roles/reviewer/opencode.md +42 -0
  106. package/templates/roles/solomon/anthropic.md +71 -0
  107. package/templates/roles/solomon/default.md +83 -0
  108. package/templates/roles/solomon/google.md +61 -0
  109. package/templates/roles/solomon/openai.md +53 -0
  110. package/templates/roles/solomon/opencode.md +55 -0
  111. package/src/utils/display.js +0 -669
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Brain decisor — intent-driven pipeline routing.
3
+ *
4
+ * Takes the triage output + task text + config and produces a Decision that
5
+ * the orchestrator applies as pipelineFlags overrides. The existing stage
6
+ * if/else in runFlow continues to drive execution; Brain just tells it which
7
+ * roles are relevant for this particular task.
8
+ *
9
+ * This is an MVP that keeps the current architecture. A future iteration
10
+ * (Pipeline Sovereignty / KJC-PCS-0022) can promote the Decision into a
11
+ * true DAG with parallel stage execution.
12
+ */
13
+
14
+ /**
15
+ * @typedef {Object} TriageOutput
16
+ * @property {"trivial"|"simple"|"medium"|"complex"} level
17
+ * @property {string[]} roles - roles triage suggests running
18
+ * @property {string} [taskType] - sw | infra | doc | add-tests | refactor | no-code | audit
19
+ * @property {string} [reasoning]
20
+ * @property {number} [confidence] - 0..1, often absent
21
+ * @property {string[]} [domainHints]
22
+ */
23
+
24
+ /**
25
+ * @typedef {Object} Decision
26
+ * @property {string[]} rolesOn - roles to enable in pipelineFlags
27
+ * @property {string[]} rolesOff - roles to explicitly disable
28
+ * @property {"low"|"medium"|"high"} confidence
29
+ * @property {string} rationale - human-readable reasoning
30
+ * @property {boolean} consultSolomon - true if the Brain is unsure
31
+ * @property {string} [solomonReason] - why Solomon is needed
32
+ * @property {string[]} appliedOverrides - names of manual overrides respected
33
+ */
34
+
35
+ const VALID_ROLES = new Set([
36
+ "planner", "researcher", "architect", "coder", "reviewer", "refactorer",
37
+ "tester", "security", "impeccable", "triage", "discover", "hu_reviewer", "solomon",
38
+ ]);
39
+
40
+ /**
41
+ * Translate triage level → base set of roles. Conservative baseline that the
42
+ * decisor then adjusts via taskType and domain hints.
43
+ */
44
+ function baselineForLevel(level) {
45
+ switch (level) {
46
+ case "trivial": return new Set(["coder"]);
47
+ case "simple": return new Set(["coder", "reviewer"]);
48
+ case "medium": return new Set(["coder", "reviewer", "tester"]);
49
+ case "complex": return new Set(["researcher", "architect", "planner", "coder", "reviewer", "tester", "security"]);
50
+ default: return new Set(["coder", "reviewer"]);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Apply taskType adjustments on top of the baseline set (mutates in place).
56
+ */
57
+ function applyTaskTypeAdjustments(roles, taskType) {
58
+ switch (taskType) {
59
+ case "doc":
60
+ // Documentation tasks: skip testing and security, keep reviewer for tone/clarity.
61
+ roles.delete("tester");
62
+ roles.delete("security");
63
+ roles.delete("refactorer");
64
+ break;
65
+ case "add-tests":
66
+ // Adding tests: tester is primary, security less relevant.
67
+ roles.add("tester");
68
+ roles.delete("security");
69
+ break;
70
+ case "refactor":
71
+ // Refactor: no new behavior; tester verifies nothing broke; reviewer checks structure.
72
+ roles.add("refactorer");
73
+ roles.add("tester");
74
+ break;
75
+ case "infra":
76
+ // Infra: architect helps; security critical.
77
+ roles.add("architect");
78
+ roles.add("security");
79
+ break;
80
+ case "audit":
81
+ // Audit: no coder; reviewer + security.
82
+ roles.delete("coder");
83
+ roles.add("reviewer");
84
+ roles.add("security");
85
+ break;
86
+ case "no-code":
87
+ // No-code tasks (e.g. running SQL queries): drop coder+reviewer+tester.
88
+ roles.delete("coder");
89
+ roles.delete("reviewer");
90
+ roles.delete("tester");
91
+ break;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Apply explicit overrides (CLI flags / config) on top of the decision.
97
+ * force = add; skip = remove. Tracks what was applied.
98
+ *
99
+ * @param {Set<string>} roles
100
+ * @param {{ forceRoles?: string[], skipRoles?: string[] }} overrides
101
+ * @returns {string[]} applied override names
102
+ */
103
+ function applyOverrides(roles, overrides) {
104
+ const applied = [];
105
+ for (const r of overrides.forceRoles || []) {
106
+ if (!VALID_ROLES.has(r)) continue;
107
+ roles.add(r);
108
+ applied.push(`force:${r}`);
109
+ }
110
+ for (const r of overrides.skipRoles || []) {
111
+ if (!VALID_ROLES.has(r)) continue;
112
+ roles.delete(r);
113
+ applied.push(`skip:${r}`);
114
+ }
115
+ return applied;
116
+ }
117
+
118
+ /**
119
+ * Build a routing Decision from triage output + task text + config.
120
+ *
121
+ * @param {Object} args
122
+ * @param {TriageOutput} args.triage
123
+ * @param {string} [args.task]
124
+ * @param {Object} [args.config] - resolved config (for rolesEnabled in pipeline)
125
+ * @param {{ forceRoles?: string[], skipRoles?: string[] }} [args.overrides]
126
+ * @returns {Decision}
127
+ */
128
+ export function buildDecision({ triage, task, config = {}, overrides = {} } = {}) {
129
+ const level = triage?.level || "simple";
130
+ const taskType = triage?.taskType || "sw";
131
+
132
+ // 1. Baseline by complexity.
133
+ const roles = baselineForLevel(level);
134
+
135
+ // 2. Include triage's own suggested roles (triage already factors domain hints).
136
+ if (Array.isArray(triage?.roles)) {
137
+ for (const r of triage.roles) {
138
+ if (VALID_ROLES.has(r)) roles.add(r);
139
+ }
140
+ }
141
+
142
+ // 3. Task-type-specific adjustments.
143
+ applyTaskTypeAdjustments(roles, taskType);
144
+
145
+ // 4. Config pipeline.X.enabled=false forces a role off (respect user config).
146
+ const pipeline = config?.pipeline || {};
147
+ for (const r of Array.from(roles)) {
148
+ if (pipeline[r]?.enabled === false) {
149
+ roles.delete(r);
150
+ }
151
+ }
152
+
153
+ // 5. Manual CLI/flag overrides (highest priority).
154
+ const appliedOverrides = applyOverrides(roles, overrides);
155
+
156
+ // 6. Invariants: coder is always on unless explicitly audit/no-code AND not force-added.
157
+ if (taskType !== "audit" && taskType !== "no-code" && !overrides.skipRoles?.includes("coder")) {
158
+ roles.add("coder");
159
+ }
160
+
161
+ // 7. Confidence + Solomon consultation.
162
+ const explicitConfidence = typeof triage?.confidence === "number" ? triage.confidence : null;
163
+ let confidence = "medium";
164
+ let consultSolomon = false;
165
+ let solomonReason;
166
+ if (explicitConfidence !== null) {
167
+ if (explicitConfidence < 0.6) {
168
+ confidence = "low";
169
+ consultSolomon = true;
170
+ solomonReason = `triage confidence ${explicitConfidence.toFixed(2)} < 0.6`;
171
+ } else if (explicitConfidence >= 0.85) {
172
+ confidence = "high";
173
+ }
174
+ }
175
+ // Ambiguous level (absent or off-vocabulary) → low confidence regardless.
176
+ if (!triage?.level) {
177
+ confidence = "low";
178
+ consultSolomon = true;
179
+ solomonReason = "triage returned no level";
180
+ }
181
+
182
+ const rolesOn = Array.from(roles).sort();
183
+ const rolesOff = Array.from(VALID_ROLES).filter((r) => !roles.has(r)).sort();
184
+
185
+ const rationale = buildRationale({ level, taskType, rolesOn, appliedOverrides, triage });
186
+
187
+ return {
188
+ rolesOn,
189
+ rolesOff,
190
+ confidence,
191
+ rationale,
192
+ consultSolomon,
193
+ solomonReason,
194
+ appliedOverrides,
195
+ };
196
+ }
197
+
198
+ function buildRationale({ level, taskType, rolesOn, appliedOverrides, triage }) {
199
+ const parts = [
200
+ `level=${level}`,
201
+ `taskType=${taskType}`,
202
+ `roles=[${rolesOn.join(",")}]`,
203
+ ];
204
+ if (triage?.domainHints?.length) {
205
+ parts.push(`hints=[${triage.domainHints.slice(0, 3).join(",")}]`);
206
+ }
207
+ if (appliedOverrides.length) {
208
+ parts.push(`overrides=[${appliedOverrides.join(",")}]`);
209
+ }
210
+ return parts.join(" | ");
211
+ }
212
+
213
+ /**
214
+ * Apply a Decision onto an existing pipelineFlags object. Returns a NEW
215
+ * object — the input is not mutated. Setting roleEnabled flags via a
216
+ * consistent naming pattern: `${role}Enabled`.
217
+ *
218
+ * Unknown roles are silently ignored; the orchestrator only consumes a
219
+ * fixed set of *Enabled flags.
220
+ *
221
+ * @param {Decision} decision
222
+ * @param {Object} pipelineFlags
223
+ * @returns {Object} new flags object
224
+ */
225
+ export function applyDecisionToFlags(decision, pipelineFlags = {}) {
226
+ const next = { ...pipelineFlags };
227
+ const flagFor = (role) => {
228
+ if (role === "hu_reviewer") return "huReviewerEnabled";
229
+ return `${role}Enabled`;
230
+ };
231
+ for (const role of decision.rolesOn) {
232
+ next[flagFor(role)] = true;
233
+ }
234
+ for (const role of decision.rolesOff) {
235
+ next[flagFor(role)] = false;
236
+ }
237
+ // Coder/security/reviewer aren't always toggled via flags in the current
238
+ // orchestrator (coder is implicit). Don't touch fields the orchestrator
239
+ // doesn't know; next simply carries them.
240
+ return next;
241
+ }
242
+
243
+ export { VALID_ROLES };
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Brain → Solomon consultation for routing decisions.
3
+ *
4
+ * When the Brain's Decision is low confidence, ambiguous, or the triage+config
5
+ * combination yields conflicting signals, the Brain consults Solomon. Solomon
6
+ * ruling is treated as *advisory*: if it returns a concrete role adjustment
7
+ * (e.g. "add security"), Brain applies it; otherwise Brain keeps the baseline.
8
+ *
9
+ * This is intentionally conservative. A future iteration can make Solomon a
10
+ * binding arbiter for routing (like it is for pipeline-control decisions).
11
+ *
12
+ * Architectural invariant: this module is the ONLY sanctioned path from
13
+ * Brain to Solomon for routing concerns. Stages / rules / agents must not
14
+ * bypass Brain to reach Solomon directly — see the note on `invokeSolomon`
15
+ * in `src/orchestrator/solomon-escalation.js` and docs/ARCHITECTURE.md.
16
+ *
17
+ * @typedef {import("../types/solomon.js").Conflict} Conflict
18
+ * @typedef {import("../types/solomon.js").SolomonResult} SolomonResult
19
+ */
20
+
21
+ /**
22
+ * Build a synthetic conflict payload suitable for invokeSolomon().
23
+ *
24
+ * @param {Object} args
25
+ * @param {import("./decisor.js").Decision} args.decision
26
+ * @param {Object} args.triage
27
+ * @param {string} args.task
28
+ * @returns {Conflict} conflict
29
+ */
30
+ export function buildRoutingConflict({ decision, triage, task }) {
31
+ return {
32
+ task,
33
+ stage: "brain-routing",
34
+ reason: decision.solomonReason || "low-confidence routing decision",
35
+ iterationCount: 0,
36
+ maxIterations: 1,
37
+ history: [],
38
+ summary: `Brain rationale: ${decision.rationale}. Roles on: ${decision.rolesOn.join(", ")}. Confidence: ${decision.confidence}.`,
39
+ // Extra data Solomon's prompt can introspect via conflict.detail
40
+ detail: {
41
+ triageLevel: triage?.level,
42
+ triageTaskType: triage?.taskType,
43
+ triageConfidence: triage?.confidence,
44
+ rolesOn: decision.rolesOn,
45
+ rolesOff: decision.rolesOff,
46
+ reason: decision.solomonReason,
47
+ },
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Invoke Solomon with a routing question and translate its ruling back into
53
+ * adjustments to the Decision's rolesOn/rolesOff lists.
54
+ *
55
+ * If anything goes wrong (Solomon disabled, invocation throws, ruling
56
+ * malformed), the original decision is returned unchanged with a diagnostic
57
+ * appended to its rationale.
58
+ *
59
+ * @param {Object} args
60
+ * @param {import("./decisor.js").Decision} args.decision
61
+ * @param {Object} args.triage
62
+ * @param {string} args.task
63
+ * @param {Object} args.config
64
+ * @param {Object} args.logger
65
+ * @param {Object} [args.emitter]
66
+ * @param {Object} [args.eventBase]
67
+ * @param {Object} [args.session]
68
+ * @param {Function} [args.askQuestion]
69
+ * @returns {Promise<import("./decisor.js").Decision>}
70
+ */
71
+ export async function consultSolomonForRouting({
72
+ decision,
73
+ triage,
74
+ task,
75
+ config,
76
+ logger,
77
+ emitter = null,
78
+ eventBase = {},
79
+ session = {},
80
+ askQuestion = null,
81
+ }) {
82
+ if (!decision?.consultSolomon) return decision;
83
+ // Route through the existing infrastructure.
84
+ let invokeSolomon;
85
+ try {
86
+ ({ invokeSolomon } = await import("../orchestrator/solomon-escalation.js"));
87
+ } catch (err) {
88
+ logger?.warn?.(`brain/solomon-consult: escalation module unavailable (${err.message})`);
89
+ return decision;
90
+ }
91
+
92
+ const conflict = buildRoutingConflict({ decision, triage, task });
93
+
94
+ let ruling;
95
+ try {
96
+ ruling = await invokeSolomon({
97
+ config,
98
+ logger,
99
+ emitter,
100
+ eventBase,
101
+ stage: "brain-routing",
102
+ conflict,
103
+ askQuestion,
104
+ session,
105
+ iteration: 0,
106
+ });
107
+ } catch (err) {
108
+ logger?.warn?.(`brain/solomon-consult: invokeSolomon threw (${err.message}) — keeping baseline`);
109
+ return {
110
+ ...decision,
111
+ rationale: `${decision.rationale} | solomon=failed(${err.message})`,
112
+ };
113
+ }
114
+
115
+ if (!ruling || typeof ruling !== "object") {
116
+ return {
117
+ ...decision,
118
+ rationale: `${decision.rationale} | solomon=no-ruling`,
119
+ };
120
+ }
121
+
122
+ return applyRulingToDecision(decision, ruling, logger);
123
+ }
124
+
125
+ /**
126
+ * Apply a Solomon ruling to a decision. Known ruling fields Solomon may
127
+ * return that we understand in routing context:
128
+ * - action: "approve" / "continue" / "retry_different_approach" / "escalate"
129
+ * - suggestedActions: list of strings that may include "add X" / "remove X"
130
+ * - conditions: list of strings
131
+ *
132
+ * For routing we only look at suggestedActions (text-based) and parse simple
133
+ * "add X" / "skip X" / "remove X" hints against the valid role set. Everything
134
+ * else is logged for the rationale and ignored.
135
+ */
136
+ export function applyRulingToDecision(decision, ruling, logger) {
137
+ const rolesOn = new Set(decision.rolesOn);
138
+ const rolesOff = new Set(decision.rolesOff);
139
+ const applied = [];
140
+
141
+ const suggestions = Array.isArray(ruling.suggestedActions) ? ruling.suggestedActions : [];
142
+ for (const raw of suggestions) {
143
+ const action = String(raw || "").toLowerCase();
144
+ const addMatch = action.match(/\b(?:add|enable|include)\s+(\w+)/);
145
+ const skipMatch = action.match(/\b(?:skip|disable|remove|drop)\s+(\w+)/);
146
+ if (addMatch) {
147
+ const role = addMatch[1];
148
+ rolesOn.add(role);
149
+ rolesOff.delete(role);
150
+ applied.push(`solomon-add:${role}`);
151
+ } else if (skipMatch) {
152
+ const role = skipMatch[1];
153
+ rolesOff.add(role);
154
+ rolesOn.delete(role);
155
+ applied.push(`solomon-skip:${role}`);
156
+ }
157
+ }
158
+
159
+ const ruleVerdict = ruling.action || ruling.verdict || "unknown";
160
+ logger?.info?.(`brain/solomon-consult: Solomon verdict=${ruleVerdict} applied=[${applied.join(",")}]`);
161
+
162
+ return {
163
+ ...decision,
164
+ rolesOn: Array.from(rolesOn).sort(),
165
+ rolesOff: Array.from(rolesOff).sort(),
166
+ appliedOverrides: [...decision.appliedOverrides, ...applied],
167
+ confidence: applied.length > 0 ? "high" : decision.confidence,
168
+ consultSolomon: false,
169
+ rationale: `${decision.rationale} | solomon=${ruleVerdict}${applied.length ? ` applied=${applied.join(",")}` : ""}`,
170
+ };
171
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Compute "With KJ" vs "Without KJ" budget comparison.
3
+ *
4
+ * Karajan reduces token consumption through two mechanisms:
5
+ * 1. RTK proxy compression (token-level output compression via the
6
+ * Rust Token Killer proxy). Tracked as `rtkSavings.estimatedTokensSaved`.
7
+ * 2. Brain role-output compression (summarization/trimming of inter-role
8
+ * outputs). Tracked in `brainCtx.compressionStats.totalSaved`.
9
+ *
10
+ * Given the real billed usage (from BudgetTracker) plus the saved tokens,
11
+ * this helper projects what usage would have been without KJ's compressions.
12
+ *
13
+ * Cost projection uses the blended rate from the real usage:
14
+ * withoutKjCost = realCost * (realTokens + savedTokens) / realTokens
15
+ *
16
+ * When no compression data is available, `hasCompression` is false and the
17
+ * caller should render only the real cost (no comparison).
18
+ */
19
+
20
+ /**
21
+ * @typedef {Object} KjComparison
22
+ * @property {boolean} hasCompression - whether any savings data exists
23
+ * @property {{ tokens: number, cost: number }} withKj
24
+ * @property {{ tokens: number, cost: number }} withoutKj
25
+ * @property {number} savedTokens - total tokens saved
26
+ * @property {number} savedPct - savings as percent of the "without" total (0..100)
27
+ * @property {{ rtkTokens: number, brainTokens: number }} breakdown
28
+ */
29
+
30
+ /**
31
+ * Compute the comparison from the current budget snapshot and available
32
+ * compression stats.
33
+ *
34
+ * @param {Object} args
35
+ * @param {number} [args.realTokens] - budget tracker total tokens
36
+ * @param {number} [args.realCost] - budget tracker cost in USD
37
+ * @param {{ estimatedTokensSaved?: number }} [args.rtkSavings]
38
+ * @param {{ compressionStats?: { totalSaved?: number } } | null} [args.brainCtx]
39
+ * @returns {KjComparison}
40
+ */
41
+ export function computeKjComparison({ realTokens = 0, realCost = 0, rtkSavings = null, brainCtx = null } = {}) {
42
+ const realT = Math.max(0, Number(realTokens) || 0);
43
+ const realC = Math.max(0, Number(realCost) || 0);
44
+
45
+ const rtkTokens = Math.max(0, Number(rtkSavings?.estimatedTokensSaved) || 0);
46
+ const brainTokens = Math.max(0, Number(brainCtx?.compressionStats?.totalSaved) || 0);
47
+ const savedTokens = rtkTokens + brainTokens;
48
+
49
+ if (savedTokens === 0 || realT === 0) {
50
+ return {
51
+ hasCompression: false,
52
+ withKj: { tokens: realT, cost: realC },
53
+ withoutKj: { tokens: realT, cost: realC },
54
+ savedTokens: 0,
55
+ savedPct: 0,
56
+ breakdown: { rtkTokens, brainTokens },
57
+ };
58
+ }
59
+
60
+ const withoutKjTokens = realT + savedTokens;
61
+ const blendedRate = realC / realT;
62
+ const withoutKjCost = Number((blendedRate * withoutKjTokens).toFixed(4));
63
+ const savedPct = Number(((savedTokens / withoutKjTokens) * 100).toFixed(1));
64
+
65
+ return {
66
+ hasCompression: true,
67
+ withKj: { tokens: realT, cost: Number(realC.toFixed(4)) },
68
+ withoutKj: { tokens: withoutKjTokens, cost: withoutKjCost },
69
+ savedTokens,
70
+ savedPct,
71
+ breakdown: { rtkTokens, brainTokens },
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Render a one-line comparison string for the CLI display. Returns null
77
+ * when there's no compression data (so the caller can fall back to the
78
+ * plain budget line).
79
+ *
80
+ * Example outputs:
81
+ * "With KJ: $0.06 / 1,287 tokens · Without KJ: ~$1.30 / ~11,324 tokens (-89%)"
82
+ *
83
+ * @param {KjComparison} cmp
84
+ * @returns {string|null}
85
+ */
86
+ export function formatComparisonLine(cmp) {
87
+ if (!cmp?.hasCompression) return null;
88
+ const fmt = (n) => n.toLocaleString("en-US");
89
+ const tok = (n) => `${fmt(n)} tokens`;
90
+ const cost = (n) => `$${n.toFixed(2)}`;
91
+ return [
92
+ `With KJ: ${cost(cmp.withKj.cost)} / ${tok(cmp.withKj.tokens)}`,
93
+ `Without KJ: ~${cost(cmp.withoutKj.cost)} / ~${tok(cmp.withoutKj.tokens)}`,
94
+ `(-${cmp.savedPct.toFixed(0)}%)`,
95
+ ].join(" · ");
96
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Binary / CLI availability checks.
3
+ *
4
+ * Covers:
5
+ * - Agent CLIs (claude, codex, gemini, aider, opencode)
6
+ * - Core binaries (node, npm, git)
7
+ * - Docker
8
+ * - Serena MCP (optional)
9
+ *
10
+ * All binary checks use `strategy: "manual"` because auto-installing binaries
11
+ * is invasive and platform-specific. Exception: Serena is `"prompt"` (we know
12
+ * the install command and can offer to run it).
13
+ */
14
+
15
+ import { checkBinary, KNOWN_AGENTS } from "../utils/agent-detect.js";
16
+ import { runCommand } from "../utils/process.js";
17
+ import { withDocLink } from "../utils/doc-links.js";
18
+ import { STRATEGY } from "./types.js";
19
+
20
+ /**
21
+ * Check the presence of a named agent CLI (claude/codex/gemini/aider).
22
+ */
23
+ function createAgentCheck(agent) {
24
+ return {
25
+ name: `agent:${agent.name}`,
26
+ label: `Agent: ${agent.name}`,
27
+ strategy: STRATEGY.MANUAL,
28
+ async detect() {
29
+ const result = await checkBinary(agent.name);
30
+ return {
31
+ ok: result.ok,
32
+ severity: "warn", // missing one agent CLI shouldn't block — user may not use it
33
+ detail: result.ok ? `${result.version} (${result.path})` : "Not found",
34
+ fix: result.ok ? undefined : withDocLink(`Install: ${agent.install}`, "agent_not_found"),
35
+ };
36
+ },
37
+ };
38
+ }
39
+
40
+ /**
41
+ * Check the presence of a core binary (node, npm, git).
42
+ */
43
+ function createCoreBinaryCheck(bin) {
44
+ return {
45
+ name: bin,
46
+ label: bin,
47
+ strategy: STRATEGY.MANUAL,
48
+ async detect() {
49
+ const result = await checkBinary(bin);
50
+ return {
51
+ ok: result.ok,
52
+ severity: "fail",
53
+ detail: result.ok ? result.version : "Not found",
54
+ fix: result.ok ? undefined : `Install ${bin} from its official website.`,
55
+ };
56
+ },
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Docker check. Manual strategy (platform-dependent install).
62
+ */
63
+ export function createDockerCheck() {
64
+ return {
65
+ name: "docker",
66
+ label: "Docker",
67
+ strategy: STRATEGY.MANUAL,
68
+ async detect() {
69
+ const docker = await checkBinary("docker", "--version");
70
+ return {
71
+ ok: docker.ok,
72
+ severity: "warn", // only required if Sonar enabled; soft-fail here
73
+ detail: docker.ok ? docker.version : "Not found",
74
+ fix: docker.ok ? undefined : withDocLink("Install Docker: https://docs.docker.com/get-docker/", "sonar_docker"),
75
+ };
76
+ },
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Serena MCP (optional). Prompt strategy: we know how to install it.
82
+ */
83
+ export function createSerenaCheck() {
84
+ return {
85
+ name: "serena",
86
+ label: "Serena MCP",
87
+ strategy: STRATEGY.MANUAL,
88
+ applies: (config) => config.serena?.enabled === true,
89
+ describe: "Install Serena via: uvx --from git+https://github.com/oraios/serena serena",
90
+ async detect() {
91
+ let ok = false;
92
+ try {
93
+ const res = await runCommand("serena", ["--version"]);
94
+ ok = res.exitCode === 0;
95
+ } catch {
96
+ ok = false;
97
+ }
98
+ return {
99
+ ok,
100
+ severity: "warn",
101
+ detail: ok ? "Available" : "Not found (prompts will still include Serena instructions)",
102
+ fix: ok ? undefined : "Install Serena: uvx --from git+https://github.com/oraios/serena serena --help",
103
+ };
104
+ },
105
+ };
106
+ }
107
+
108
+ /**
109
+ * Aggregate: all binary-related checks for the current config.
110
+ * @returns {import("./types.js").Check[]}
111
+ */
112
+ export function getBinaryChecks() {
113
+ const checks = [];
114
+ for (const agent of KNOWN_AGENTS) {
115
+ checks.push(createAgentCheck(agent));
116
+ }
117
+ for (const bin of ["node", "npm", "git"]) {
118
+ checks.push(createCoreBinaryCheck(bin));
119
+ }
120
+ checks.push(createDockerCheck());
121
+ checks.push(createSerenaCheck());
122
+ return checks;
123
+ }