karajan-code 3.7.2 → 3.8.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.
package/README.md CHANGED
@@ -235,8 +235,22 @@ kj board start # Start web dashboard (po
235
235
  kj board open # Start + open in browser
236
236
  kj board status # Check if running
237
237
  kj board stop # Stop the board
238
+
239
+ # Quality guardrails
240
+ kj harden # Install hooks, config, CI, guidelines
241
+ kj check # Verify the harness (drift gate)
242
+ kj mutate # Mutation-test the diff (do tests catch mutants?)
238
243
  ```
239
244
 
245
+ **Mutation testing** (`kj mutate`) closes the gap coverage leaves: it flips the
246
+ logic of the code you just changed and reruns your suite, so a line that ran but
247
+ isn't really tested shows up as a **survivor**. It is diff-scoped by default
248
+ (vs `HEAD~1`), drives the right runner per stack (Stryker/mutmut/Infection/…
249
+ with no silent fallback), and folds into a workflow three ways — on demand,
250
+ as an opt-in reviewer signal (`KJ_REVIEW_MUTATION=1`), or as a non-blocking
251
+ nightly CI job (`kj harden --mutation`). See
252
+ [GETTING-STARTED](docs/GETTING-STARTED.md#mutation-testing--kj-mutate).
253
+
240
254
  ### 2. MCP: inside your AI agent
241
255
 
242
256
  This is the primary use case. Karajan runs as an MCP server inside Claude Code, Codex, or Gemini. You ask your AI agent to do something, and it delegates the heavy lifting to Karajan's pipeline.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "karajan-code",
3
- "version": "3.7.2",
3
+ "version": "3.8.0",
4
4
  "description": "Local multi-agent coding orchestrator with TDD, SonarQube, and code review pipeline",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0",
@@ -0,0 +1,61 @@
1
+ // KJC-TSK-0582: the flat `kj --help` list had grown to 37 commands, which
2
+ // drowns the handful a newcomer actually needs. This module is the single
3
+ // source of truth for which commands are "core" (always shown in `kj --help`)
4
+ // vs "advanced/specialized" (grouped under `kj advanced`). Nothing is hidden
5
+ // or unregistered — every command stays top-level and invokable for
6
+ // back-compat; this only changes what the help listing surfaces by default.
7
+
8
+ /** The few commands a newcomer needs. Shown in `kj --help`. */
9
+ export const CORE_COMMANDS = [
10
+ "start",
11
+ "init",
12
+ "run",
13
+ "plan",
14
+ "status",
15
+ "doctor",
16
+ "harden",
17
+ "config",
18
+ "update",
19
+ ];
20
+
21
+ /** Navigation/built-ins that are neither core-basics nor advanced. */
22
+ export const META_COMMANDS = ["advanced", "help"];
23
+
24
+ /**
25
+ * Advanced commands grouped by area, in display order. Every advanced
26
+ * command MUST live in exactly one group — the parity test fails otherwise,
27
+ * so a newly-registered command can never silently vanish from `kj advanced`.
28
+ */
29
+ export const ADVANCED_GROUPS = [
30
+ { title: "Pipeline (piezas sueltas)", commands: ["autorun", "code", "review", "scan"] },
31
+ { title: "Análisis pre-run", commands: ["discover", "triage", "researcher", "architect", "onboard"] },
32
+ { title: "Búsqueda / RAG", commands: ["rag", "qmd", "watch"] },
33
+ { title: "Calidad / auditoría", commands: ["audit", "check", "mutate", "webperf", "sonar"] },
34
+ { title: "Sesión / board", commands: ["resume", "report", "board", "undo", "standby"] },
35
+ { title: "Infra / setup", commands: ["install-tools", "ollama", "skills", "roles", "agents"] },
36
+ { title: "Mantenimiento", commands: ["clean", "sync", "telemetry"] },
37
+ ];
38
+
39
+ /** Flat set of every advanced command name (for fast lookup / filtering). */
40
+ export const ADVANCED_COMMANDS = ADVANCED_GROUPS.flatMap((g) => g.commands);
41
+
42
+ const ADVANCED_SET = new Set(ADVANCED_COMMANDS);
43
+ const CORE_SET = new Set(CORE_COMMANDS);
44
+ const META_SET = new Set(META_COMMANDS);
45
+
46
+ /**
47
+ * Classify a command name. Returns "core" | "advanced" | "meta" | "unknown".
48
+ * "unknown" means the command is registered but not yet placed in this file —
49
+ * the parity test treats that as a failure so the listing never drifts.
50
+ */
51
+ export function classifyCommand(name) {
52
+ if (CORE_SET.has(name)) return "core";
53
+ if (ADVANCED_SET.has(name)) return "advanced";
54
+ if (META_SET.has(name)) return "meta";
55
+ return "unknown";
56
+ }
57
+
58
+ /** True when the command should be hidden from the flat `kj --help` list. */
59
+ export function isAdvancedCommand(name) {
60
+ return ADVANCED_SET.has(name);
61
+ }
@@ -3,6 +3,7 @@ import { triageCommand } from "../commands/triage.js";
3
3
  import { researcherCommand } from "../commands/researcher.js";
4
4
  import { architectCommand } from "../commands/architect.js";
5
5
  import { onboardCommand } from "../commands/onboard.js";
6
+ import { startCommand } from "../commands/start.js";
6
7
  import { ragIndexCommand, ragQueryCommand, ragInstallHooksCommand, ragEvalCommand } from "../commands/rag.js";
7
8
  import { qmdQueryCommand } from "../commands/qmd.js";
8
9
  import { ragMcpCommand } from "../commands/rag-mcp.js";
@@ -15,8 +16,10 @@ import { undoCommand } from "../commands/undo.js";
15
16
  import { syncCommand } from "../commands/sync.js";
16
17
  import { cleanCommand } from "../commands/clean.js";
17
18
  import { checkCommand } from "../commands/check.js";
19
+ import { mutateCommand } from "../commands/mutate.js";
18
20
  import { hardenCommand } from "../commands/harden.js";
19
21
  import { telemetryPreviewCommand, telemetryStatusCommand } from "../commands/telemetry.js";
22
+ import { formatAdvancedIndex } from "../commands/advanced.js";
20
23
  import { withConfig } from "./_shared.js";
21
24
 
22
25
  /**
@@ -105,6 +108,19 @@ export function registerMeta(program, { pkgVersion }) {
105
108
  });
106
109
  });
107
110
 
111
+ program
112
+ .command("start")
113
+ .description("Single entry point: assess the project and recommend the next step")
114
+ .argument("[task]", "What you want to do (optional natural-language goal)")
115
+ .option("--maturity <type>", "Declare project maturity: new|existing|legacy")
116
+ .option("--yes", "Non-interactive: emit assessment + recommendation, apply nothing")
117
+ .option("--json", "Output the assessment + decision as JSON")
118
+ .action(async (task, flags) => {
119
+ await withConfig(pkgVersion, "start", flags, async ({ config, logger }) => {
120
+ await startCommand({ task, config, logger, flags });
121
+ });
122
+ });
123
+
108
124
  const rag = program.command("rag").description("Retrieval-augmented search over Karajan plans, onboarding briefs and project code");
109
125
  rag.command("index")
110
126
  .description("Index plans + onboarding (and optionally project sources) into the local vector store")
@@ -406,6 +422,7 @@ export function registerMeta(program, { pkgVersion }) {
406
422
  .option("--no-config", "Skip lint/format/commit config files (hooks only)")
407
423
  .option("--no-ci", "Skip CI quality workflows")
408
424
  .option("--no-guidelines", "Skip AI-agent guideline files (AGENTS.md/CLAUDE.md)")
425
+ .option("--mutation", "Also seed an opt-in nightly/manual mutation CI job (never a PR gate)")
409
426
  .option("--only <dirs...>", "Harden only these language roots (e.g. frontend backend)")
410
427
  .option("--exclude <globs...>", "Skip language roots matching these globs (e.g. wrappers)")
411
428
  .option("--report", "Read-only: show what kj would add/improve, change nothing")
@@ -419,6 +436,7 @@ export function registerMeta(program, { pkgVersion }) {
419
436
  config: flags.config !== false,
420
437
  ci: flags.ci !== false,
421
438
  guidelines: flags.guidelines !== false,
439
+ mutation: Boolean(flags.mutation),
422
440
  only: flags.only ?? [],
423
441
  exclude: flags.exclude ?? [],
424
442
  report: Boolean(flags.report),
@@ -441,4 +459,35 @@ export function registerMeta(program, { pkgVersion }) {
441
459
  );
442
460
  if (Number.isInteger(code)) process.exit(code);
443
461
  });
462
+
463
+ program
464
+ .command("mutate")
465
+ .description("Diff-scoped mutation testing (¿cazan tus tests los mutantes de tu cambio?)")
466
+ .argument("[path]", "Target explícito a mutar (omite el diff)")
467
+ .option("--since <ref>", "Ref git contra la que sacar el diff", "HEAD~1")
468
+ .option("--max-survivors <n>", "Supervivientes tolerados antes de exit 1", "0")
469
+ .option("--json", "Emitir el resultado normalizado como JSON")
470
+ .action(async (pathArg, flags) => {
471
+ const code = await withConfig(pkgVersion, "mutate", flags, async ({ logger }) =>
472
+ mutateCommand({
473
+ path: pathArg,
474
+ since: flags.since,
475
+ maxSurvivors: Number(flags.maxSurvivors),
476
+ json: Boolean(flags.json),
477
+ logger,
478
+ })
479
+ );
480
+ if (Number.isInteger(code)) process.exit(code);
481
+ });
482
+
483
+ // KJC-TSK-0582: index of the advanced/specialized commands kept out of the
484
+ // flat `kj --help` list. Descriptions are read from commander itself so they
485
+ // never drift from each command's own --description.
486
+ program
487
+ .command("advanced")
488
+ .description("List advanced & specialized commands, grouped by area")
489
+ .action(() => {
490
+ const descriptions = Object.fromEntries(program.commands.map((c) => [c.name(), c.description()]));
491
+ console.log(formatAdvancedIndex(descriptions));
492
+ });
444
493
  }
package/src/cli.js CHANGED
@@ -2,8 +2,9 @@
2
2
  import path from "node:path";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
- import { Command } from "commander";
5
+ import { Command, Help } from "commander";
6
6
  import { loadConfig } from "./config.js";
7
+ import { isAdvancedCommand } from "./cli/advanced-commands.js";
7
8
  import { registerPipeline } from "./cli/register-pipeline.js";
8
9
  import { registerPlan } from "./cli/register-plan.js";
9
10
  import { registerRolesSkills } from "./cli/register-roles-skills.js";
@@ -41,8 +42,20 @@ program
41
42
  .allowUnknownOption(true)
42
43
  .allowExcessArguments(true);
43
44
 
44
- // KJC-TSK-0571: the command list is long (30+). Orient a newcomer to the few
45
- // commands they actually need; the rest are advanced/internal.
45
+ // KJC-TSK-0582: the flat list had grown to 37 commands. Show only the core
46
+ // basics in `kj --help`; the advanced/specialized ones live under
47
+ // `kj advanced`. The filter applies to the ROOT help only — subcommand help
48
+ // keeps listing its own subcommands untouched.
49
+ program.configureHelp({
50
+ visibleCommands(cmd) {
51
+ const cmds = Help.prototype.visibleCommands.call(this, cmd);
52
+ if (cmd !== program) return cmds;
53
+ return cmds.filter((c) => !isAdvancedCommand(c.name()));
54
+ },
55
+ });
56
+
57
+ // KJC-TSK-0571/0582: orient a newcomer to the few commands they need and
58
+ // point them at `kj advanced` for everything else.
46
59
  program.addHelpText(
47
60
  "after",
48
61
  `
