karajan-code 2.5.0 → 2.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 (109) hide show
  1. package/README.md +20 -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 +163 -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 +21 -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/architect-role.js +3 -1
  56. package/src/roles/base-role.js +23 -2
  57. package/src/roles/coder-role.js +3 -1
  58. package/src/roles/security-role.js +12 -0
  59. package/src/roles/tester-role.js +11 -0
  60. package/src/session/journal/decisions-writer.js +200 -0
  61. package/src/session/journal/iteration-logger.js +194 -0
  62. package/src/session/journal/summary-writer.js +176 -0
  63. package/src/session/journal/tree-writer.js +164 -0
  64. package/src/skills/semantic-detector.js +147 -0
  65. package/src/skills/skill-detector.js +186 -8
  66. package/src/skills/skill-loader.js +131 -1
  67. package/src/skills/skills-cache.js +128 -0
  68. package/src/types/agent.js +55 -0
  69. package/src/types/config.js +114 -0
  70. package/src/types/hu.js +47 -0
  71. package/src/types/index.js +34 -0
  72. package/src/types/policy.js +43 -0
  73. package/src/types/session.js +74 -0
  74. package/src/types/stage.js +68 -0
  75. package/src/utils/display/event-handlers.js +389 -0
  76. package/src/utils/display/formatters.js +132 -0
  77. package/src/utils/display/header.js +48 -0
  78. package/src/utils/display/session-summary.js +108 -0
  79. package/src/utils/display/solomon.js +42 -0
  80. package/src/utils/port-check.js +45 -0
  81. package/src/utils/port-occupant.js +95 -0
  82. package/src/utils/provider-env.js +116 -0
  83. package/src/utils/with-timeout.js +42 -0
  84. package/templates/roles/architect/anthropic.md +65 -0
  85. package/templates/roles/architect/default.md +63 -0
  86. package/templates/roles/architect/google.md +52 -0
  87. package/templates/roles/architect/openai.md +51 -0
  88. package/templates/roles/architect/opencode.md +50 -0
  89. package/templates/roles/coder/anthropic.md +72 -0
  90. package/templates/roles/coder/default.md +69 -0
  91. package/templates/roles/coder/google.md +78 -0
  92. package/templates/roles/coder/openai.md +59 -0
  93. package/templates/roles/coder/opencode.md +49 -0
  94. package/templates/roles/planner/anthropic.md +50 -0
  95. package/templates/roles/planner/default.md +48 -0
  96. package/templates/roles/planner/google.md +66 -0
  97. package/templates/roles/planner/openai.md +46 -0
  98. package/templates/roles/planner/opencode.md +53 -0
  99. package/templates/roles/reviewer/anthropic.md +61 -0
  100. package/templates/roles/reviewer/default.md +62 -0
  101. package/templates/roles/reviewer/google.md +63 -0
  102. package/templates/roles/reviewer/openai.md +57 -0
  103. package/templates/roles/reviewer/opencode.md +42 -0
  104. package/templates/roles/solomon/anthropic.md +71 -0
  105. package/templates/roles/solomon/default.md +83 -0
  106. package/templates/roles/solomon/google.md +61 -0
  107. package/templates/roles/solomon/openai.md +53 -0
  108. package/templates/roles/solomon/opencode.md +55 -0
  109. package/src/utils/display.js +0 -669
