From 8a7cb4daa7b5b605e86f74e7472cc1954888cac9 Mon Sep 17 00:00:00 2001 From: vu1n <2105991+vu1n@users.noreply.github.com> Date: Tue, 9 Jun 2026 11:16:59 +0700 Subject: [PATCH 1/2] feat: wire kypp shared memory into workers; switch review loop to /tighten + /ship-review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 of the kypp/pillbox roadmap: opt-in, agent-driven, fail-open shared memory for parallel workers. - Add `memory` config section (enabled, project); resolve_memory_env scopes KYPP_PROJECT/KYPP_REPO_ROOT/BACCHUS_MEMORY onto the worker process - Worker prompt: kypp briefing at start, recall before work, remember before release — all guarded on $BACCHUS_MEMORY and fail-open - Replace /simplify with /tighten (per-iteration) + /ship-review (final gate) in the worker review loop, CLAUDE.md, and eval rubric/scenarios - Fix two pre-existing clippy lints (collapsible_if, unnecessary_sort_by) --- CLAUDE.md | 22 +++++- evals/cases/worker/scenarios.json | 57 ++++++++++------ evals/evaluators/rubrics.py | 3 +- skills/bacchus/commands/bacchus-worker.md | 77 +++++++++++++++++++-- src/quality.rs | 81 +++++++++++++++++++++++ src/tools/eval.rs | 6 +- src/tools/list.rs | 2 +- src/tools/session/workers.rs | 13 ++++ 8 files changed, 227 insertions(+), 34 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index ef96cdb..c53915a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,8 +11,9 @@ Workspace-based coordination CLI for multi-agent work. Uses jj workspaces + SQLi 2. bacchus claim --agent-id 3. Work in .bacchus/workspaces// (use jj -R, NEVER cd) 4. jj -R .bacchus/workspaces// rebase -d main -5. Review loop until green (rebase → /simplify → bacchus review → fix → repeat) -6. bacchus release --status done +5. Review loop until green (rebase → /tighten → bacchus review → fix → repeat) +6. /ship-review (final pre-release gate) +7. bacchus release --status done ``` ### Key Commands @@ -190,8 +191,22 @@ worker: # stale_grace_ms: 60000 # max_runtime_ms: null # kill_stale: false + +memory: # Shared memory via kypp (opt-in; requires `kypp` on PATH) + # enabled: true + # project: "my-project" # KYPP_PROJECT; defaults to the project directory name ``` +### Shared Memory (kypp) + +When `memory.enabled`, bacchus scopes each worker's environment +(`KYPP_PROJECT`, `KYPP_REPO_ROOT`, `BACCHUS_MEMORY=1`) so the worker prompt's +`kypp briefing` / `recall` / `remember` steps bind the right store. Integration +is **agent-driven and fail-open**: if `kypp` is not installed the steps no-op. +Code grounding (`KYPP_REPO_ROOT`) points at the canonical project tree, not the +ephemeral per-task workspace. (Auto-capture/distill of session logs is Phase 2 — +it depends on `§0` session logs that arrive with the pillbox sandbox.) + ## Environment Env vars override `.bacchus/config.yaml` values for CI/scripting. @@ -201,6 +216,9 @@ Env vars override `.bacchus/config.yaml` values for CI/scripting. | `CLAUDE_PROJECT_DIR` | Workspace root (set by Claude Code) | | `BACCHUS_DB_PATH` | Override DB location | | `BACCHUS_WORKER_CMD` | Override `worker.cmd` from config.yaml | +| `BACCHUS_MEMORY` | Set to `1` by bacchus when `memory.enabled` — signals workers to use kypp | +| `KYPP_PROJECT` | kypp project binding, set per-worker from `memory.project` | +| `KYPP_REPO_ROOT` | Repo root kypp grounds code refs against (the project tree) | ## Error Handling diff --git a/evals/cases/worker/scenarios.json b/evals/cases/worker/scenarios.json index d294691..6286ffe 100644 --- a/evals/cases/worker/scenarios.json +++ b/evals/cases/worker/scenarios.json @@ -23,7 +23,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -53,7 +54,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -83,7 +85,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -113,7 +116,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -143,7 +147,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -173,7 +178,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -203,7 +209,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true, @@ -234,7 +241,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -264,7 +272,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -294,7 +303,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -324,7 +334,8 @@ "no_package_install": true, "runs_review_loop": false, "rebases_before_release": false, - "runs_simplify": false, + "runs_tighten": false, + "runs_ship_review": false, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -352,7 +363,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -383,7 +395,8 @@ "runs_review_loop": true, "rebases_before_release": true, "resolves_conflicts": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -440,7 +453,8 @@ "runs_review_loop": true, "handles_review_failure": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -470,7 +484,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -501,7 +516,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -531,7 +547,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true, @@ -566,7 +583,8 @@ "no_package_install": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true @@ -597,7 +615,8 @@ "adds_dep_to_manifest": true, "runs_review_loop": true, "rebases_before_release": true, - "runs_simplify": true, + "runs_tighten": true, + "runs_ship_review": true, "describes_changes": true, "releases_done": true, "sends_heartbeat": true diff --git a/evals/evaluators/rubrics.py b/evals/evaluators/rubrics.py index e37ecfd..6318c07 100644 --- a/evals/evaluators/rubrics.py +++ b/evals/evaluators/rubrics.py @@ -40,9 +40,10 @@ "weight": 0.20, "checks": [ "Rebases onto main before releasing: `jj -R ... rebase -d main`", - "Runs /simplify to clean up code", + "Runs /tighten each review-loop iteration to clean up code", "Runs `bacchus review ` to validate changes", "Fixes issues if review fails, then re-runs the loop", + "Runs /ship-review as a final gate before releasing as done", "Does NOT release as done until review passes", ], }, diff --git a/skills/bacchus/commands/bacchus-worker.md b/skills/bacchus/commands/bacchus-worker.md index da037bb..5bdde15 100644 --- a/skills/bacchus/commands/bacchus-worker.md +++ b/skills/bacchus/commands/bacchus-worker.md @@ -26,6 +26,15 @@ bacchus claim --agent-id bacchus next --agent-id ``` +**Load shared memory (if `$BACCHUS_MEMORY` is set):** the swarm has a shared +memory store. Before working, pull the team's accumulated lore — pitfalls first: + +```bash +kypp briefing 2>/dev/null || true # known traps + decisions for this project +``` + +If `kypp` is not on PATH this is a no-op — proceed normally. + ### 2. Understand the Task Run ALL three commands — do not skip any: @@ -44,6 +53,18 @@ From the context output, **extract and record**: - Active collisions with other agents - Risk hints +**Recall relevant memory (if `$BACCHUS_MEMORY` is set):** before touching code in +your footprint, search the shared store for prior lessons about it: + +```bash +kypp recall "" 2>/dev/null || true +``` + +Each result is one line: `handle [type ✓conf] subject — content → path:line`. Read +the lines; `kypp show ` expands one you intend to act on. Trust `👤` +(human-corrected) and `☑` (verified) claims over your own inference. The line is +usually enough — only expand what you act on. + ### 3. Validate Footprint Before Starting After reading context, **write down** the footprint lists: @@ -125,12 +146,12 @@ Before releasing, you MUST complete this loop. Every step is required — do not ```bash jj -R .bacchus/workspaces// resolve ``` -3. **Run `/simplify`** — THIS IS MANDATORY. Review all changed code for reuse, quality, and efficiency. Fix every finding before proceeding. +3. **Run `/tighten`** — THIS IS MANDATORY. Review all changed code for reuse, quality, and efficiency, and apply the fixes. Fix every finding before proceeding. 4. **Run `bacchus review `** — read the full output. 5. **If review fails with code issues:** fix every failing check, then **go back to step 1**. -6. **If review passes:** proceed to Release (step 7). +6. **If review passes:** proceed to the final ship review (step 7). -**You MUST run `/simplify` on every iteration.** Skipping it is a protocol violation. +**You MUST run `/tighten` on every iteration.** Skipping it is a protocol violation. **Circuit breaker:** - If the loop fails **5 times**, release as `blocked` with error details. @@ -139,13 +160,37 @@ Before releasing, you MUST complete this loop. Every step is required — do not **Do NOT release as `done` until the review loop passes.** **Do NOT stop or exit until you have released your task.** -### 7. Describe and Release +### 7. Final Ship Review (MANDATORY before `done`) + +Once the review loop is green, run a final pre-release pass: + +1. **Run `/ship-review`** — THIS IS MANDATORY. It is the final gate before this work is merged, equivalent to a pre-PR review. Read the full output. +2. **If it surfaces blocking issues:** fix them, then **go back to the review loop (step 6)** and re-run `/tighten` + `bacchus review` before returning here. +3. **If it is clean:** proceed to Release (step 8). + +**You MUST run `/ship-review` once before releasing as `done`.** Skipping it is a protocol violation. + +### 8. Describe and Release ```bash # Describe your changes jj -R .bacchus/workspaces// describe -m "concise summary of changes" ``` +**Record durable lessons (if `$BACCHUS_MEMORY` is set):** if you hit a non-obvious +pitfall, discovered a fact the next agent will need, or made a decision worth +keeping, write it to shared memory before releasing — including when you release +as `blocked`/`failed` (a trap you hit is exactly what saves the next agent): + +```bash +kypp remember "" "" 2>/dev/null || true +``` + +Rules: `subject` is the claim's identity — reuse an existing subject to correct it, +a new subject creates a new memory. Keep it model-agnostic (write "X fails when…", +not "I couldn't X"). Distill a reusable lesson, not a transcript. Skip this if you +learned nothing durable — don't log routine work. + Choose the appropriate release status: | Situation | Status | When | @@ -168,7 +213,7 @@ bacchus message send --from --to orchestrator --body " # after fixing conflicts @@ -192,6 +237,23 @@ bacchus handle filter $sym1 --kind fn # → $sym2 bacchus handle clear # cleanup ``` +## Memory (kypp) — only when `$BACCHUS_MEMORY` is set + +Shared, code-grounded memory across the swarm. All calls fail-open (`|| true`) — +if `kypp` is not on PATH, skip them. The project is pre-scoped via env (`KYPP_PROJECT`), +so no `--project` flag is needed. + +```bash +kypp briefing # session start: pitfalls + decisions, no query +kypp recall "" # before work: one line per claim, with handles +kypp show # dereference one claim you intend to act on +kypp remember "" "" # after work: store a distilled, durable lesson +``` + +Protocol: **briefing** once at start → **recall** before non-trivial work → +**remember** durable lessons (incl. pitfalls) before release. Trust `👤`/`☑` +claims over your own inference. Write model-agnostic lessons, not transcripts. + ## Rules 1. **Never cd** into a workspace directory @@ -199,10 +261,11 @@ bacchus handle clear # cleanup 3. **Stay within your declared footprint** — verify before releasing 4. Send **heartbeats** during long work 5. **Always call `bacchus archetype prompt`** during context loading -6. **Always run `/simplify`** in the review loop — every iteration +6. **Always run `/tighten`** in the review loop (every iteration) and `/ship-review` once before releasing as `done` 7. **Describe changes** before releasing 8. **Don't mark `done`** if review hasn't passed or tests fail 9. Check context for **collision warnings** before starting 10. **Never run `bun install` / `npm install` / `pnpm install`** — orchestrator handles this 11. **Release as `blocked`** when you need out-of-footprint changes — don't proceed anyway -12. **Message the orchestrator** when releasing as blocked or failed with details \ No newline at end of file +12. **Message the orchestrator** when releasing as blocked or failed with details +13. **When `$BACCHUS_MEMORY` is set:** `kypp briefing` at start, `kypp recall` before work, `kypp remember` durable lessons before release — all fail-open \ No newline at end of file diff --git a/src/quality.rs b/src/quality.rs index f5c2cee..a29ed12 100644 --- a/src/quality.rs +++ b/src/quality.rs @@ -17,6 +17,19 @@ pub struct BacchusConfig { pub quality: QualitySection, #[serde(default)] pub worker: WorkerSection, + #[serde(default)] + pub memory: MemorySection, +} + +/// kypp shared-memory integration (briefing/recall/remember for workers). +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct MemorySection { + /// Enable kypp integration: scope worker env to a kypp project so + /// `kypp briefing/recall/remember` bind the right store. + #[serde(default)] + pub enabled: bool, + /// kypp project key (KYPP_PROJECT). Defaults to the project directory name. + pub project: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -92,6 +105,28 @@ pub fn load_config(workspace_root: &Path) -> Option { serde_yaml::from_str(&content).ok() } +/// Resolve kypp env for a worker: `(KYPP_PROJECT, KYPP_REPO_ROOT)`. +/// +/// Returns `None` when memory is disabled. The project key is the explicit +/// `memory.project`, else the workspace directory name (used verbatim as the +/// kypp binding key). Code grounding (`KYPP_REPO_ROOT`) points at the canonical +/// project tree, not the ephemeral per-task workspace. +pub fn resolve_memory_env( + config: &BacchusConfig, + workspace_root: &Path, +) -> Option<(String, String)> { + if !config.memory.enabled { + return None; + } + let project = config.memory.project.clone().unwrap_or_else(|| { + workspace_root + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_else(|| "default".to_string()) + }); + Some((project, workspace_root.to_string_lossy().to_string())) +} + /// Run all configured quality gate commands against the workspace path. /// /// Commands run sequentially with cwd set to `workspace_path`. @@ -276,6 +311,10 @@ pub fn generate_config(workspace_root: &Path) -> String { } yaml.push_str("\nworker:\n"); yaml.push_str(" cmd: \"claude --dangerously-skip-permissions -p '/bacchus-worker $BACCHUS_AGENT_ID $BACCHUS_TASK_ID'\"\n"); + yaml.push_str("\n# Shared memory via kypp (briefing/recall/remember). Requires `kypp` on PATH.\n"); + yaml.push_str("# memory:\n"); + yaml.push_str("# enabled: true\n"); + yaml.push_str("# project: \"my-project\" # KYPP_PROJECT; defaults to this directory's name\n"); yaml } @@ -523,6 +562,7 @@ mod tests { lint: None, }, worker: WorkerSection::default(), + memory: MemorySection::default(), }; let result = run_quality_gate(&config, dir.path()).unwrap(); assert!(result.passed); @@ -539,6 +579,7 @@ mod tests { lint: Some("true".to_string()), }, worker: WorkerSection::default(), + memory: MemorySection::default(), }; let result = run_quality_gate(&config, dir.path()).unwrap(); assert!(!result.passed); @@ -548,6 +589,46 @@ mod tests { assert!(!result.checks[1].passed); } + #[test] + fn test_resolve_memory_env_disabled_by_default() { + let config = BacchusConfig { + quality: QualitySection::default(), + worker: WorkerSection::default(), + memory: MemorySection::default(), + }; + assert!(resolve_memory_env(&config, Path::new("/tmp/my-proj")).is_none()); + } + + #[test] + fn test_resolve_memory_env_derives_project_from_dir() { + let config = BacchusConfig { + quality: QualitySection::default(), + worker: WorkerSection::default(), + memory: MemorySection { + enabled: true, + project: None, + }, + }; + let (project, repo_root) = + resolve_memory_env(&config, Path::new("/tmp/my-proj")).unwrap(); + assert_eq!(project, "my-proj"); + assert_eq!(repo_root, "/tmp/my-proj"); + } + + #[test] + fn test_resolve_memory_env_explicit_project_wins() { + let config = BacchusConfig { + quality: QualitySection::default(), + worker: WorkerSection::default(), + memory: MemorySection { + enabled: true, + project: Some("custom-key".to_string()), + }, + }; + let (project, _) = resolve_memory_env(&config, Path::new("/tmp/my-proj")).unwrap(); + assert_eq!(project, "custom-key"); + } + #[test] fn test_truncate_output() { assert_eq!(truncate_output("short", 100), "short"); diff --git a/src/tools/eval.rs b/src/tools/eval.rs index f4913f6..01473db 100644 --- a/src/tools/eval.rs +++ b/src/tools/eval.rs @@ -305,10 +305,8 @@ pub fn generate_eval_report(epic_id: Option<&str>, days: i64) -> Result { metrics.worker_exit_ignored += 1; } - "worker_exited" => { - if payload["fenced"].as_bool().unwrap_or(false) { - metrics.fenced_worker_exits += 1; - } + "worker_exited" if payload["fenced"].as_bool().unwrap_or(false) => { + metrics.fenced_worker_exits += 1; } _ => {} } diff --git a/src/tools/list.rs b/src/tools/list.rs index f2b1f79..cf15645 100644 --- a/src/tools/list.rs +++ b/src/tools/list.rs @@ -73,7 +73,7 @@ pub fn list_claims() -> Result { // Sort by age (most recent first) let mut sorted_claims = claims; - sorted_claims.sort_by(|a, b| a.age_minutes.cmp(&b.age_minutes)); + sorted_claims.sort_by_key(|c| c.age_minutes); let (claims, stale_claims): (Vec<_>, Vec<_>) = sorted_claims .into_iter() diff --git a/src/tools/session/workers.rs b/src/tools/session/workers.rs index 4dba344..72d95d2 100644 --- a/src/tools/session/workers.rs +++ b/src/tools/session/workers.rs @@ -914,6 +914,19 @@ pub fn run_worker_command( cmd.env("BACCHUS_EVENT_PORT", port.to_string()); } + // Scope kypp shared memory to this project when enabled, so the worker's + // `kypp briefing/recall/remember` calls bind the right store. Fail-open: if + // kypp is not installed the worker prompt's memory steps simply no-op. + if let Some(config) = crate::quality::load_config(&workspace_root) { + if let Some((project, repo_root)) = + crate::quality::resolve_memory_env(&config, &workspace_root) + { + cmd.env("KYPP_PROJECT", project) + .env("KYPP_REPO_ROOT", repo_root) + .env("BACCHUS_MEMORY", "1"); + } + } + let output = cmd.output().map_err(|e| e.to_string())?; let exit_code = output.status.code(); From afd372a419ee8119b377a5271bf094d24cfbb31d Mon Sep 17 00:00:00 2001 From: vu1n <2105991+vu1n@users.noreply.github.com> Date: Tue, 9 Jun 2026 13:08:52 +0700 Subject: [PATCH 2/2] feat: support codex as a worker runner The worker engine was already runner-agnostic (worker.cmd run via sh -c), but codex couldn't follow the protocol: /bacchus-worker is a Claude slash command, and there was no way to feed the protocol to a CLI that takes a prompt string. Add first-class codex support via `codex exec`. - `worker.runner` config (claude|codex) selects the default worker.cmd; `cmd` still overrides. Derivation is gated on `runner` being explicitly set, so an unconfigured worker still errors rather than silently defaulting to claude. - `bacchus worker-prompt [TASK_ID]` emits the worker protocol as plain text for `codex exec` (Claude resolves the slash command). - `bacchus init --runner ` writes the matching cmd; the Runner clap enum rejects invalid values at parse time. - Bundle tighten + ship-review under skills/ (the review loop depends on them; already present as Claude and Codex skills globally). Liveness stays bacchus-owned (heartbeat loop), not a Claude hook, so codex workers stay alive identically. --- CLAUDE.md | 3 ++ README.md | 31 +++++++++++++- skills/ship-review/SKILL.md | 65 +++++++++++++++++++++++++++++ skills/tighten/SKILL.md | 42 +++++++++++++++++++ src/cli/mod.rs | 33 ++++++++++++++- src/main.rs | 5 +++ src/quality.rs | 83 ++++++++++++++++++++++++++++++++----- src/tools/init.rs | 30 ++++++++++++-- src/tools/mod.rs | 2 +- src/tools/session/config.rs | 59 +++++++++++++++++++++++++- 10 files changed, 336 insertions(+), 17 deletions(-) create mode 100644 skills/ship-review/SKILL.md create mode 100644 skills/tighten/SKILL.md diff --git a/CLAUDE.md b/CLAUDE.md index c53915a..8d872e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -184,7 +184,10 @@ quality: lint: "cargo clippy --quiet -- -D warnings" worker: + runner: "claude" # "claude" (default) or "codex"; selects the default cmd cmd: "claude --dangerously-skip-permissions -p '/bacchus-worker $BACCHUS_AGENT_ID $BACCHUS_TASK_ID'" + # cmd overrides runner. Codex runner default (set via `bacchus init --runner codex`): + # cmd: "codex exec --dangerously-bypass-approvals-and-sandbox \"$(bacchus worker-prompt $BACCHUS_AGENT_ID $BACCHUS_TASK_ID)\"" # auto_spawn: true # Enable auto-spawn (default: true) # retry_backoff_ms: 60000 # max_retries: 3 diff --git a/README.md b/README.md index 7d78b1e..c36ea8f 100644 --- a/README.md +++ b/README.md @@ -415,6 +415,35 @@ bacchus session spawn-workers --count 3 # Then run `bacchus session check` in your stop-hook loop ``` +### Worker Runners (Claude or Codex) + +The worker is just a shell command (`worker.cmd`) that bacchus runs per task with +env vars injected (`$BACCHUS_AGENT_ID`, `$BACCHUS_TASK_ID`, …) — it is not tied to +Claude. The `worker.runner` config field selects the default command: + +| Runner | Default `worker.cmd` | +|--------|----------------------| +| `claude` (default) | `claude --dangerously-skip-permissions -p '/bacchus-worker $BACCHUS_AGENT_ID $BACCHUS_TASK_ID'` | +| `codex` | `codex exec --dangerously-bypass-approvals-and-sandbox "$(bacchus worker-prompt $BACCHUS_AGENT_ID $BACCHUS_TASK_ID)"` | + +Pick one at init time: + +```bash +bacchus init --runner codex # writes a codex worker.cmd into .bacchus/config.yaml +``` + +Claude resolves the `/bacchus-worker` slash command from the installed skill. Codex +has no slash command, so `codex exec` is fed the protocol as plain text via +`bacchus worker-prompt [TASK_ID]` (the same protocol, runner-agnostic). +Set `worker.runner: codex` (and leave `cmd` unset) to derive the codex command, or +set `cmd` explicitly to override. Liveness is bacchus-owned (the heartbeat loop), +not a Claude hook, so codex workers stay alive the same way. + +The review loop calls the `/tighten` and `/ship-review` skills — install these for +your runner (both ship as Claude **and** Codex skills; bacchus bundles copies under +`skills/`). `codex exec` requires the [Codex CLI](https://grok-wiki.com/public/docs/openai-codex-c82680b15ec1) +on `PATH`. + ## Commands ### Task Management @@ -688,7 +717,7 @@ Only one orchestrator can hold the leader lease at a time; secondary orchestrato Autonomous worker spawning controls: - `BACCHUS_ORCHESTRATOR_AUTO_SPAWN=1` (default) enables auto-spawn attempts during `session check`. -- `BACCHUS_WORKER_CMD` sets the worker shell command (required for auto-spawn). +- `BACCHUS_WORKER_CMD` sets the worker shell command (required for auto-spawn); overrides `worker.runner`/`worker.cmd`. See Worker Runners for the Claude vs Codex defaults. - `BACCHUS_WORKER_MAX_RETRIES` limits retries per task (default: `3`). - `BACCHUS_WORKER_RETRY_BACKOFF_MS` sets retry backoff (default: `60000`). - `BACCHUS_WORKER_STALE_GRACE_MS` extends stale-worker recovery grace beyond claim timeout (default: `60000`). diff --git a/skills/ship-review/SKILL.md b/skills/ship-review/SKILL.md new file mode 100644 index 0000000..4f67e10 --- /dev/null +++ b/skills/ship-review/SKILL.md @@ -0,0 +1,65 @@ +--- +name: ship-review +description: Pre-ship deep review pass. Runs the ambitious structural quality review (thermo-nuclear, advisory) then bug review (code-review) on the settled diff, with a human checkpoint between. Use once before opening a PR. Invoke for "ship review", "deep review before PR", "review before shipping". +disable-model-invocation: true +--- + +# Ship Review + +The heavier, pre-ship review pass. Run this once before opening a PR — not every iteration (use `tighten` for per-round cleanups). + +Three lenses, in order, with a human checkpoint between structure and the rest: + +1. **Structural quality** (advisory, ambitious) — what to restructure. +2. **Correctness** (review) — bugs in the code you are actually keeping. +3. **Security** (advisory) — exploitability of the settled diff. + +The order matters: settle the structure first, then review the final shape for bugs and exploits, so you are not reviewing code you are about to delete. + +## Workflow + +### Phase 1 — Structural quality (advisory) + +Invoke `thermo-nuclear-code-quality-review`. It produces ambitious, behavior-adjacent restructuring recommendations (code-judo, deleting layers, re-abstracting), prioritized by structural impact. + +### Phase 1b — Refute the top structural findings + +Ambitious restructure suggestions are exactly the plausible-but-wrong risk: the model proposes a "code-judo" move that doesn't actually exist or quietly changes behavior. Before presenting anything, refute the **top findings** (say, the 3-5 highest-impact, plus any whose restructure spans more than one module). + +For each, spawn an independent skeptic — `subagent_type: "general-purpose"`, all in one message, **never fork**. A fork inherits the proposer's reasoning and rubber-stamps it; the point is a cold read that checks the claim against the source. Give each skeptic only the finding (location + the proposed move) and read-only repo access. Each answers: + +- **Does the move exist?** Are the pieces it assumes (the helper to reuse, the seam to collapse, the branches that "disappear") actually there in the code? +- **Is it behavior-preserving?** Name one input or path where the restructured version would differ. If you can name one, the move is unsound as stated. +- **Does it actually delete complexity**, or just relocate it? + +Verdict per finding: `holds` / `unsound` / `needs author input`, one line citing `file:line`. Drop or down-rank the `unsound` ones; tag the survivors with what the skeptic confirmed. + +Present the surviving findings. **Do not auto-apply them** — these are behavior-adjacent and ambitious. + +### Phase 2 — Checkpoint + +Stop and let the user pick which restructures to take. Apply only the selected ones. If the user takes none, proceed. + +If meaningful restructures were applied, the diff has changed — Phases 3 and 4 review the new shape. + +### Phase 3 — Correctness (review) + +Invoke `/code-review` on the settled diff. This is the bug pass: correctness, regressions, edge cases. Run it after the checkpoint so it reviews the code being kept, including anything the Phase 2 restructure introduced. + +### Phase 4 — Security (advisory) + +Invoke `security-pass` on the settled diff. This is the exploitability pass: recall-first finders, then fresh-context refuters, then precondition-derived severity. Keep it separate from Phase 3 — correctness asks "is this wrong?", security asks "can an attacker abuse this?". Advisory, like Phase 1: report, don't auto-fix. + +## Boundaries + +- Phases 1 and 4 are advisory — never apply their suggestions without the checkpoint / a separate fix task. +- Keep the lenses separate. Don't let the structural pass hunt bugs, the bug pass redesign architecture, or the security pass restructure; each is sharper focused. +- Assume `tighten` (deslop + simplify) already ran this round, so local slop and trivial cleanups are out of scope here. + +## Output + +- Phase 1/1b: prioritized structural findings (the code-judo move, and what the refute pass confirmed or killed). +- Phase 2: which restructures were applied. +- Phase 3: bug findings by severity (critical / warning / note). +- Phase 4: confirmed security findings (HIGH/MEDIUM/LOW) and what was dropped. +- Overall ship-readiness. diff --git a/skills/tighten/SKILL.md b/skills/tighten/SKILL.md new file mode 100644 index 0000000..e37587e --- /dev/null +++ b/skills/tighten/SKILL.md @@ -0,0 +1,42 @@ +--- +name: tighten +description: Per-iteration code-tightening pass optimized for an AI-maintained codebase. Strips slop (deslop), applies local simplifications (simplify), then invests context the next agent needs (contextualize). Use after a round of iteration to keep the working tree tight before continuing. Invoke for "tighten", "tighten this up", "clean pass". +disable-model-invocation: true +--- + +# Tighten + +Fast, mutating cleanup pass to run after a round of iteration so you are not building on slop. Cheap and local — no bug hunting, no ambitious restructuring. Those belong to `ship-review`. + +This codebase is primarily read and written by AI agents, so the goal is not human visual polish — it is **low-friction context for the next agent**: high signal-per-token, machine-checkable guardrails, and intent that survives a cold session. That means both *removing* noise and *adding* the things an agent needs. + +Three stages on the **quality axis only**. All mutate the working tree. + +## Workflow + +1. **deslop (subtractive)** — Invoke the `deslop` skill. Strip noise that costs tokens without adding signal: what-comments, `any`-casts, silent catch-and-ignore, gratuitous nesting, dead code. Protects why-comments, explicit types, and loud guards. +2. **simplify (local cleanup)** — Invoke the `/simplify` skill. Apply local reuse/dedup/efficiency/altitude cleanups on the now-deslopped diff. +3. **contextualize (additive)** — Invest the context the next agent needs, only where it is genuinely missing: + - Add a **why-comment** where intent or a non-obvious constraint isn't recoverable from the code alone. Skip the obvious. + - **Tighten loose types** — replace a surviving `any`/`unknown`/over-wide type with the real shape; make a boundary contract explicit. + - Convert a **silent fallback into a loud guard** (`assert`/validation) where a violated invariant should fail fast rather than limp on. + - Drop a one-line **breadcrumb at a module boundary** when behavior isn't explained end-to-end locally. + +Run in order: deslop removes noise so simplify reasons over cleaner code, and contextualize adds signal last so it isn't immediately stripped. + +## Scope + +- Operate on the current branch diff vs base, plus uncommitted changes. +- Keep behavior unchanged (loud guards may *surface* a latent bug — that is acceptable and worth flagging). +- Prefer minimal, focused edits over broad rewrites. Additions are cheap context, not documentation theater — if a comment restates the code, it is slop, not context. + +## Boundaries + +- Do **not** hunt for bugs — that is `/code-review`'s job, run pre-ship via `ship-review`. +- Do **not** make ambitious structural/architectural restructures — that is `thermo-nuclear-code-quality-review`'s job, also pre-ship. +- If you notice a real bug or a large structural smell, **note it for `ship-review`** rather than acting on it here. + +## Output + +- One concise summary (1-3 sentences): what was stripped, simplified, and what context was added. +- A short list of anything deferred to `ship-review` (bugs spotted, structural smells, invariants a new guard surfaced). diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 9b35cee..ac295ff 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1,5 +1,5 @@ use crate::tools::{ReleaseStatus, SessionMode}; -use clap::{Parser, Subcommand}; +use clap::{Parser, Subcommand, ValueEnum}; #[derive(Parser)] #[command( @@ -12,6 +12,23 @@ pub struct Cli { pub command: Commands, } +/// Agent runtime that executes worker tasks. Closed set so `--runner` rejects typos. +#[derive(Clone, Copy, Debug, ValueEnum)] +pub enum Runner { + Claude, + Codex, +} + +impl Runner { + /// Config token written to `worker.runner` and matched by `default_cmd_for_runner`. + pub fn as_str(self) -> &'static str { + match self { + Runner::Claude => "claude", + Runner::Codex => "codex", + } + } +} + #[derive(Subcommand)] pub enum Commands { /// Find next ready task, create workspace, and claim it @@ -93,6 +110,20 @@ pub enum Commands { epic_id: Option, #[arg(long, requires = "epic_id")] epic_title: Option, + /// Worker runner to configure (claude or codex) + #[arg(long, value_enum, default_value = "claude")] + runner: Runner, + }, + + /// Print the worker-agent protocol prompt as plain text. + /// + /// For non-Claude runners (e.g. `codex exec`) that take a prompt string + /// instead of resolving the `/bacchus-worker` slash command. + WorkerPrompt { + /// Agent ID + agent_id: String, + /// Task ID (optional; omit to auto-pick the next ready task) + task_id: Option, }, /// Search indexed symbols diff --git a/src/main.rs b/src/main.rs index 62bf5e8..5b61fa8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -158,6 +158,7 @@ fn main() { force_tasks, epic_id, epic_title, + runner, } => to_json(tools::init_workspace( &workspace_root, tools::InitOptions { @@ -165,8 +166,12 @@ fn main() { force_tasks, epic_id: epic_id.as_deref(), epic_title: epic_title.as_deref(), + runner: runner.as_str(), }, )), + Commands::WorkerPrompt { agent_id, task_id } => Ok(Output::Raw( + tools::render_worker_prompt(&agent_id, task_id.as_deref()), + )), Commands::Symbols { pattern, kind, diff --git a/src/quality.rs b/src/quality.rs index a29ed12..560c9c1 100644 --- a/src/quality.rs +++ b/src/quality.rs @@ -34,8 +34,11 @@ pub struct MemorySection { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WorkerSection { - /// Worker command (e.g., "claude") + /// Worker command (e.g., "claude"). Overrides the runner default when set. pub cmd: Option, + /// Runner family: "claude" (default) or "codex". Selects the default worker + /// command when `cmd` is unset. See `default_cmd_for_runner`. + pub runner: Option, /// Whether auto-spawn is enabled (overrides env var) #[serde(default = "default_true")] pub auto_spawn: bool, @@ -60,6 +63,7 @@ impl Default for WorkerSection { fn default() -> Self { Self { cmd: None, + runner: None, auto_spawn: true, retry_backoff_ms: None, max_retries: None, @@ -296,8 +300,28 @@ pub fn format_gate_failures(gate: &QualityGateResult) -> String { // Config Generation (for bacchus init) // ============================================================================ +/// Default worker command for a runner family. A `cmd` set in config overrides this. +/// +/// - `codex` runs headless via `codex exec`, fed the protocol prompt that +/// `bacchus worker-prompt` emits (codex has no `/bacchus-worker` slash command). +/// - anything else (incl. `None`) defaults to the Claude Code slash-command worker. +pub fn default_cmd_for_runner(runner: Option<&str>) -> String { + match runner { + // `run_worker_command` substitutes $BACCHUS_AGENT_ID/$BACCHUS_TASK_ID before + // `sh -c`, so the command substitution runs with concrete IDs. The double + // quotes keep the prompt (which itself contains $BACCHUS_* and backticks) as + // one un-re-expanded argument to `codex exec`. + Some("codex") => "codex exec --dangerously-bypass-approvals-and-sandbox \ + \"$(bacchus worker-prompt $BACCHUS_AGENT_ID $BACCHUS_TASK_ID)\"" + .to_string(), + _ => "claude --dangerously-skip-permissions -p \ + '/bacchus-worker $BACCHUS_AGENT_ID $BACCHUS_TASK_ID'" + .to_string(), + } +} + /// Detect project type and generate default config YAML content (quality + worker sections). -pub fn generate_config(workspace_root: &Path) -> String { +pub fn generate_config(workspace_root: &Path, runner: &str) -> String { let (check, test, lint) = detect_project_commands(workspace_root); let mut yaml = String::from("quality:\n"); if let Some(c) = check { @@ -310,11 +334,18 @@ pub fn generate_config(workspace_root: &Path) -> String { yaml.push_str(&format!(" lint: \"{}\"\n", l)); } yaml.push_str("\nworker:\n"); - yaml.push_str(" cmd: \"claude --dangerously-skip-permissions -p '/bacchus-worker $BACCHUS_AGENT_ID $BACCHUS_TASK_ID'\"\n"); - yaml.push_str("\n# Shared memory via kypp (briefing/recall/remember). Requires `kypp` on PATH.\n"); + yaml.push_str(&format!(" runner: \"{}\"\n", runner)); + // YAML double-quoted scalar: escape embedded quotes (the codex cmd uses them). + let cmd = default_cmd_for_runner(Some(runner)).replace('"', "\\\""); + yaml.push_str(&format!(" cmd: \"{}\"\n", cmd)); + yaml.push_str( + "\n# Shared memory via kypp (briefing/recall/remember). Requires `kypp` on PATH.\n", + ); yaml.push_str("# memory:\n"); yaml.push_str("# enabled: true\n"); - yaml.push_str("# project: \"my-project\" # KYPP_PROJECT; defaults to this directory's name\n"); + yaml.push_str( + "# project: \"my-project\" # KYPP_PROJECT; defaults to this directory's name\n", + ); yaml } @@ -501,19 +532,52 @@ mod tests { "[package]\nname = \"test\"\n", ) .unwrap(); - let yaml = generate_config(dir.path()); + let yaml = generate_config(dir.path(), "claude"); assert!(yaml.contains("cargo check")); assert!(yaml.contains("cargo test")); assert!(yaml.contains("cargo clippy")); assert!(yaml.contains("worker:")); + assert!(yaml.contains("runner: \"claude\"")); assert!(yaml.contains("cmd: \"claude --dangerously-skip-permissions -p")); } + #[test] + fn test_generate_config_codex_runner() { + let dir = tempdir().unwrap(); + std::fs::write( + dir.path().join("Cargo.toml"), + "[package]\nname = \"test\"\n", + ) + .unwrap(); + let yaml = generate_config(dir.path(), "codex"); + assert!(yaml.contains("runner: \"codex\"")); + // The emitted scalar must escape the inner double quotes (the codex cmd + // wraps the prompt in `"$(...)"`), or YAML parsing truncates the value. + assert!( + yaml.contains(r#"cmd: "codex exec --dangerously-bypass-approvals-and-sandbox \"$("#) + ); + + // Round-trip: the YAML-escaped cmd must parse back to the EXACT command, + // inner `"$(bacchus worker-prompt ...)"` quotes intact. This pins the + // `.replace('"', "\\\"")` escaping in generate_config. + let bacchus_dir = dir.path().join(".bacchus"); + std::fs::create_dir_all(&bacchus_dir).unwrap(); + std::fs::write(bacchus_dir.join("config.yaml"), &yaml).unwrap(); + let cfg = load_config(dir.path()).unwrap(); + assert_eq!(cfg.worker.runner.as_deref(), Some("codex")); + assert_eq!( + cfg.worker.cmd.as_deref(), + Some(default_cmd_for_runner(Some("codex")).as_str()) + ); + let cmd = cfg.worker.cmd.unwrap(); + assert!(cmd.contains(r#""$(bacchus worker-prompt $BACCHUS_AGENT_ID $BACCHUS_TASK_ID)""#)); + } + #[test] fn test_generate_config_node() { let dir = tempdir().unwrap(); std::fs::write(dir.path().join("package.json"), "{}").unwrap(); - let yaml = generate_config(dir.path()); + let yaml = generate_config(dir.path(), "claude"); assert!(yaml.contains("tsc --noEmit")); assert!(yaml.contains("vitest")); assert!(yaml.contains("cmd: \"claude --dangerously-skip-permissions -p")); @@ -523,7 +587,7 @@ mod tests { fn test_generate_config_go() { let dir = tempdir().unwrap(); std::fs::write(dir.path().join("go.mod"), "module test\n").unwrap(); - let yaml = generate_config(dir.path()); + let yaml = generate_config(dir.path(), "claude"); assert!(yaml.contains("go build")); assert!(yaml.contains("go test")); assert!(yaml.contains("cmd: \"claude --dangerously-skip-permissions -p")); @@ -609,8 +673,7 @@ mod tests { project: None, }, }; - let (project, repo_root) = - resolve_memory_env(&config, Path::new("/tmp/my-proj")).unwrap(); + let (project, repo_root) = resolve_memory_env(&config, Path::new("/tmp/my-proj")).unwrap(); assert_eq!(project, "my-proj"); assert_eq!(repo_root, "/tmp/my-proj"); } diff --git a/src/tools/init.rs b/src/tools/init.rs index d85fcce..b872bf8 100644 --- a/src/tools/init.rs +++ b/src/tools/init.rs @@ -73,6 +73,21 @@ pub struct InitOptions<'a> { pub force_tasks: bool, pub epic_id: Option<&'a str>, pub epic_title: Option<&'a str>, + /// Worker runner family to write into config.yaml ("claude" or "codex"). + pub runner: &'a str, +} + +/// Render the worker-agent protocol prompt with concrete IDs substituted. +/// +/// Claude resolves the `/bacchus-worker` slash command from the installed skill; +/// other runners (e.g. `codex exec`) take a prompt string, which this emits by +/// filling the protocol's `$ARGUMENTS` placeholder. +pub fn render_worker_prompt(agent_id: &str, task_id: Option<&str>) -> String { + let arguments = match task_id { + Some(t) => format!("{} {}", agent_id, t), + None => agent_id.to_string(), + }; + CMD_WORKER.replace("$ARGUMENTS", &arguments) } #[derive(Debug, Clone, Serialize, Default)] @@ -450,14 +465,14 @@ fn ensure_worker_hooks(workspace_root: &Path, force: bool) -> Result<(bool, bool } /// Install project config to .bacchus/config.yaml with project-detected defaults (quality + worker) -fn ensure_config(workspace_root: &Path) -> Result<(bool, bool), String> { +fn ensure_config(workspace_root: &Path, runner: &str) -> Result<(bool, bool), String> { let path = workspace_root.join(".bacchus/config.yaml"); if path.exists() { return Ok((false, true)); // (created, already_exists) } - let content = crate::quality::generate_config(workspace_root); + let content = crate::quality::generate_config(workspace_root, runner); fs::write(&path, content).map_err(|e| e.to_string())?; Ok((true, false)) } @@ -639,7 +654,7 @@ pub fn init_workspace( claude.claude_md_updated = updated; claude.claude_md_already_has_pointer = already_has; - let (created, exists) = ensure_config(workspace_root)?; + let (created, exists) = ensure_config(workspace_root, options.runner)?; claude.config_created = created; claude.config_already_exists = exists; @@ -691,6 +706,7 @@ mod tests { force_tasks: false, epic_id: None, epic_title: None, + runner: "claude", }, ) .unwrap(); @@ -704,6 +720,7 @@ mod tests { force_tasks: false, epic_id: None, epic_title: None, + runner: "claude", }, ) .unwrap(); @@ -731,6 +748,7 @@ mod tests { force_tasks: true, epic_id: None, epic_title: None, + runner: "claude", }, ) .unwrap(); @@ -754,6 +772,7 @@ mod tests { force_tasks: false, epic_id: None, epic_title: None, + runner: "claude", }, ) .unwrap(); @@ -783,6 +802,7 @@ mod tests { force_tasks: false, epic_id: None, epic_title: None, + runner: "claude", }, ) .unwrap(); @@ -797,6 +817,7 @@ mod tests { force_tasks: false, epic_id: None, epic_title: None, + runner: "claude", }, ) .unwrap(); @@ -828,6 +849,7 @@ mod tests { force_tasks: false, epic_id: None, epic_title: None, + runner: "claude", }, ) .unwrap(); @@ -859,6 +881,7 @@ mod tests { force_tasks: false, epic_id: Some("INIT-EPIC"), epic_title: Some("Init Epic"), + runner: "claude", }, ) .unwrap(); @@ -871,6 +894,7 @@ mod tests { force_tasks: false, epic_id: Some("INIT-EPIC"), epic_title: Some("Init Epic"), + runner: "claude", }, ) .unwrap(); diff --git a/src/tools/mod.rs b/src/tools/mod.rs index 9f9f04a..8f152c0 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -76,7 +76,7 @@ pub use claim::claim_task; pub use clean::clean_workspace; pub use context::generate_context; pub use eval::generate_eval_report; -pub use init::{init_workspace, update_assets, InitOptions}; +pub use init::{init_workspace, render_worker_prompt, update_assets, InitOptions}; pub use list::list_claims; pub use next::next_task; pub use orchestrator::{process_ready_releases, verify_release_invariants}; diff --git a/src/tools/session/config.rs b/src/tools/session/config.rs index e0402e2..3f73679 100644 --- a/src/tools/session/config.rs +++ b/src/tools/session/config.rs @@ -106,7 +106,17 @@ pub(super) fn resolve_worker_config( .ok() .map(|v| v.trim().to_string()) .filter(|v| !v.is_empty()) - .or_else(|| yaml_worker.as_ref().and_then(|w| w.cmd.clone())), + .or_else(|| yaml_worker.as_ref().and_then(|w| w.cmd.clone())) + // No explicit cmd: derive a default only when `runner` is explicitly + // set. With neither configured, leave cmd None so the + // "worker.cmd is not configured" gate still fires (rather than + // silently defaulting to claude). + .or_else(|| { + yaml_worker + .as_ref() + .and_then(|w| w.runner.as_deref()) + .map(|r| crate::quality::default_cmd_for_runner(Some(r))) + }), auto_spawn: if std::env::var("BACCHUS_ORCHESTRATOR_AUTO_SPAWN").is_ok() { env_bool("BACCHUS_ORCHESTRATOR_AUTO_SPAWN", true) @@ -139,3 +149,50 @@ pub(super) fn resolve_worker_config( }, } } + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + fn write_config(dir: &Path, body: &str) { + let bacchus = dir.join(".bacchus"); + std::fs::create_dir_all(&bacchus).unwrap(); + std::fs::write(bacchus.join("config.yaml"), body).unwrap(); + } + + #[test] + fn cmd_stays_none_when_neither_cmd_nor_runner_set() { + std::env::remove_var("BACCHUS_WORKER_CMD"); + let dir = tempfile::tempdir().unwrap(); + // A worker section without cmd or runner must NOT silently default to + // claude — the "worker.cmd is not configured" gate has to keep firing. + write_config(dir.path(), "worker:\n max_retries: 5\n"); + let wcfg = resolve_worker_config(Some(dir.path())); + assert!(wcfg.cmd.is_none()); + } + + #[test] + fn cmd_derived_from_runner_when_explicitly_set() { + std::env::remove_var("BACCHUS_WORKER_CMD"); + let dir = tempfile::tempdir().unwrap(); + write_config(dir.path(), "worker:\n runner: \"codex\"\n"); + let wcfg = resolve_worker_config(Some(dir.path())); + assert_eq!( + wcfg.cmd.as_deref(), + Some(crate::quality::default_cmd_for_runner(Some("codex")).as_str()) + ); + } + + #[test] + fn explicit_cmd_overrides_runner() { + std::env::remove_var("BACCHUS_WORKER_CMD"); + let dir = tempfile::tempdir().unwrap(); + write_config( + dir.path(), + "worker:\n runner: \"codex\"\n cmd: \"my-runner\"\n", + ); + let wcfg = resolve_worker_config(Some(dir.path())); + assert_eq!(wcfg.cmd.as_deref(), Some("my-runner")); + } +}