karajan-code 3.4.0 → 3.4.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 (52) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/packages/hu-board/src/routes/api.js +70 -49
  4. package/packages/hu-board/src/zombie-reaper.js +1 -1
  5. package/src/agents/aider-agent.js +1 -1
  6. package/src/agents/gemini-agent.js +1 -1
  7. package/src/agents/opencode-agent.js +1 -1
  8. package/src/audit/agent-readiness.js +2 -1
  9. package/src/audit/deterministic-summary.js +11 -5
  10. package/src/audit/issue-filter.js +3 -6
  11. package/src/audit/plan-adherence.js +3 -1
  12. package/src/audit/semgrep-findings.js +5 -1
  13. package/src/brain/agent-error-classifier.js +8 -1
  14. package/src/brain/decisor.js +2 -2
  15. package/src/brain/solomon-consult.js +2 -2
  16. package/src/brain/standby-scheduler.js +0 -2
  17. package/src/commands/audit.js +8 -3
  18. package/src/commands/board.js +1 -1
  19. package/src/commands/standby.js +4 -1
  20. package/src/config/loader.js +2 -2
  21. package/src/golden/asserter.js +3 -1
  22. package/src/golden/schema.js +1 -1
  23. package/src/hu/auto-generator.js +1 -1
  24. package/src/lang/tree-sitter-loader.js +1 -5
  25. package/src/mcp/handlers/management-handlers.js +4 -3
  26. package/src/orchestrator/drivers/post-loop.js +43 -91
  27. package/src/orchestrator/flow-runner.js +25 -0
  28. package/src/orchestrator/fs-leak-detector.js +6 -1
  29. package/src/orchestrator/preflight-checks.js +51 -0
  30. package/src/orchestrator/solomon-rules.js +12 -1
  31. package/src/prompts/audit.js +12 -11
  32. package/src/prompts/hu-reviewer.js +1 -1
  33. package/src/prompts/planner.js +1 -1
  34. package/src/rag/embedders/factory.js +0 -1
  35. package/src/rag/retriever.js +1 -1
  36. package/src/roles/agent-role.js +1 -1
  37. package/src/roles/audit-role.js +10 -2
  38. package/src/session/journal/write-all.js +89 -0
  39. package/src/sonar/discovery.js +2 -1
  40. package/src/sonar/scanner.js +1 -1
  41. package/src/utils/cli-progress.js +4 -2
  42. package/src/utils/escape-regexp.js +15 -0
  43. package/src/utils/paths.js +0 -1
  44. package/src/utils/port-occupant.js +2 -1
  45. package/src/utils/project-detect.js +1 -1
  46. package/node_modules/better-sqlite3/build/Release/better_sqlite3.node +0 -0
  47. package/node_modules/deep-extend/CHANGELOG.md +0 -46
  48. package/node_modules/sqlite-vec/index.cjs +0 -46
  49. package/node_modules/sqlite-vec/index.d.ts +0 -17
  50. package/node_modules/sqlite-vec/index.mjs +0 -47
  51. package/node_modules/sqlite-vec-linux-x64/vec0.so +0 -0
  52. package/node_modules/which/CHANGELOG.md +0 -166
@@ -10,12 +10,14 @@
10
10
  * allowed_loc_range need filesystem access — PR-3a wires those.
11
11
  */
12
12
 
13
+ import { escapeRegExp } from "../utils/escape-regexp.js";
14
+
13
15
  const COMMIT_LINE = /^- `([^`]+)`\s+(.*)$/;
14
16
  const SCORE_LINE = /^\*\*Score\*\*:\s*(\d+)\s*\/\s*100/m;
15
17
  const AUDIT_ROW = /^\|\s*`audit`\s*\|\s*([^|]+?)\s*\|/m;
16
18
 
17
19
  function extractSection(content, heading) {
18
- const re = new RegExp(`^## ${heading}\\s*$([\\s\\S]*?)(?=^## |\\Z)`, "m");
20
+ const re = new RegExp(`^## ${escapeRegExp(heading)}\\s*$([\\s\\S]*?)(?=^## |\\Z)`, "m");
19
21
  const m = content.match(re);
20
22
  return m ? m[1].trim() : "";
21
23
  }
@@ -12,7 +12,7 @@ const NonNegInt = v.pipe(v.number(), v.integer(), v.minValue(0));
12
12
  const LocRangeSchema = v.pipe(v.array(NonNegInt), v.length(2),
13
13
  v.check((arr) => arr[0] <= arr[1], "allowed_loc_range: min must be <= max"));
14
14
 