@@ -0,0 +1,163 @@
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
+
13
+ /**
14
+ * Build a synthetic conflict payload suitable for invokeSolomon().
15
+ *
16
+ * @param {Object} args
17
+ * @param {import("./decisor.js").Decision} args.decision
18
+ * @param {Object} args.triage
19
+ * @param {string} args.task
20
+ * @returns {Object} conflict
21
+ */
22
+ export function buildRoutingConflict({ decision, triage, task }) {
23
+ return {
24
+ task,
25
+ stage: "brain-routing",
26
+ reason: decision.solomonReason || "low-confidence routing decision",
27
+ iterationCount: 0,
28
+ maxIterations: 1,
29
+ history: [],
30
+ summary: `Brain rationale: ${decision.rationale}. Roles on: ${decision.rolesOn.join(", ")}. Confidence: ${decision.confidence}.`,
31
+ // Extra data Solomon's prompt can introspect via conflict.detail
32
+ detail: {
33
+ triageLevel: triage?.level,
34
+ triageTaskType: triage?.taskType,
35
+ triageConfidence: triage?.confidence,
36
+ rolesOn: decision.rolesOn,
37
+ rolesOff: decision.rolesOff,
38
+ reason: decision.solomonReason,
39
+ },
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Invoke Solomon with a routing question and translate its ruling back into
45
+ * adjustments to the Decision's rolesOn/rolesOff lists.
46
+ *
47
+ * If anything goes wrong (Solomon disabled, invocation throws, ruling
48
+ * malformed), the original decision is returned unchanged with a diagnostic
49
+ * appended to its rationale.
50
+ *
51
+ * @param {Object} args
52
+ * @param {import("./decisor.js").Decision} args.decision
53
+ * @param {Object} args.triage
54
+ * @param {string} args.task
55
+ * @param {Object} args.config
56
+ * @param {Object} args.logger
57
+ * @param {Object} [args.emitter]
58
+ * @param {Object} [args.eventBase]
59
+ * @param {Object} [args.session]
60
+ * @param {Function} [args.askQuestion]
61
+ * @returns {Promise<import("./decisor.js").Decision>}
62
+ */
63
+ export async function consultSolomonForRouting({
64
+ decision,
65
+ triage,
66
+ task,
67
+ config,
68
+ logger,
69
+ emitter = null,
70
+ eventBase = {},
71
+ session = {},
72
+ askQuestion = null,
73
+ }) {
74
+ if (!decision?.consultSolomon) return decision;
75
+ // Route through the existing infrastructure.
76
+ let invokeSolomon;
77
+ try {
78
+ ({ invokeSolomon } = await import("../orchestrator/solomon-escalation.js"));
79
+ } catch (err) {
80
+ logger?.warn?.(`brain/solomon-consult: escalation module unavailable (${err.message})`);
81
+ return decision;
82
+ }
83
+
84
+ const conflict = buildRoutingConflict({ decision, triage, task });
85
+
86
+ let ruling;
87
+ try {
88
+ ruling = await invokeSolomon({
89
+ config,
90
+ logger,
91
+ emitter,
92
+ eventBase,
93
+ stage: "brain-routing",
94
+ conflict,
95
+ askQuestion,
96
+ session,
97
+ iteration: 0,
98
+ });
99
+ } catch (err) {
100
+ logger?.warn?.(`brain/solomon-consult: invokeSolomon threw (${err.message}) — keeping baseline`);
101
+ return {
102
+ ...decision,
103
+ rationale: `${decision.rationale} | solomon=failed(${err.message})`,
104
+ };
105
+ }
106
+
107
+ if (!ruling || typeof ruling !== "object") {
108
+ return {
109
+ ...decision,
110
+ rationale: `${decision.rationale} | solomon=no-ruling`,
111
+ };
112
+ }
113
+
114
+ return applyRulingToDecision(decision, ruling, logger);
115
+ }
116
+
117
+ /**
118
+ * Apply a Solomon ruling to a decision. Known ruling fields Solomon may
119
+ * return that we understand in routing context:
120
+ * - action: "approve" / "continue" / "retry_different_approach" / "escalate"
121
+ * - suggestedActions: list of strings that may include "add X" / "remove X"
122
+ * - conditions: list of strings
123
+ *
124
+ * For routing we only look at suggestedActions (text-based) and parse simple
125
+ * "add X" / "skip X" / "remove X" hints against the valid role set. Everything
126
+ * else is logged for the rationale and ignored.
127
+ */
128
+ export function applyRulingToDecision(decision, ruling, logger) {
129
+ const rolesOn = new Set(decision.rolesOn);
130
+ const rolesOff = new Set(decision.rolesOff);
131
+ const applied = [];
132
+
133
+ const suggestions = Array.isArray(ruling.suggestedActions) ? ruling.suggestedActions : [];
134
+ for (const raw of suggestions) {
135
+ const action = String(raw || "").toLowerCase();
136
+ const addMatch = action.match(/\b(?:add|enable|include)\s+(\w+)/);
137
+ const skipMatch = action.match(/\b(?:skip|disable|remove|drop)\s+(\w+)/);
138
+ if (addMatch) {
139
+ const role = addMatch[1];
140
+ rolesOn.add(role);
141
+ rolesOff.delete(role);
142
+ applied.push(`solomon-add:${role}`);
143
+ } else if (skipMatch) {
144
+ const role = skipMatch[1];
145
+ rolesOff.add(role);
146
+ rolesOn.delete(role);
147
+ applied.push(`solomon-skip:${role}`);
148
+ }
149
+ }
150
+
151
+ const ruleVerdict = ruling.action || ruling.verdict || "unknown";
152
+ logger?.info?.(`brain/solomon-consult: Solomon verdict=${ruleVerdict} applied=[${applied.join(",")}]`);
153
+
154
+ return {
155
+ ...decision,
156
+ rolesOn: Array.from(rolesOn).sort(),
157
+ rolesOff: Array.from(rolesOff).sort(),
158
+ appliedOverrides: [...decision.appliedOverrides, ...applied],
159
+ confidence: applied.length > 0 ? "high" : decision.confidence,
160
+ consultSolomon: false,
161
+ rationale: `${decision.rationale} | solomon=${ruleVerdict}${applied.length ? ` applied=${applied.join(",")}` : ""}`,
162
+ };
163
+ }
@@ -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
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * CI infrastructure checks: required workflows, gh CLI, and GitHub secrets.
3
+ * Only applies when `config.ci.enabled === true`.
4
+ */
5
+
6
+ import path from "node:path";
7
+ import { exists } from "../utils/fs.js";
8
+ import { runCommand } from "../utils/process.js";
9
+ import { checkBinary } from "../utils/agent-detect.js";
10
+ import { STRATEGY } from "./types.js";
11
+
12
+ const REQUIRED_WORKFLOWS = ["kj-ci-gateway.yml", "automerge.yml", "houston-override.yml"];
13
+
14
+ function ciEnabled(config) {
15
+ return config.ci?.enabled === true;
16
+ }
17
+
18
+ function createWorkflowCheck(workflow) {
19
+ return {
20
+ name: `ci:workflow:${workflow}`,
21
+ label: `CI workflow: ${workflow}`,
22
+ strategy: STRATEGY.MANUAL,
23
+ applies: ciEnabled,
24
+ async detect({ config }) {
25
+ const projectDir = config.projectDir || process.cwd();
26
+ const wfPath = path.join(projectDir, ".github", "workflows", workflow);
27
+ const wfExists = await exists(wfPath);
28
+ return {
29
+ ok: wfExists,
30
+ severity: "fail",
31
+ detail: wfExists ? "Found" : "Not found",
32
+ fix: wfExists
33
+ ? undefined
34
+ : `Run 'kj init --scaffold-ci' or copy from karajan-code/templates/workflows/${workflow}`,
35
+ };
36
+ },
37
+ };
38
+ }
39
+
40
+ export function createGhCliCheck() {
41
+ return {
42
+ name: "ci:gh",
43
+ label: "CI: gh CLI",
44
+ strategy: STRATEGY.MANUAL,
45
+ applies: ciEnabled,
46
+ async detect() {
47
+ const gh = await checkBinary("gh");
48
+ return {
49
+ ok: gh.ok,
50
+ severity: "fail",
51
+ detail: gh.ok ? gh.version : "Not found",
52
+ fix: gh.ok ? undefined : "Install GitHub CLI: https://cli.github.com/",
53
+ };
54
+ },
55
+ };
56
+ }
57
+
58
+ export function createGhSecretsCheck() {
59
+ return {
60
+ name: "ci:secrets",
61
+ label: "CI: GitHub secrets",
62
+ strategy: STRATEGY.MANUAL,
63
+ applies: ciEnabled,
64
+ async detect() {
65
+ try {
66
+ const { detectRepo } = await import("../ci/repo.js");
67
+ const repo = await detectRepo();
68
+ if (!repo) {
69
+ return { ok: true, severity: "info", detail: "No GitHub repo detected (skipped)" };
70
+ }
71
+ const res = await runCommand("gh", ["api", `repos/${repo}/actions/secrets`, "--jq", ".secrets[].name"]);
72
+ if (res.exitCode !== 0) {
73
+ return { ok: true, severity: "info", detail: "Cannot query secrets (gh unauthenticated?)" };
74
+ }
75
+ const names = new Set(res.stdout.split("\n").map((s) => s.trim()));
76
+ const hasAppId = names.has("KJ_CI_APP_ID");
77
+ const hasKey = names.has("KJ_CI_PRIVATE_KEY");
78
+ const secretsOk = hasAppId && hasKey;
79
+ const missing = [!hasAppId && "KJ_CI_APP_ID", !hasKey && "KJ_CI_PRIVATE_KEY"].filter(Boolean).join(" ");
80
+ return {
81
+ ok: secretsOk,
82
+ severity: "fail",
83
+ detail: secretsOk ? "KJ_CI_APP_ID + KJ_CI_PRIVATE_KEY found" : `Missing: ${missing}`,
84
+ fix: secretsOk ? undefined : "Add KJ_CI_APP_ID and KJ_CI_PRIVATE_KEY as GitHub repository secrets",
85
+ };
86
+ } catch {
87
+ return { ok: true, severity: "info", detail: "Cannot check secrets (unexpected error, skipped)" };
88
+ }
89
+ },
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Aggregate of CI checks. Each check carries its own `applies` so the runner
95
+ * marks them SKIPPED when CI is disabled.
96
+ */
97
+ export function getCiChecks() {
98
+ const checks = [];
99
+ for (const wf of REQUIRED_WORKFLOWS) {
100
+ checks.push(createWorkflowCheck(wf));
101
+ }
102
+ checks.push(createGhCliCheck());
103
+ checks.push(createGhSecretsCheck());
104
+ return checks;
105
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Config and rule-file checks.
3
+ *
4
+ * Covers:
5
+ * - kj.config.yml existence (strategy: prompt — offer to run kj init)
6
+ * - Review / coder rules discovery (strategy: none, informational)
7
+ * - Agent config files: ~/.claude.json, ~/.codex/config.toml,
8
+ * ~/.karajan/kj.config.yml (strategy: manual — structural fixes needed)
9
+ */
10
+
11
+ import fs from "node:fs/promises";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { exists } from "../utils/fs.js";
15
+ import { getConfigPath } from "../config.js";
16
+ import { resolveRoleMdPath, loadFirstExisting } from "../roles/base-role.js";
17
+ import { withDocLink } from "../utils/doc-links.js";
18
+ import { STRATEGY } from "./types.js";
19
+
20
+ /**
21
+ * kj.config.yml presence check.
22
+ */
23
+ export function createConfigFileCheck() {
24
+ return {
25
+ name: "config",
26
+ label: "Config file",
27
+ strategy: STRATEGY.PROMPT,
28
+ describe: "Run 'kj init' to scaffold a default kj.config.yml",
29
+ async detect() {
30
+ const configPath = getConfigPath();
31
+ const configExists = await exists(configPath);
32
+ return {
33
+ ok: configExists,
34
+ severity: "fail",
35
+ detail: configExists ? configPath : "Not found",
36
+ fix: configExists ? undefined : withDocLink("Run 'kj init' to create the config file.", "config_missing"),
37
+ };
38
+ },
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Review rules (.md) informational check.
44
+ */
45
+ export function createReviewRulesCheck() {
46
+ return {
47
+ name: "review-rules",
48
+ label: "Reviewer rules (.md)",
49
+ strategy: STRATEGY.NONE,
50
+ async detect({ config }) {
51
+ const projectDir = config.projectDir || process.cwd();
52
+ const paths = resolveRoleMdPath("reviewer", projectDir);
53
+ const rules = await loadFirstExisting(paths);
54
+ return {
55
+ ok: true,
56
+ severity: "info",
57
+ detail: rules ? "Found" : "Not found (will use defaults)",
58
+ };
59
+ },
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Coder rules (.md) informational check.
65
+ */
66
+ export function createCoderRulesCheck() {
67
+ return {
68
+ name: "coder-rules",
69
+ label: "Coder rules (.md)",
70
+ strategy: STRATEGY.NONE,
71
+ async detect({ config }) {
72
+ const projectDir = config.projectDir || process.cwd();
73
+ const paths = resolveRoleMdPath("coder", projectDir);
74
+ const rules = await loadFirstExisting(paths);
75
+ return {
76
+ ok: true,
77
+ severity: "info",
78
+ detail: rules ? "Found" : "Not found (will use defaults)",
79
+ };
80
+ },
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Detect duplicate TOML table headers (e.g. [mcp_servers."karajan-mcp"] twice).
86
+ */
87
+ function findDuplicateTomlKeys(content) {
88
+ const tableHeaders = [];
89
+ const duplicates = [];
90
+ for (const line of content.split("\n")) {
91
+ const match = line.match(/^\s*\[([^\]]+)\]\s*$/);
92
+ if (match) {
93
+ const key = match[1].trim();
94
+ if (tableHeaders.includes(key)) {
95
+ duplicates.push(key);
96
+ } else {
97
+ tableHeaders.push(key);
98
+ }
99
+ }
100
+ }
101
+ return duplicates;
102
+ }
103
+
104
+ /**
105
+ * Claude config (~/.claude.json) validity.
106
+ */
107
+ export function createClaudeConfigCheck() {
108
+ return {
109
+ name: "agent-config:claude",
110
+ label: "Agent config: claude (~/.claude.json)",
111
+ strategy: STRATEGY.MANUAL,
112
+ async detect() {
113
+ const home = os.homedir();
114
+ const claudeJsonPath = path.join(home, ".claude.json");
115
+ try {
116
+ const raw = await fs.readFile(claudeJsonPath, "utf8");
117
+ JSON.parse(raw);
118
+ return { ok: true, severity: "info", detail: "Valid JSON" };
119
+ } catch (err) {
120
+ if (err.code === "ENOENT") {
121
+ // Not configured: Claude may not be in use. Informational skip.
122
+ return { ok: true, severity: "info", detail: "Not present (skipped)" };
123
+ }
124
+ return {
125
+ ok: false,
126
+ severity: "warn",
127
+ detail: `Invalid JSON: ${err.message.split("\n")[0]}`,
128
+ fix: "Fix the JSON syntax in ~/.claude.json. Common issues: trailing commas, missing quotes.",
129
+ };
130
+ }
131
+ },
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Codex config (~/.codex/config.toml) validity.
137
+ */
138
+ export function createCodexConfigCheck() {
139
+ return {
140
+ name: "agent-config:codex",
141
+ label: "Agent config: codex (~/.codex/config.toml)",
142
+ strategy: STRATEGY.MANUAL,
143
+ async detect() {
144
+ const home = os.homedir();
145
+ const codexTomlPath = path.join(home, ".codex", "config.toml");
146
+ try {
147
+ const raw = await fs.readFile(codexTomlPath, "utf8");
148
+ const duplicates = findDuplicateTomlKeys(raw);
149
+ if (duplicates.length > 0) {
150
+ return {
151
+ ok: false,
152
+ severity: "warn",
153
+ detail: `Duplicate TOML keys: ${duplicates.join(", ")}`,
154
+ fix: `Remove duplicate entries in ~/.codex/config.toml: ${duplicates.join(", ")}`,
155
+ };
156
+ }
157
+ return { ok: true, severity: "info", detail: "Valid TOML (no duplicate keys)" };
158
+ } catch (err) {
159
+ if (err.code === "ENOENT") {
160
+ return { ok: true, severity: "info", detail: "Not present (skipped)" };
161
+ }
162
+ return {
163
+ ok: false,
164
+ severity: "warn",
165
+ detail: `Cannot read: ${err.message.split("\n")[0]}`,
166
+ fix: "Check file permissions on ~/.codex/config.toml",
167
+ };
168
+ }
169
+ },
170
+ };
171
+ }
172
+
173
+ /**
174
+ * KJ config (~/.karajan/kj.config.yml) YAML validity (separate from existence).
175
+ */
176
+ export function createKjConfigYamlCheck() {
177
+ return {
178
+ name: "agent-config:karajan",
179
+ label: "Agent config: karajan (kj.config.yml)",
180
+ strategy: STRATEGY.MANUAL,
181
+ async detect() {
182
+ const kjConfigPath = getConfigPath();
183
+ try {
184
+ const raw = await fs.readFile(kjConfigPath, "utf8");
185
+ const yaml = await import("js-yaml");
186
+ yaml.default.load(raw);
187
+ return { ok: true, severity: "info", detail: "Valid YAML" };
188
+ } catch (err) {
189
+ if (err.code === "ENOENT") {
190
+ // Covered by createConfigFileCheck — don't duplicate the failure
191
+ return { ok: true, severity: "info", detail: "Not present (covered by config check)" };
192
+ }
193
+ return {
194
+ ok: false,
195
+ severity: "fail",
196
+ detail: `Invalid YAML: ${err.message.split("\n")[0]}`,
197
+ fix: `Fix YAML syntax in ${kjConfigPath}. Run 'kj init' to regenerate if needed.`,
198
+ };
199
+ }
200
+ },
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Aggregate: all config-file-related checks.
206
+ * @returns {import("./types.js").Check[]}
207
+ */
208
+ export function getConfigFileChecks() {
209
+ return [
210
+ createConfigFileCheck(),
211
+ createReviewRulesCheck(),
212
+ createCoderRulesCheck(),
213
+ createClaudeConfigCheck(),
214
+ createCodexConfigCheck(),
215
+ createKjConfigYamlCheck(),
216
+ ];
217
+ }