@@ -53,7 +66,7 @@ Getting started (the basics — start here):
53
66
  kj doctor Check your environment is ready
54
67
  kj harden Add quality git hooks + CI to any repo
55
68
 
56
- Everything else is advanced or internal — you rarely call it directly.`
69
+ kj advanced List every advanced/specialized command, grouped by area`
57
70
  );
58
71
 
59
72
  registerPipeline(program, { pkgVersion: PKG_VERSION });
@@ -0,0 +1,31 @@
1
+ // KJC-TSK-0582: `kj advanced` prints every advanced/specialized command,
2
+ // grouped by area, with the one-line description commander already holds for
3
+ // it. Pure formatter (takes a name→description map) so it's trivially
4
+ // testable without spinning up the whole CLI.
5
+ import { ADVANCED_GROUPS } from "../cli/advanced-commands.js";
6
+
7
+ const NAME_PAD = 14;
8
+
9
+ /**
10
+ * Build the `kj advanced` index text.
11
+ * @param {Record<string,string>|Map<string,string>} descriptions name → one-line description
12
+ */
13
+ export function formatAdvancedIndex(descriptions) {
14
+ const lookup = descriptions instanceof Map ? descriptions : new Map(Object.entries(descriptions || {}));
15
+ const firstLine = (text) => String(text || "").split("\n")[0].trim();
16
+
17
+ const lines = [
18
+ "Comandos avanzados y especializados (agrupados por área).",
19
+ "Todos siguen siendo invocables directamente: kj <comando>.",
20
+ "",
21
+ ];
22
+ for (const group of ADVANCED_GROUPS) {
23
+ lines.push(`${group.title}:`);
24
+ for (const name of group.commands) {
25
+ lines.push(` kj ${name.padEnd(NAME_PAD)} ${firstLine(lookup.get(name))}`.trimEnd());
26
+ }
27
+ lines.push("");
28
+ }
29
+ lines.push("Usa 'kj <comando> --help' para los detalles de cualquiera de ellos.");
30
+ return lines.join("\n");
31
+ }
@@ -76,6 +76,7 @@ export async function hardenCommand({
76
76
  config = true,
77
77
  ci = true,
78
78
  guidelines = true,
79
+ mutation = false,
79
80
  dryRun = false,
80
81
  json = false,
81
82
  report = false,
@@ -134,7 +135,7 @@ export async function hardenCommand({
134
135
  const cfg = withConfig ? installConfigsForRoots({ projectDir, roots, dryRun }) : null;
135
136
  const withCi = ci && profile !== "minimal";
136
137
  const wf = withCi
137
- ? installWorkflows({ projectDir, language: roots[0]?.language ?? null, profile, dryRun })
138
+ ? installWorkflows({ projectDir, language: roots[0]?.language ?? null, profile, mutation, dryRun })
138
139
  : null;
139
140
  const withGuidelines = guidelines && profile !== "minimal";
140
141
  const gl = withGuidelines ? installGuidelines({ projectDir, dryRun }) : null;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * `kj mutate` (KJC-TSK-0587) — diff-scoped mutation testing. Detects language
3
+ * (M-A registry) → changed lines (M-B diff-scope) → runs the tool (M-C runner)
4
+ * only over what you just touched. `--json` + exit code make it a gate. No
5
+ * silent fallback: unsupported language / unreadable report exit non-zero.
6
+ */
7
+
8
+ import fs from "node:fs/promises";
9
+ import path from "node:path";
10
+ import { detectProjectStack } from "../utils/stack-detect.js";
11
+ import { getMutationTool } from "../mutate/tool-registry.js";
12
+ import { getDiffScope } from "../mutate/diff-scope.js";
13
+ import { runMutation } from "../mutate/runner.js";
14
+
15
+ // Per-tool launch detail: subcommand + JSON report path. Tools without a JSON
16
+ // report leave `report` empty → the run surfaces the tool's own output.
17
+ const INVOCATION = {
18
+ stryker: { base: ["run"], report: "reports/mutation/mutation.json" },
19
+ mutmut: { base: ["run"], report: "mutmut-report.json" },
20
+ infection: { base: [], report: "infection.json" },
21
+ "go-mutesting": { base: [], report: "" },
22
+ pitest: { base: [], report: "" },
23
+ };
24
+
25
+ const DEFAULT_SINCE = "HEAD~1";
26
+
27
+ function makeReadReport(reportFile) {
28
+ if (!reportFile) return undefined;
29
+ return async () => JSON.parse(await fs.readFile(reportFile, "utf8"));
30
+ }
31
+
32
+ /**
33
+ * `deps` ({detectStack, diffScope, run}) is injectable so tests stay pure.
34
+ * `since` diffs against a git ref (default HEAD~1); `path` bypasses the diff.
35
+ * @returns {Promise<number>} process exit code
36
+ */
37
+ export async function mutateCommand({
38
+ projectDir = process.cwd(),
39
+ since,
40
+ path: pathArg,
41
+ json = false,
42
+ maxSurvivors = 0,
43
+ logger = console,
44
+ deps = {},
45
+ } = {}) {
46
+ const detectStack = deps.detectStack ?? detectProjectStack;
47
+ const diffScope = deps.diffScope ?? getDiffScope;
48
+ const run = deps.run ?? runMutation;
49
+ const say = (msg) => logger.info?.(msg);
50
+
51
+ const { language } = await detectStack(projectDir);
52
+ const tool = getMutationTool(language);
53
+ if (!tool.supported) {
54
+ say(`kj mutate: lenguaje no soportado (${language ?? "desconocido"}) — ${tool.reason}`);
55
+ return 2;
56
+ }
57
+
58
+ let scope;
59
+ if (pathArg) {
60
+ const args = tool.scope.flag ? [tool.scope.flag, pathArg] : [pathArg];
61
+ scope = { supported: true, empty: false, args };
62
+ } else {
63
+ scope = await diffScope({ since: since ?? DEFAULT_SINCE, language, projectDir });
64
+ }
65
+ if (scope.empty) {
66
+ say("kj mutate: nada que mutar en el diff.");
67
+ return 0;
68
+ }
69
+
70
+ const invocation = INVOCATION[tool.id] ?? { base: [], report: "" };
71
+ const reportFile = invocation.report ? path.join(projectDir, invocation.report) : "";
72
+ const outcome = await run({
73
+ binary: tool.binary,
74
+ args: [...invocation.base, ...scope.args],
75
+ cwd: projectDir,
76
+ readReport: makeReadReport(reportFile),
77
+ });
78
+
79
+ if (!outcome.result) {
80
+ say(`kj mutate: la herramienta ${tool.id} no produjo un informe legible.`);
81
+ if (outcome.stderr) say(outcome.stderr.trim());
82
+ return 1;
83
+ }
84
+
85
+ const { score, killed, total, survived } = outcome.result;
86
+ if (json) {
87
+ say(JSON.stringify(outcome.result));
88
+ } else {
89
+ say(`kj mutate (${tool.id}): score ${score ?? "n/a"}% — ${killed}/${total} mutantes cazados`);
90
+ for (const s of survived) say(` ✗ superviviente ${s.file}:${s.line} (${s.mutator ?? s.status})`);
91
+ if (survived.length === 0) say(" ✓ sin supervivientes");
92
+ }
93
+ return survived.length > maxSurvivors ? 1 : 0;
94
+ }
@@ -0,0 +1,117 @@
1
+ // KJC-TSK-0570 (Onboard C) — `kj start`: the single entry point to the Brain.
2
+ // Wires the read-only sweep (0568) → deterministic assessment (0569) → haiku
3
+ // decider (0569), reports the recommended next step, and — interactively only —
4
+ // confirms and dispatches the chosen intent to its saved command
5
+ // (harden/rag/run/plan). --json / --yes / no-TTY stay read-only: emit the
6
+ // assessment + intent and apply nothing. Collaborators are injected for testing.
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { execa } from "execa";
10
+ import { runReadOnlySweep } from "../start/sweep.js";
11
+ import { buildAssessment } from "../start/assessment.js";
12
+ import { StartDecidorRole } from "../start/start-decider-role.js";
13
+ import { createWizard, isTTY } from "../utils/wizard.js";
14
+
15
+ // The recommended next step shown for each intent.
16
+ const NEXT_STEP = {
17
+ ASSESS_ONLY: "Everything looks healthy — nothing to do.",
18
+ RECOMMEND_HARDEN: "Suggested: `kj harden --interactive`",
19
+ RECOMMEND_INDEX: "Suggested: `kj rag index`",
20
+ START_TASK: 'Suggested: `kj run "<task>"`',
21
+ PROPOSE_PLAN: 'Suggested: `kj plan "<goal>"`',
22
+ };
23
+
24
+ // Each writing intent maps to the saved command + args `kj start` dispatches.
25
+ const DISPATCH = {
26
+ RECOMMEND_HARDEN: () => ["harden", "--interactive"],
27
+ RECOMMEND_INDEX: () => ["rag", "index"],
28
+ START_TASK: (task) => ["run", task],
29
+ PROPOSE_PLAN: (task) => ["plan", task],
30
+ };
31
+
32
+ const ASK_FALLBACK = "What would you like to do with this project?";
33
+ const CLI_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "cli.js");
34
+
35
+ // Run a saved `kj` subcommand as a child, inheriting stdio so its own prompts
36
+ // (e.g. `harden --interactive`) drive the real terminal. Never throws here.
37
+ async function spawnKj(args, { cwd }) {
38
+ await execa("node", [CLI_PATH, ...args.filter(Boolean)], { cwd, stdio: "inherit", reject: false });
39
+ }
40
+
41
+ // The decider has its own quota/parse recovery; a spawn-level failure (CLI not
42
+ // installed) still throws, so we degrade here too — `kj start` never crashes.
43
+ async function decide({ task, text, config, logger, makeDecider }) {
44
+ const decider = makeDecider({ config, logger });
45
+ try {
46
+ const decision = await decider.execute({ userMessage: task, assessment: text });
47
+ return decision.result || {};
48
+ } catch (err) {
49
+ logger?.warn?.(`[start] decider unavailable (${err?.message || err}) — asking the user.`);
50
+ return { intent: "ASK_USER", rationale: "Decider unavailable.", questionToAsk: ASK_FALLBACK, degraded: true };
51
+ }
52
+ }
53
+
54
+ // Ask one yes/no, always closing the readline interface afterwards.
55
+ async function confirmApply(makeWizard) {
56
+ const wizard = makeWizard();
57
+ try {
58
+ return await wizard.confirm("Apply this?", true);
59
+ } finally {
60
+ wizard.close();
61
+ }
62
+ }
63
+
64
+ // Print the rationale + recommended step, or the open question for ASK_USER.
65
+ function render(result) {
66
+ if (result.intent === "ASK_USER") {
67
+ console.log(`❓ ${result.questionToAsk || ASK_FALLBACK}`);
68
+ return;
69
+ }
70
+ if (result.rationale) console.log(`→ ${result.rationale}`);
71
+ const step = NEXT_STEP[result.intent];
72
+ if (step) console.log(` ${step}`);
73
+ }
74
+
75
+ export async function startCommand({ task = "", config, logger, flags = {}, deps = {} }) {
76
+ const sweep = deps.runReadOnlySweep || runReadOnlySweep;
77
+ const assess = deps.buildAssessment || buildAssessment;
78
+ const makeDecider = deps.makeDecider || ((opts) => new StartDecidorRole(opts));
79
+ const tty = deps.isTTY || isTTY;
80
+ const spawn = deps.spawnKj || spawnKj;
81
+ const makeWizard = deps.makeWizard || (() => createWizard());
82
+
83
+ const bundle = await sweep(config.projectDir, { declared: flags.maturity || null });
84
+ const { text, summary } = assess(bundle);
85
+ let result = await decide({ task, text, config, logger, makeDecider });
86
+
87
+ if (flags.json) {
88
+ console.log(JSON.stringify({ maturity: summary.maturity, assessment: text, ...result }, null, 2));
89
+ return { ok: true, intent: result.intent };
90
+ }
91
+
92
+ console.log(`${text}\n`);
93
+ const interactive = tty() && !flags.yes;
94
+ let goal = task;
95
+
96
+ // ASK_USER: one interactive re-route — the open answer becomes the goal.
97
+ if (result.intent === "ASK_USER" && interactive) {
98
+ const wizard = makeWizard();
99
+ try {
100
+ const answer = await wizard.input(`❓ ${result.questionToAsk || ASK_FALLBACK}`);
101
+ if (answer) {
102
+ goal = answer;
103
+ result = await decide({ task: answer, text, config, logger, makeDecider });
104
+ }
105
+ } finally {
106
+ wizard.close();
107
+ }
108
+ }
109
+ render(result);
110
+
111
+ // Dispatch the chosen intent to its saved command, confirming first (it writes).
112
+ const toArgs = DISPATCH[result.intent];
113
+ if (interactive && toArgs && (await confirmApply(makeWizard))) {
114
+ await spawn(toArgs(goal), { cwd: config.projectDir });
115
+ }
116
+ return { ok: true, intent: result.intent };
117
+ }
@@ -27,7 +27,8 @@ const DEFAULTS = {
27
27
  triage: { provider: null, model: null },
28
28
  discover: { provider: null, model: null },
29
29
  architect: { provider: null, model: null },
30
- hu_reviewer: { provider: null, model: null }
30
+ hu_reviewer: { provider: null, model: null },
31
+ start: { provider: null, model: "haiku" }
31
32
  },
32
33
  pipeline: {
33
34
  planner: { enabled: false },
@@ -90,6 +90,7 @@ const RolesMap = v.optional(v.looseObject({
90
90
  discover: v.optional(RoleEntry),
91
91
  architect: v.optional(RoleEntry),
92
92
  hu_reviewer: v.optional(RoleEntry),
93
+ start: v.optional(RoleEntry),
93
94
  }));
94
95
 
95
96
  const PipelineEntry = v.looseObject({
@@ -0,0 +1,71 @@
1
+ // KJC-TSK-0583 — Inbound secret redaction for the review boundary.
2
+ //
3
+ // The outbound boundary (output-guard.js) already blocks committing secrets.
4
+ // This closes the *inbound* gap: a hardcoded credential in the working tree
5
+ // would otherwise reach the (possibly cloud) reviewer model verbatim inside the
6
+ // diff. `redactSecrets` masks each credential before the model sees it, reusing
7
+ // the SAME catalog as output-guard — no new patterns, no AI cost, deterministic.
8
+ import { CREDENTIAL_PATTERNS } from "./output-guard.js";
9
+
10
+ // Families whose match begins with a fixed, identifiable literal prefix. The
11
+ // placeholder keeps that prefix so the reviewer can still tell WHAT kind of
12
+ // secret was redacted (and say "move it to .env") without seeing the value.
13
+ const STABLE_PREFIX_BY_ID = {
14
+ "aws-key": "AKIA",
15
+ "npm-token": "npm_",
16
+ "openai-key": "sk-",
17
+ "anthropic-key": "sk-ant-",
18
+ "stripe-key": "sk_live_",
19
+ "stripe-test": "sk_test_",
20
+ "google-api-key": "AIza",
21
+ };
22
+
23
+ // Families with a dynamic prefix: keep the real match up to and including the
24
+ // first separator (ghp_/gho_/…, xoxb-/xoxp-/…), then mask the rest.
25
+ const DYNAMIC_SEPARATOR_BY_ID = {
26
+ "github-token": "_",
27
+ "slack-token": "-",
28
+ };
29
+
30
+ const GENERIC = "***REDACTED-SECRET***";
31
+ const SUFFIX = "***REDACTED***";
32
+
33
+ function placeholderFor(id, match) {
34
+ const stable = STABLE_PREFIX_BY_ID[id];
35
+ if (stable) return `${stable}${SUFFIX}`;
36
+ const sep = DYNAMIC_SEPARATOR_BY_ID[id];
37
+ if (sep) {
38
+ const idx = match.indexOf(sep);
39
+ return idx >= 0 ? `${match.slice(0, idx + 1)}${SUFFIX}` : GENERIC;
40
+ }
41
+ return GENERIC;
42
+ }
43
+
44
+ // Apply the most specific prefixes first so `sk-ant-` wins over `sk-`; families
45
+ // without a stable prefix keep their catalog order (stable sort) and run last.
46
+ function orderedPatterns() {
47
+ return [...CREDENTIAL_PATTERNS].sort(
48
+ (a, b) => (STABLE_PREFIX_BY_ID[b.id]?.length ?? 0) - (STABLE_PREFIX_BY_ID[a.id]?.length ?? 0)
49
+ );
50
+ }
51
+
52
+ /**
53
+ * Mask every credential in `text`, preserving line structure. Pure and
54
+ * deterministic: clean text is returned untouched (no-op, no cost).
55
+ * @param {string} text
56
+ * @returns {string}
57
+ */
58
+ export function redactSecrets(text) {
59
+ if (typeof text !== "string" || text.length === 0) return text;
60
+ let out = text;
61
+ for (const { id, pattern } of orderedPatterns()) {
62
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
63
+ out = out.replace(new RegExp(pattern.source, flags), (match) =>
64
+ // Idempotent: a broad pattern (generic-secret, hardcoded-key-assignment)
65
+ // can span an already-masked value; leave the more specific placeholder
66
+ // in place instead of clobbering it with the generic one.
67
+ match.includes("REDACTED") ? match : placeholderFor(id, match)
68
+ );
69
+ }
70
+ return out;
71
+ }
@@ -10,7 +10,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
10
  import { join } from "node:path";
11
11
 
12
12
  import { upsertManagedBlock } from "../utils/managed-markers.js";
13
- import { extraWorkflowsFor, qualityWorkflowFor, WORKFLOWS } from "./workflow-templates.js";
13
+ import { extraWorkflowsFor, mutationWorkflowFor, qualityWorkflowFor, WORKFLOWS } from "./workflow-templates.js";
14
14
 
15
15
  const BLOCK_VERSION = 1;
16
16
  const WORKFLOWS_DIR = join(".github", "workflows");
@@ -31,12 +31,14 @@ export function installWorkflows({
31
31
  projectDir = process.cwd(),
32
32
  language = null,
33
33
  profile = "standard",
34
+ mutation = false,
34
35
  dryRun = false,
35
36
  } = {}) {
36
37
  const dir = join(projectDir, WORKFLOWS_DIR);
37
38
  const quality = qualityWorkflowFor(language);
38
39
  const extras = extraWorkflowsFor({ profile, publishable: isPublishableNpm(projectDir) });
39
- const all = [...WORKFLOWS, ...(quality ? [quality] : []), ...extras];
40
+ const mut = mutation ? mutationWorkflowFor(language) : null;
41
+ const all = [...WORKFLOWS, ...(quality ? [quality] : []), ...extras, ...(mut ? [mut] : [])];
40
42
  const results = [];
41
43
  for (const wf of all) {
42
44
  const target = join(dir, wf.file);
@@ -147,6 +147,58 @@ export const PACK_SMOKE_WORKFLOW = [
147
147
  ' echo "Tarball installs clean: $tgz"',
148
148
  ].join("\n");
149
149
 
150
+ // Opt-in nightly/manual mutation audit (KJC-TSK-0589). NEVER a PR gate: it runs
151
+ // on a weekly schedule + manual dispatch, and the mutate step is non-blocking
152
+ // (continue-on-error) so a red run never nags. Only stacks whose `kj mutate`
153
+ // yields a JSON report (stryker/mutmut/infection) get a workflow — no silent
154
+ // scaffold for tools that can't report yet.
155
+ const MUTATION_TOOLCHAIN = {
156
+ javascript: [" - run: npm ci"],
157
+ python: [
158
+ " - uses: actions/setup-python@v5",
159
+ " with:",
160
+ " python-version: '3.12'",
161
+ " - run: pip install mutmut pytest",
162
+ ],
163
+ php: [
164
+ " - uses: shivammathur/setup-php@v2",
165
+ " with:",
166
+ " php-version: '8.3'",
167
+ " - run: composer install --no-interaction --no-progress",
168
+ ],
169
+ };
170
+ MUTATION_TOOLCHAIN.typescript = MUTATION_TOOLCHAIN.javascript;
171
+
172
+ /** Opt-in mutation workflow entry, or null for a stack without a JSON report. */
173
+ export function mutationWorkflowFor(language) {
174
+ const toolchain = MUTATION_TOOLCHAIN[language];
175
+ if (!toolchain) return null;
176
+ const body = [
177
+ "name: Mutation (nightly)",
178
+ "on:",
179
+ " schedule:",
180
+ " - cron: '0 4 * * 1'",
181
+ " workflow_dispatch:",
182
+ "permissions:",
183
+ " contents: read",
184
+ "jobs:",
185
+ " mutation:",
186
+ " runs-on: ubuntu-latest",
187
+ " steps:",
188
+ " - uses: actions/checkout@v4",
189
+ " with:",
190
+ " fetch-depth: 0",
191
+ " - uses: actions/setup-node@v4",
192
+ " with:",
193
+ " node-version: 22",
194
+ ...toolchain,
195
+ " - name: Mutation testing (advisory, never blocks a PR)",
196
+ " continue-on-error: true",
197
+ " run: npx --yes --package karajan-code kj mutate --since HEAD~1",
198
+ ].join("\n");
199
+ return { file: "kj-mutation.yml", blockId: "wf-mutation", body };
200
+ }
201
+
150
202
  /** Conditional workflows: shrink-budget on strict, pack-smoke when publishable. */
151
203
  export function extraWorkflowsFor({ profile = "standard", publishable = false } = {}) {
152
204
  const extras = [];