15
- export const GoldenTaskSchema = v.looseObject({
15
+ const GoldenTaskSchema = v.looseObject({
16
16
  id: v.pipe(NonEmptyString, v.regex(/^[a-z0-9_-]+$/, "id must be lowercase a-z0-9_-")),
17
17
  title: NonEmptyString,
18
18
  prompt: NonEmptyString,
@@ -106,7 +106,7 @@ function filterConflictingHints(hints) {
106
106
  * @param {string[]} hints
107
107
  * @returns {"python"|"go"|"rust"|"javascript"}
108
108
  */
109
- export function resolveLanguageFromHints(hints) {
109
+ function resolveLanguageFromHints(hints) {
110
110
  if (!hints || hints.length === 0) return "javascript";
111
111
  if (hints.some((h) => HINT_PYTHON.has(h))) return "python";
112
112
  if (hints.some((h) => HINT_GO.has(h))) return "go";
@@ -24,7 +24,7 @@ async function initRuntime() {
24
24
  return runtimePromise;
25
25
  }
26
26
 
27
- export function grammarPath(id) {
27
+ function grammarPath(id) {
28
28
  return resolve(GRAMMAR_DIR, `${id}.wasm`);
29
29
  }
30
30
 
@@ -43,7 +43,3 @@ export function getLoaded(id) {
43
43
  return cache.get(id) || null;
44
44
  }
45
45
 
46
- export function resetForTests() {
47
- cache.clear();
48
- runtimePromise = null;
49
- }
@@ -16,6 +16,7 @@ import {
16
16
  } from "../shared-helpers.js";
17
17
  import { buildDashboardJson } from "../../utils/status-dashboard.js";
18
18
  import { loadMostRecentSession } from "../../session/store.js";
19
+ import { escapeRegExp } from "../../utils/escape-regexp.js";
19
20
 
20
21
  const AGENT_ROLES = new Set(["coder", "reviewer", "tester", "security", "solomon"]);
21
22
 
@@ -72,9 +73,9 @@ export async function handleAgents(a) {
72
73
  function parseHumanResponseOverrides(humanResponse, overrides) {
73
74
  for (const role of AGENT_ROLES) {
74
75
  const patterns = [
75
- new RegExp(String.raw`use\s+(\w+)\s+(?:as|for)\s+${role}`, "i"),
76
- new RegExp(String.raw`${role}\s*[:=]\s*(\w+)`, "i"),
77
- new RegExp(String.raw`set\s+${role}\s+(?:to|=)\s*(\w+)`, "i")
76
+ new RegExp(String.raw`use\s+(\w+)\s+(?:as|for)\s+${escapeRegExp(role)}`, "i"),
77
+ new RegExp(String.raw`${escapeRegExp(role)}\s*[:=]\s*(\w+)`, "i"),
78
+ new RegExp(String.raw`set\s+${escapeRegExp(role)}\s+(?:to|=)\s*(\w+)`, "i")
78
79
  ];
79
80
  for (const pat of patterns) {
80
81
  const m = pat.exec(humanResponse);
@@ -34,7 +34,6 @@ import { emitProgress, makeEvent } from "../../utils/events.js";
34
34
  import { runTesterStage, runSecurityStage, runFinalAuditStage } from "../post-loop-stages.js";
35
35
  import { invokeSolomon } from "../solomon-escalation.js";
36
36
  import { tryCiComment } from "../ci-integration.js";
37
- import { writeIterationsJournal } from "../session-journal.js";
38
37
  import { getIntegration } from "../integrations.js";
39
38
 
40
39
  export async function handlePostLoopStages({ config, session, emitter, eventBase, coderRole, trackBudget, i, task, stageResults, ciEnabled: _ciEnabled, testerEnabled, securityEnabled, askQuestion, logger, brainCtx }) {
@@ -129,103 +128,56 @@ export async function finalizeApprovedSession({ config, gitCtx, task, logger, se
129
128
  if (rtkSavings) setRtkSavings(session, rtkSavings);
130
129
  await saveSession(session);
131
130
 
132
- // --- Journal: write final files ---
131
+ // --- Journal: write final files (shared writer, KJC-BUG-0084) ---
133
132
  const journalDir = session._journalDir;
134
133
  if (journalDir) {
134
+ // 2026-05-07 dogfooding: gitResult.commits only carries the post-loop
135
+ // commit (scaffold). Compute the full range from session_start_sha so
136
+ // every commit the run produced shows up in execution order.
137
+ let allCommits;
138
+ try { allCommits = (await listCommitsBetween(session.head_at_start || session.session_start_sha)) || []; }
139
+ catch { allCommits = gitResult?.commits || []; }
140
+ const summaryCommits = allCommits.length > 0 ? allCommits : (gitResult?.commits || []);
141
+
142
+ // KJC-TSK-0376 — plan adherence metric (deepeval-inspired). When the
143
+ // run executed against a known plan (`kj run --plan <id>`), score how
144
+ // faithfully the coder followed it. Pure offline; safe-by-default
145
+ // (try/catch swallows missing helper or unreadable plan).
146
+ let planAdherence = null;
135
147
  try {
136
- await writeIterationsJournal(journalDir, session._journalIterations || []);
137
- // decisions.md: writes only when Solomon was invoked (AC of KJC-TSK-0287).
138
- // Pulls structured data from session.solomonRulings + session.brainDecisions.
139
- const { writeDecisionsJournal: writeDecisionsJournalV2 } =
140
- await import("../../session/journal/decisions-writer.js");
141
- const decisionsResult = await writeDecisionsJournalV2(session, { journalDir, logger });
142
- // KJC-TSK-0288: use the new tree-writer with directory grouping
143
- const { writeTreeJournal: writeTreeJournalV2 } =
144
- await import("../../session/journal/tree-writer.js");
145
- const treeResult = await writeTreeJournalV2(journalDir, session.session_start_sha, { logger });
146
-
147
- const journalFiles = [...(session._journalFiles || [])];
148
- if (session._journalIterations?.length) journalFiles.push("iterations.md");
149
- if (decisionsResult.written) journalFiles.push("decisions.md");
150
- if (treeResult.written) journalFiles.push("tree.txt");
151
-
152
- // KJC-TSK-0289: use the richer summary writer (stages table, budget
153
- // breakdown, brain/solomon counts, typed links to other journal files).
154
- const { writeSummaryJournal: writeSummaryJournalV2 } =
155
- await import("../../session/journal/summary-writer.js");
156
- const startedAt = session._startedAt ? new Date(session._startedAt).toISOString() : undefined;
157
- // 2026-05-07 dogfooding: gitResult.commits only carries the post-loop
158
- // commit (scaffold), not the coder's own commit. The summary's
159
- // "Commits" section was therefore misleading — it claimed the run
160
- // produced one chore commit when in fact the coder had also written
161
- // a docs/feat commit. Compute the full range from session_start_sha
162
- // so every commit between then and HEAD shows up in execution order.
163
- // try/catch (instead of `.catch(...)`) so we tolerate both promise
164
- // rejection AND a sync return of undefined — the latter happens
165
- // when a test mocks listCommitsBetween with a plain vi.fn() that
166
- // resetAllMocks has stripped of its mockResolvedValue.
167
- let allCommits = [];
168
- try { allCommits = (await listCommitsBetween(session.head_at_start || session.session_start_sha)) || []; }
169
- catch { allCommits = gitResult?.commits || []; }
170
- const summaryCommits = allCommits.length > 0 ? allCommits : (gitResult?.commits || []);
171
-
172
- // KJC-TSK-0376 — plan adherence metric (deepeval-inspired). When the
173
- // run executed against a known plan (`kj run --plan <id>`), score how
174
- // faithfully the coder followed it. Pure offline; safe-by-default
175
- // (try/catch swallows missing helper or unreadable plan).
176
- let planAdherence = null;
177
- try {
178
- const planId = session._planRef?.planId
179
- || stageResults?.huReviewer?.planId
180
- || null;
181
- if (planId) {
182
- const projectDir = config?.projectDir
183
- || session.config_snapshot?.projectDir
184
- || process.cwd();
185
- const plan = await loadPlan(projectDir, planId).catch(() => null);
186
- if (plan && Array.isArray(plan.hus) && plan.hus.length > 0) {
187
- const filesChanged = await listFilesChangedSince(
188
- session.head_at_start || session.session_start_sha,
189
- ).catch(() => []);
190
- planAdherence = computePlanAdherenceScore({
191
- commits: summaryCommits,
192
- plan,
193
- filesChanged,
194
- });
195
- }
148
+ const planId = session._planRef?.planId
149
+ || stageResults?.huReviewer?.planId
150
+ || null;
151
+ if (planId) {
152
+ const projectDir = config?.projectDir
153
+ || session.config_snapshot?.projectDir
154
+ || process.cwd();
155
+ const plan = await loadPlan(projectDir, planId).catch(() => null);
156
+ if (plan && Array.isArray(plan.hus) && plan.hus.length > 0) {
157
+ const filesChanged = await listFilesChangedSince(
158
+ session.head_at_start || session.session_start_sha,
159
+ ).catch(() => []);
160
+ planAdherence = computePlanAdherenceScore({
161
+ commits: summaryCommits,
162
+ plan,
163
+ filesChanged,
164
+ });
196
165
  }
197
- } catch (err) {
198
- logger?.warn?.(`Plan adherence calculation skipped: ${err.message}`);
199
166
  }
200
-
201
- await writeSummaryJournalV2(journalDir, {
202
- task: session.task,
203
- result: "APPROVED",
204
- sessionId: session.id,
205
- iterations: i,
206
- durationMs: Date.now() - (session._startedAt || Date.now()),
207
- budget: budgetSummary(),
208
- stages: stageResults,
209
- commits: summaryCommits,
210
- files: journalFiles,
211
- startedAt,
212
- finishedAt: new Date().toISOString(),
213
- brainDecisions: Array.isArray(session.brainDecisions) ? session.brainDecisions.length : 0,
214
- solomonInvocations: Array.isArray(session.solomonRulings) ? session.solomonRulings.length : 0,
215
- // KJC-TSK-0327: surface skill-source decisions in the summary so the
216
- // post-mortem shows which process skills (addyosmani) and stack skills
217
- // (OpenSkills) actually shaped the role prompts.
218
- skills: {
219
- addyosmani: session.addyosmaniSkills,
220
- installed: session.autoInstalledSkills,
221
- recommended: session.skillsRecommended,
222
- },
223
- planAdherence,
224
- }, { logger });
225
- logger.info(`Session journal written to ${journalDir}`);
226
167
  } catch (err) {
227
- logger.warn(`Journal write failed (non-blocking): ${err.message}`);
168
+ logger?.warn?.(`Plan adherence calculation skipped: ${err.message}`);
228
169
  }
170
+
171
+ const { writeSessionJournal } = await import("../../session/journal/write-all.js");
172
+ await writeSessionJournal({
173
+ session, logger,
174
+ result: "APPROVED",
175
+ iterations: i,
176
+ budget: budgetSummary(),
177
+ stages: stageResults,
178
+ commits: summaryCommits,
179
+ planAdherence,
180
+ });
229
181
  }
230
182
 
231
183
  // Mirror the same enriched commit list into the session:end event so the
@@ -247,6 +247,31 @@ async function _runFlowInner({ task, config, logger, flags = {}, emitter = null,
247
247
  await sealSessionStatusIfStillRunning(ctx.session, result);
248
248
  return result;
249
249
  } finally {
250
+ // --- Journal: best-effort write for non-approved endings (KJC-BUG-0084) ---
251
+ // finalizeApprovedSession writes the journal on the happy path and sets
252
+ // session._journalWritten. Every other terminal ending (sonar_repeat
253
+ // stall, stage_error, thrown stage, budget exceeded) used to leave only
254
+ // triage.md behind — losing the Cache hits table, budget breakdown and
255
+ // commits exactly on the runs where the post-mortem matters most.
256
+ // Paused sessions are skipped: they resume later and the eventual
257
+ // finalize overwrites the journal with the real outcome.
258
+ try {
259
+ const s = ctx.session;
260
+ if (s && s._journalDir && !s._journalWritten && s.status !== "paused") {
261
+ const { writeSessionJournal } = await import("../session/journal/write-all.js");
262
+ const badge = s.status && s.status !== "running" ? s.status.toUpperCase() : "FAILED";
263
+ await writeSessionJournal({
264
+ session: s, logger,
265
+ result: badge,
266
+ iterations: s._journalIterations?.length || 0,
267
+ budget: typeof ctx.budgetSummary === "function" ? ctx.budgetSummary() : null,
268
+ stages: ctx.stageResults || {},
269
+ });
270
+ }
271
+ } catch (err) {
272
+ logger.warn(`Final journal write failed (non-blocking): ${err.message}`);
273
+ }
274
+
250
275
  // --- Cleanup auto-installed skills ---
251
276
  const autoSkills = ctx.session?.autoInstalledSkills;
252
277
  if (autoSkills && autoSkills.length > 0) {
@@ -156,11 +156,16 @@ export function detectTranscriptCdLeaks(transcript, projectDir) {
156
156
  const projectDirAbs = projectDir ? path.resolve(projectDir) : null;
157
157
  const homeDir = os.homedir();
158
158
  // Capture cd target + the next ~200 chars of the same line for write-cmd lookup.
159
- const cdRegex = /\bcd\s+(~\/[^\s&|;`'"\n]+|\$HOME\/[^\s&|;`'"\n]+|\/[^\s&|;`'"\n]+)([^\n]{0,200})/g;
159
+ // Two-step (S5843, complexity 31): capture ANY cd target with one simple
160
+ // class, then filter to the absolute/home-rooted shapes the original
161
+ // single alternation required (~/, $HOME/, /).
162
+ const cdRegex = /\bcd\s+([^\s&|;`'"\n]+)([^\n]{0,200})/g;
163
+ const absoluteTargetRe = /^(?:~\/|\$HOME\/|\/)/;
160
164
  const writeCmdRegex = /\b(mkdir|touch|cp|mv|git\s+init|(?:pnpm|npm|yarn)\s+(?:init|create)|npx\s+create|cat\s*>|echo\s+[^|]*>|>>?\s*\S)/i;
161
165
  const leaks = new Set();
162
166
  let match;
163
167
  while ((match = cdRegex.exec(transcript)) !== null) {
168
+ if (!absoluteTargetRe.test(match[1])) continue;
164
169
  const original = match[1];
165
170
  let target = original;
166
171
  const rest = match[2] || "";
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { checkBinary } from "../utils/agent-detect.js";
13
13
  import { isSonarReachable, sonarUp } from "../sonar/manager.js";
14
+ import { resolveSonarProjectKey, canResolveSonarProjectKey } from "../sonar/project-key.js";
14
15
  import { runCommand } from "../utils/process.js";
15
16
  import { emitProgress, makeEvent } from "../utils/events.js";
16
17
  import { msg, getLang } from "../utils/messages.js";
@@ -137,6 +138,28 @@ async function checkSonarAuth(config) {
137
138
  return { name: "sonar-auth", ok: false, detail: "Could not validate or generate Sonar token" };
138
139
  }
139
140
 
141
+ /**
142
+ * KJC-BUG-0083 — run the real project-key resolver at preflight time so a
143
+ * repo Sonar cannot scan aborts BEFORE the first coder iteration instead
144
+ * of dying in sonar_repeat after burning tokens. Sonar stays mandatory
145
+ * for code tasks (v2.7.4 contract); this only moves the failure earlier.
146
+ */
147
+ async function checkSonarProjectKey(config) {
148
+ // No remote at all (fresh local project): the SonarStage already skips
149
+ // cleanly via canResolveSonarProjectKey, so preflight must not block.
150
+ // The hard-fail case is the inconsistent one: a remote EXISTS but the
151
+ // resolver cannot parse it — that's what looped into sonar_repeat.
152
+ if (!(await canResolveSonarProjectKey(config))) {
153
+ return { name: "sonar-project-key", ok: true, detail: "No git remote — Sonar stage will skip cleanly" };
154
+ }
155
+ try {
156
+ const key = await resolveSonarProjectKey(config);
157
+ return { name: "sonar-project-key", ok: true, detail: `Project key resolved: ${key}` };
158
+ } catch (err) {
159
+ return { name: "sonar-project-key", ok: false, detail: err.message };
160
+ }
161
+ }
162
+
140
163
  async function checkSecurityAgent(config) {
141
164
  const provider = config.roles?.security?.provider
142
165
  || config.roles?.coder?.provider
@@ -311,6 +334,34 @@ export async function runPreflightChecks({ config, logger, emitter, eventBase, r
311
334
  }
312
335
  }
313
336
 
337
+ // --- 3b. Sonar project key derivable (KJC-BUG-0083) ---
338
+ // The scanner derives its project key from git remote.origin.url. With
339
+ // an unparseable remote (local-path bare, exotic URL) and no explicit
340
+ // sonarqube.project_key, every iteration's scan threw, the run burned
341
+ // coder tokens and died in sonar_repeat. Run the REAL resolver here —
342
+ // canResolveSonarProjectKey() is weaker (any non-empty remote passes) —
343
+ // so the run fails fast with the actionable message before iteration 1.
344
+ if (sonarEnabled && result.ok) {
345
+ const keyCheck = await checkSonarProjectKey(config);
346
+ result.checks.push(keyCheck);
347
+
348
+ emitProgress(emitter, makeEvent("preflight:check", { ...eventBase, stage: "preflight" }, {
349
+ status: keyCheck.ok ? "ok" : "fail",
350
+ message: `Sonar project key: ${keyCheck.detail}`,
351
+ detail: keyCheck
352
+ }));
353
+
354
+ if (!keyCheck.ok) {
355
+ result.ok = false;
356
+ result.errors.push({
357
+ check: "sonar-project-key",
358
+ message: "Sonar cannot scan this repository: no project key can be derived.",
359
+ fix: withDocLink("Set sonarqube.project_key in kj.config.yml, or point remote.origin.url at a valid SSH/HTTPS remote.", "sonar_docker")
360
+ });
361
+ logger.error("Preflight: Sonar project key not derivable — failing fast before burning iterations");
362
+ }
363
+ }
364
+
314
365
  // --- 4. Security agent (graceful — only warning, not blocking) ---
315
366
  if (securityEnabled) {
316
367
  const secCheck = await checkSecurityAgent(config);
@@ -70,7 +70,18 @@ export function evaluateRules(context, rulesConfig = {}) {
70
70
  const styleKeywords = /\b(naming|name|rename|style|format|formatting|indent|spacing|camelCase|snake_case|convention|cosmetic|readability|comment|jsdoc|documentation|whitespace|semicolon|quotes|trailing)\b/i;
71
71
  // Anti-style: if any of these match, the issue is NOT style — it's a real correctness/security concern.
72
72
  // Fixes KJC-BUG-0026 (Solomon approving legitimate security blockers misclassified as "style").
73
- const securityKeywords = /\b(sql\s*injection|xss|csrf|ssrf|rce|injection|vulnerab|exploit|sanitiz|escape\b|encod\b|cors|auth|authn|authz|password|secret|credential|token|api[-_\s]*key|private[-_\s]*key|hash|cipher|crypto|encrypt|decrypt|tls|ssl|certificate|leak|sensitive|pii|privacy|insecure|unsafe|race[-_\s]*condition|deadlock|memory[-_\s]*leak|null[-_\s]*deref|uaf|overflow|traversal|prototype[-_\s]*pollution|deserializ|eval\b|exec\b|spawn|shell|command[-_\s]*injection)\b/i;
73
+ // Decomposed by concern (S5843, complexity 71 → 7 named groups).
74
+ // The union of tokens is byte-identical to the original alternation.
75
+ const SECURITY_KEYWORD_GROUPS = [
76
+ /\b(sql\s*injection|xss|csrf|ssrf|rce|injection|vulnerab|exploit)\b/i,
77
+ /\b(sanitiz|escape\b|encod\b|cors|traversal|prototype[-_\s]*pollution|deserializ)\b/i,
78
+ /\b(auth|authn|authz|password|secret|credential|token|api[-_\s]*key|private[-_\s]*key)\b/i,
79
+ /\b(hash|cipher|crypto|encrypt|decrypt|tls|ssl|certificate)\b/i,
80
+ /\b(leak|sensitive|pii|privacy|insecure|unsafe)\b/i,
81
+ /\b(race[-_\s]*condition|deadlock|memory[-_\s]*leak|null[-_\s]*deref|uaf|overflow)\b/i,
82
+ /\b(eval\b|exec\b|spawn|shell|command[-_\s]*injection)\b/i,
83
+ ];
84
+ const securityKeywords = { test: (text) => SECURITY_KEYWORD_GROUPS.some((re) => re.test(text)) };
74
85
  const securityCategories = new Set(["security", "correctness", "bug", "vulnerability"]);
75
86
  const styleSeverities = new Set(["low", "minor"]);
76
87
  const blockingSeverities = new Set(["critical", "high", "blocker", "major"]);
@@ -49,13 +49,10 @@ export function buildAuditPrompt({ task, instructions, dimensions = null, contex
49
49
  const stackLines = ["## Project Stack"];
50
50
  if (stack.language) stackLines.push(`- Language: ${stack.language}`);
51
51
  if (stack.frameworks?.length) stackLines.push(`- Frameworks: ${stack.frameworks.join(", ")}`);
52
- const tier = stack.isFullstack
53
- ? "fullstack (frontend + backend)"
54
- : stack.isFrontend
55
- ? "frontend-only"
56
- : stack.isBackend
57
- ? "backend-only"
58
- : "unknown";
52
+ let tier = "unknown";
53
+ if (stack.isFullstack) tier = "fullstack (frontend + backend)";
54
+ else if (stack.isFrontend) tier = "frontend-only";
55
+ else if (stack.isBackend) tier = "backend-only";
59
56
  stackLines.push(`- Tier: ${tier}`);
60
57
  if (stack.isFullstack) {
61
58
  stackLines.push("Apply BOTH backend heuristics (queries, sync I/O, caching) AND frontend heuristics (bundle size, lazy loading, render-blocking) where each layer applies.");
@@ -241,7 +238,8 @@ export function buildAuditPrompt({ task, instructions, dimensions = null, contex
241
238
  lines.push(`### ${severity} (${issues.length})`);
242
239
  const slice = issues.slice(0, Math.max(0, remaining));
243
240
  for (const issue of slice) {
244
- const loc = issue.component ? `${issue.component}${issue.line ? `:${issue.line}` : ""}` : "";
241
+ const lineSuffix = issue.line ? `:${issue.line}` : "";
242
+ const loc = issue.component ? `${issue.component}${lineSuffix}` : "";
245
243
  const rule = issue.rule ? ` [${issue.rule}]` : "";
246
244
  lines.push(` - ${loc}${rule} ${issue.message || ""}`.trim());
247
245
  }
@@ -332,8 +330,10 @@ export function buildAuditPrompt({ task, instructions, dimensions = null, contex
332
330
  lines.push(`### ${severity} (${findings.length})`);
333
331
  const slice = findings.slice(0, Math.max(0, remaining));
334
332
  for (const f of slice) {
335
- const loc = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
336
- const cwe = f.cwe ? ` (${Array.isArray(f.cwe) ? f.cwe.join(", ") : f.cwe})` : "";
333
+ const lineSuffix = f.line ? `:${f.line}` : "";
334
+ const loc = f.file ? `${f.file}${lineSuffix}` : "";
335
+ const cweText = Array.isArray(f.cwe) ? f.cwe.join(", ") : f.cwe;
336
+ const cwe = f.cwe ? ` (${cweText})` : "";
337
337
  lines.push(` - ${loc} [${f.rule}]${cwe}: ${f.message || ""}`.trim());
338
338
  }
339
339
  if (findings.length > slice.length) {
@@ -355,7 +355,8 @@ export function buildAuditPrompt({ task, instructions, dimensions = null, contex
355
355
  lines.push(`- Unused files: ${(deadExports.files || []).length}`);
356
356
  const allItems = [...(deadExports.exports || []), ...(deadExports.files || [])].slice(0, 40);
357
357
  for (const item of allItems) {
358
- const loc = `${item.path}${item.line ? `:${item.line}` : ""}`;
358
+ const lineSuffix = item.line ? `:${item.line}` : "";
359
+ const loc = `${item.path}${lineSuffix}`;
359
360
  const name = item.name ? ` \`${item.name}\`` : "";
360
361
  lines.push(` - [${item.severity}] ${loc} [${item.rule}]${name}`);
361
362
  }
@@ -29,7 +29,7 @@ const DIMENSION_KEYS = [
29
29
  * identical across batches on the same project; the stories under
30
30
  * evaluation and the per-batch additional context go last.
31
31
  */
32
- export function buildHuReviewerPromptLayout({ stories, instructions, context = null, productContext = null, domainContext = null, hu_language = "en" }) {
32
+ function buildHuReviewerPromptLayout({ stories, instructions, context = null, productContext = null, domainContext = null, hu_language = "en" }) {
33
33
  const langInstruction = getLanguageInstruction(hu_language);
34
34
 
35
35
  return buildPromptLayout([
@@ -70,7 +70,7 @@ export function parsePlannerOutput(output) {
70
70
  * @param {string} task
71
71
  * @returns {string[]} deduplicated trimmed exclusion items
72
72
  */
73
- export function extractScopeExclusions(task) {
73
+ function extractScopeExclusions(task) {
74
74
  if (!task || typeof task !== "string") return [];
75
75
  const patterns = [
76
76
  /\bNO\s+incluye[^:\n]{0,60}:\s*([^.\n]+)/gi,
@@ -27,4 +27,3 @@ export function makeEmbedder(config = {}) {
27
27
  return new spec.cls({ url: cfg.url, apiKey: cfg.api_key, model: cfg.model, dim, timeoutMs: cfg.timeout_ms });
28
28
  }
29
29
 
30
- export { PROVIDERS };
@@ -124,4 +124,4 @@ export async function query(db, embedder, text, { topK = 5, scope = "all", kindB
124
124
  return reranked;
125
125
  }
126
126
 
127
- export { shouldBoostSources, isTestPath, fuseHits, cosineSim };
127
+ export { fuseHits, cosineSim };
@@ -25,7 +25,7 @@ import { withBrainRecovery } from "../brain/with-brain-recovery.js";
25
25
  * @param {object} config
26
26
  * @returns {number|null}
27
27
  */
28
- export function resolveAgentSilenceTimeoutMs(config) {
28
+ function resolveAgentSilenceTimeoutMs(config) {
29
29
  const minutes = Number(config?.session?.max_agent_silence_minutes);
30
30
  return Number.isFinite(minutes) && minutes > 0 ? Math.round(minutes * 60 * 1000) : null;
31
31
  }
@@ -205,11 +205,13 @@ export class AuditRole extends AgentRole {
205
205
  * result fields. Returns a single object so consumers (CLI formatter,
206
206
  * report-file writer, MCP) don't need to know about the spread shape.
207
207
  *
208
+ * Consumed by tests via vi.importActual (knip blind spot) — keep exported.
209
+ * @public
208
210
  * @param {object} result - raw agent.runTask() return
209
211
  * @param {{provider: string, durationMs: number}} ctx
210
- * @returns {{available: boolean, provider: string, model?: string, tokens_in?: number, tokens_out?: number, total_tokens?: number, cost_usd?: number, durationMs: number, reason?: string}}
212
+ * @returns {{available: boolean, provider: string, model?: string, tokens_in?: number, tokens_out?: number, cached_tokens?: number, total_tokens?: number, cost_usd?: number, durationMs: number, reason?: string}}
211
213
  */
212
- function extractUsage(result, { provider, durationMs }) {
214
+ export function extractUsage(result, { provider, durationMs }) {
213
215
  if (!result || typeof result !== "object") {
214
216
  return { available: false, provider, durationMs, reason: "no agent result" };
215
217
  }
@@ -218,12 +220,18 @@ function extractUsage(result, { provider, durationMs }) {
218
220
  if (tokens_in === null && tokens_out === null) {
219
221
  return { available: false, provider, model: result.model, durationMs, reason: `provider "${provider}" did not report token usage` };
220
222
  }
223
+ // KJC-BUG-0085: cached_tokens must survive this consolidation — the
224
+ // budget chain (computeUsage → BudgetTracker → summary.md Cache hits →
225
+ // telemetry) reads it from `usage` and the audit is the most expensive
226
+ // role of the session.
227
+ const cached_tokens = Number.isFinite(result.cached_tokens) ? result.cached_tokens : 0;
221
228
  return {
222
229
  available: true,
223
230
  provider,
224
231
  model: result.model,
225
232
  tokens_in: tokens_in ?? 0,
226
233
  tokens_out: tokens_out ?? 0,
234
+ cached_tokens,
227
235
  total_tokens: (tokens_in ?? 0) + (tokens_out ?? 0),
228
236
  cost_usd: typeof result.cost_usd === "number" ? result.cost_usd : null,
229
237
  durationMs,
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Session-journal writer shared by every terminal path (KJC-BUG-0084).
3
+ *
4
+ * Pre-fix, the iterations/decisions/tree/summary block lived inline in
5
+ * finalizeApprovedSession(), so a run that died on a stage error
6
+ * (sonar_repeat, gh pr create failure, thrown stage) left only triage.md
7
+ * behind — the Cache hits table, the budget breakdown and the commit list
8
+ * vanished exactly on the runs where they matter most. This module is the
9
+ * single writer; the approved path calls it with its enriched extras and
10
+ * flow-runner's `finally` calls it best-effort for every other ending.
11
+ *
12
+ * Never throws: a journal failure must not mask the run's real result.
13
+ */
14
+
15
+ import { writeIterationsJournal } from "../../orchestrator/session-journal.js";
16
+ import { listCommitsBetween } from "../../utils/git.js";
17
+ import { writeDecisionsJournal } from "./decisions-writer.js";
18
+ import { writeTreeJournal } from "./tree-writer.js";
19
+ import { writeSummaryJournal } from "./summary-writer.js";
20
+
21
+ /**
22
+ * Write iterations.md, decisions.md, tree.txt and summary.md for a session.
23
+ *
24
+ * @param {object} args
25
+ * @param {object} args.session - live session (needs _journalDir to write)
26
+ * @param {{info?: Function, warn?: Function}} [args.logger]
27
+ * @param {string} [args.result] - summary badge: APPROVED | FAILED | STOPPED…
28
+ * @param {number} [args.iterations]
29
+ * @param {object|null} [args.budget] - budgetSummary() snapshot
30
+ * @param {object} [args.stages] - stageResults map
31
+ * @param {Array} [args.commits] - precomputed commit list; computed from
32
+ * session_start_sha when omitted
33
+ * @param {object|null} [args.planAdherence]
34
+ * @returns {Promise<{written: boolean, reason?: string}>}
35
+ */
36
+ export async function writeSessionJournal({ session, logger, result = "APPROVED", iterations = 0, budget = null, stages = {}, commits = null, planAdherence = null }) {
37
+ const journalDir = session?._journalDir;
38
+ if (!journalDir) return { written: false, reason: "no journal dir" };
39
+
40
+ try {
41
+ await writeIterationsJournal(journalDir, session._journalIterations || []);
42
+ const decisionsResult = await writeDecisionsJournal(session, { journalDir, logger });
43
+ const treeResult = await writeTreeJournal(journalDir, session.session_start_sha, { logger });
44
+
45
+ const journalFiles = [...(session._journalFiles || [])];
46
+ if (session._journalIterations?.length) journalFiles.push("iterations.md");
47
+ if (decisionsResult.written) journalFiles.push("decisions.md");
48
+ if (treeResult.written) journalFiles.push("tree.txt");
49
+
50
+ // Commit range from session start so the summary shows every commit
51
+ // the run produced, not just the post-loop scaffold (2026-05-07
52
+ // dogfooding). try/catch tolerates promise rejection AND a sync
53
+ // undefined return from a resetAllMocks-stripped test mock.
54
+ let summaryCommits = Array.isArray(commits) ? commits : null;
55
+ if (!summaryCommits) {
56
+ try { summaryCommits = (await listCommitsBetween(session.head_at_start || session.session_start_sha)) || []; }
57
+ catch { summaryCommits = []; }
58
+ }
59
+
60
+ const startedAt = session._startedAt ? new Date(session._startedAt).toISOString() : undefined;
61
+ await writeSummaryJournal(journalDir, {
62
+ task: session.task,
63
+ result,
64
+ sessionId: session.id,
65
+ iterations,
66
+ durationMs: Date.now() - (session._startedAt || Date.now()),
67
+ budget,
68
+ stages,
69
+ commits: summaryCommits,
70
+ files: journalFiles,
71
+ startedAt,
72
+ finishedAt: new Date().toISOString(),
73
+ brainDecisions: Array.isArray(session.brainDecisions) ? session.brainDecisions.length : 0,
74
+ solomonInvocations: Array.isArray(session.solomonRulings) ? session.solomonRulings.length : 0,
75
+ skills: {
76
+ addyosmani: session.addyosmaniSkills,
77
+ installed: session.autoInstalledSkills,
78
+ recommended: session.skillsRecommended,
79
+ },
80
+ planAdherence,
81
+ }, { logger });
82
+ session._journalWritten = true;
83
+ logger?.info?.(`Session journal written to ${journalDir}`);
84
+ return { written: true };
85
+ } catch (err) {
86
+ logger?.warn?.(`Journal write failed (non-blocking): ${err.message}`);
87
+ return { written: false, reason: err.message };
88
+ }
89
+ }
@@ -21,6 +21,7 @@
21
21
 
22
22
  import { runCommand } from "../utils/process.js";
23
23
  import { isSonarReachable } from "./manager.js";
24
+ import { escapeRegExp } from "../utils/escape-regexp.js";
24
25
 
25
26
  /**
26
27
  * @typedef {Object} DiscoveredSonar
@@ -48,7 +49,7 @@ import { isSonarReachable } from "./manager.js";
48
49
  export function extractHostPort(portsStr, internalPort = 9000) {
49
50
  if (!portsStr) return null;
50
51
  const re = new RegExp(
51
- `(?:0\\.0\\.0\\.0|127\\.0\\.0\\.1|::|\\[::\\]):(\\d+)\\s*->\\s*${internalPort}\\/tcp`,
52
+ `(?:0\\.0\\.0\\.0|127\\.0\\.0\\.1|::|\\[::\\]):(\\d+)\\s*->\\s*${escapeRegExp(internalPort)}\\/tcp`,
52
53
  "g"
53
54
  );
54
55
  const matches = [...portsStr.matchAll(re)];
@@ -11,7 +11,7 @@ import {
11
11
  resolveSonarCredentials,
12
12
  } from "./config-resolver.js";
13
13
 
14
- export async function findNativeSonarScanner() {
14
+ async function findNativeSonarScanner() {
15
15
  const which = await runCommand("sh", ["-c", "command -v sonar-scanner"]);
16
16
  if (which.exitCode === 0) {
17
17
  const bin = String(which.stdout || "").trim();
@@ -157,8 +157,10 @@ export function createCliProgressReporter(opts = {}) {
157
157
  // - ` "foo": 123` propiedad numérica
158
158
  // - ` "foo": {` apertura de objeto en valor
159
159
  // - ` },` / ` ],` / ` }` / ` ]` cierre con o sin coma
160
- const JSON_SCRAP_RE =
161
- /^\s*(?:"[^"\\]*(?:\\.[^"\\]*)*"\s*:\s*.+|[}\]][,]?)\s*$/;
160
+ // Split in two named patterns (S5843): property line vs closer line.
161
+ const JSON_PROP_LINE_RE = /^\s*"[^"\\]*(?:\\.[^"\\]*)*"\s*:\s*.+$/;
162
+ const JSON_CLOSER_LINE_RE = /^\s*[}\]],?\s*$/;
163
+ const JSON_SCRAP_RE = { test: (l) => JSON_PROP_LINE_RE.test(l) || JSON_CLOSER_LINE_RE.test(l) };
162
164
  const onOutput = (event) => {
163
165
  if (!event || typeof event !== "object") return;
164
166
  const raw = typeof event.line === "string" ? event.line : "";