@caddis/cli 0.4.111 → 0.4.112

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 (24) hide show
  1. package/bundles/antigravity-plugin/plugin.json +1 -1
  2. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  3. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  4. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/caddis_guide.json +2 -2
  14. package/bundles/antigravity-plugin/scripts/caddis_lanes.py +72 -2
  15. package/bundles/antigravity-plugin/scripts/caddis_review.py +4 -3
  16. package/bundles/antigravity-plugin/scripts/caddis_spend.py +11 -5
  17. package/bundles/antigravity-plugin/scripts/oss_review.py +312 -132
  18. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +8 -8
  19. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +3 -4
  20. package/bundles/antigravity-plugin/skills/implement/SKILL.md +2 -2
  21. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  22. package/bundles/antigravity-plugin-extras/skills/agent-orchestration/SKILL.md +2 -2
  23. package/bundles/manifest.json +3 -3
  24. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "caddis",
3
- "version": "1.3.195",
3
+ "version": "1.3.196",
4
4
  "description": "caddis — agent-agnostic dev harness as an Antigravity (agy) plugin: TDD skills + commands, single-sourced with the Claude Code plugin."
5
5
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "1.3.194",
4
- "generated": "2026-11-13 01:10 UTC",
3
+ "version": "1.3.195",
4
+ "generated": "2026-11-13 03:53 UTC",
5
5
  "commands": [
6
6
  {
7
7
  "name": "add-rules",
@@ -947,7 +947,70 @@ def _kill_tree(proc: subprocess.Popen) -> None:
947
947
  proc.kill()
948
948
 
949
949
 
950
- def run_review(worktree: Path, env: dict, timeout_s: int = LANE_REVIEW_TIMEOUT_S) -> ReviewResult:
950
+ # The lane's review author, as `oss_review.py --author` names it. The reviewer comes from the author's vendor:
951
+ # the review never runs on the vendor that wrote the code. `claude` has no entry: no `--author` keeps the default chain.
952
+ LANE_AUTHOR = {"agy": "agy", "glm": "glm", "codex-sol": "codex", "codex-astra": "codex"}
953
+
954
+ _REVIEW_TIERS = ("0", "1-small", "1", "2")
955
+
956
+
957
+ def _untracked_files(worktree: Path) -> list[Path]:
958
+ """Untracked, not-ignored files in `worktree` (`git ls-files --others --exclude-standard`), relative paths.
959
+ Raises on a git failure: the caller counts that as tier 2."""
960
+ res = subprocess.run(["git", "-C", str(worktree), "ls-files", "-z", "--others", "--exclude-standard"],
961
+ capture_output=True, timeout=60, check=True)
962
+ return [Path(p) for p in res.stdout.decode("utf-8", errors="replace").split("\0") if p]
963
+
964
+
965
+ def _file_lines(path: Path, binary_lines: int) -> int:
966
+ """Changed lines a new file adds: its line count, or `binary_lines` for a binary file."""
967
+ data = path.read_bytes()
968
+ if b"\0" in data:
969
+ return binary_lines
970
+ return data.count(b"\n") + (1 if data and not data.endswith(b"\n") else 0)
971
+
972
+
973
+ def _review_tier(worktree: Path, base_sha: str, runner=subprocess.run, untracked=_untracked_files) -> str:
974
+ """The review tier for the lane's change, from `caddis_gate.py review-tier`. Any failure gives "2".
975
+
976
+ The range is `base_sha` alone, not `base_sha..HEAD`: the lane review runs only while HEAD is still the base,
977
+ so `base_sha..HEAD` is always empty. `git diff <base_sha>` compares the worktree with the base.
978
+ `git diff` does not see untracked new files, so when one is not a tier-0 path the tier is computed again by
979
+ the gate's own `review_tier` over the tracked numstat plus (path, line count) of each untracked file."""
980
+ gate = Path(__file__).with_name("caddis_gate.py")
981
+ argv = [sys.executable, str(gate), "review-tier", "--range", base_sha, "--repo-root", str(worktree)]
982
+ try:
983
+ proc = runner(argv, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60)
984
+ except (OSError, subprocess.SubprocessError):
985
+ return "2"
986
+ if proc.returncode != 0:
987
+ return "2"
988
+ tier = "2"
989
+ for line in _as_text(proc.stdout).splitlines():
990
+ if line.startswith("TIER:"):
991
+ tier = line.split(":", 1)[1].strip()
992
+ tier = tier if tier in _REVIEW_TIERS else "2"
993
+ break
994
+ if tier == "2":
995
+ return tier
996
+ try:
997
+ new_files = untracked(worktree)
998
+ if not new_files:
999
+ return tier
1000
+ gate_mod = _load_file_module("_caddis_gate_for_lanes", gate)
1001
+ posix = [p.as_posix() for p in new_files]
1002
+ if all(gate_mod.is_tier0_file(p) for p in posix):
1003
+ return tier
1004
+ files = gate_mod._numstat(base_sha, worktree)
1005
+ files += [(p, _file_lines(worktree / rel, gate_mod.BINARY_LINES)) for p, rel in zip(posix, new_files)]
1006
+ combined = gate_mod.review_tier(files)
1007
+ except Exception: # noqa: BLE001 - a change we cannot measure is reviewed in full
1008
+ return "2"
1009
+ return combined if combined in _REVIEW_TIERS else "2"
1010
+
1011
+
1012
+ def run_review(worktree: Path, env: dict, timeout_s: int = LANE_REVIEW_TIMEOUT_S,
1013
+ author: str | None = None, tier: str = "1") -> ReviewResult:
951
1014
  fake_review = _review_fake()
952
1015
  if fake_review:
953
1016
  return ReviewResult(fake_review, 0 if fake_review == "CLEAN" else 1, f"fake review: {fake_review}")
@@ -961,6 +1024,8 @@ def run_review(worktree: Path, env: dict, timeout_s: int = LANE_REVIEW_TIMEOUT_S
961
1024
  group = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if sys.platform == "win32"
962
1025
  else {"start_new_session": True})
963
1026
  argv = [sys.executable, str(path), "--cwd", str(worktree)]
1027
+ if author:
1028
+ argv += ["--author", author, "--tier", tier]
964
1029
  try:
965
1030
  proc = subprocess.Popen(
966
1031
  argv,
@@ -2062,7 +2127,12 @@ def _run_post_checks(
2062
2127
  # No review: it would cover only the uncommitted part and could print CLEAN over the commit.
2063
2128
  review = ReviewResult("COMMITTED", None, committed)
2064
2129
  else:
2065
- review = run_review(worktree, dict(os.environ))
2130
+ review = run_review(
2131
+ worktree,
2132
+ dict(os.environ),
2133
+ author=LANE_AUTHOR.get(str(packet.get("lane") or "")), # no lane: no author, the default chain
2134
+ tier=_review_tier(worktree, str(packet["base_sha"])),
2135
+ )
2066
2136
  review_s = time.monotonic() - review_started
2067
2137
  pythons = list(before)
2068
2138
  if pythons:
@@ -687,8 +687,9 @@ def _claude_exe() -> str | None:
687
687
  return _find_on_path("claude")
688
688
 
689
689
 
690
- def launch_claude(prompt: str, worktree: Path, out: Path) -> str:
691
- """One review run: `claude -p` in `worktree`, the prompt on stdin. Writes the masked output to `out`, returns it.
690
+ def launch_claude(prompt: str, worktree: Path, out: Path, model: str = "opus", effort: str | None = None) -> str:
691
+ """One review run: `claude -p --model <model>` (plus `--effort <effort>` when set) in `worktree`, the prompt
692
+ on stdin. Writes the masked output to `out`, returns it.
692
693
  A timeout, a start failure or a non-zero exit returns a `caddis_review: ` line first, which makes the run NOT_RUN."""
693
694
  # Read only: `--tools` gives Read, Grep and Glob and nothing else (no Bash, no Edit); dontAsk refuses any other
694
695
  # call and no prompt waits (`--permission-prompts none`). `--restricted` ignores the settings files (no settings
@@ -712,7 +713,7 @@ def launch_claude(prompt: str, worktree: Path, out: Path) -> str:
712
713
  out.parent.mkdir(parents=True, exist_ok=True)
713
714
  out.write_text(output, encoding="utf-8")
714
715
  return output
715
- cmd = [exe, "-p", "--model", "opus", "--restricted",
716
+ cmd = [exe, "-p", "--model", model, *(["--effort", effort] if effort else []), "--restricted",
716
717
  "--tools", ",".join(REVIEWER_TOOLS), "--permission-mode", "dontAsk", "--permission-prompts", "none",
717
718
  "--strict-mcp-config", "--disable-slash-commands",
718
719
  "--output-format", "json", "--max-budget-usd", str(MAX_BUDGET_USD)]
@@ -187,16 +187,16 @@ def _locked(home: Path):
187
187
 
188
188
 
189
189
  def json_mode(argv: list[str]) -> bool:
190
- """True only when the command has exactly ONE output-format flag and its value is `json`
191
- (`--output-format json` or `--output-format=json`). A second flag could switch agy to text, where the
192
- model's own lines could pose as a usage document."""
190
+ """True only when the command has exactly ONE output-format flag and its value is `json` or `stream-json`
191
+ (`--output-format json`, `--output-format=stream-json`, ...). A second flag could switch agy to text, where
192
+ the model's own lines could pose as a usage document."""
193
193
  values = []
194
194
  for i, arg in enumerate(argv):
195
195
  if arg == "--output-format":
196
196
  values.append(argv[i + 1] if i + 1 < len(argv) else "")
197
197
  elif arg.startswith("--output-format="):
198
198
  values.append(arg.split("=", 1)[1])
199
- return values == ["json"]
199
+ return values in (["json"], ["stream-json"])
200
200
 
201
201
 
202
202
  def _read(home: Path) -> list[dict]:
@@ -302,7 +302,9 @@ def settle(home: Path, rid: str, tokens: tuple[int, int] | None, now: datetime,
302
302
 
303
303
 
304
304
  def _agy_document(stdout: str) -> dict | None:
305
- """agy's own JSON document from `agy --output-format json` (sample: scripts/tests/fixtures/agy-json-sample.json).
305
+ """agy's own JSON document from `agy --output-format json` (sample: scripts/tests/fixtures/agy-json-sample.json),
306
+ or the `result` of the last `"event": "result"` line from `--output-format stream-json`
307
+ (sample: scripts/tests/fixtures/agy-stream-json-sample.ndjson).
306
308
 
307
309
  The document may follow other lines (on Windows the governor writes `[caddis-governor] scope=...` first,
308
310
  and run_lane merges stderr into stdout), and agy pretty-prints it over several lines. So: try every `{`
@@ -319,6 +321,10 @@ def _agy_document(stdout: str) -> dict | None:
319
321
  obj, _end = decoder.raw_decode(text, start)
320
322
  except json.JSONDecodeError:
321
323
  continue
324
+ # stream-json (`--output-format stream-json`): one event per line; the `"event": "result"` line holds
325
+ # the same document under `result`. The reply is an escaped string inside a line, as in json mode.
326
+ if isinstance(obj, dict) and obj.get("event") == "result" and isinstance(obj.get("result"), dict):
327
+ obj = obj["result"]
322
328
  if isinstance(obj, dict) and {"status", "response", "usage"} <= obj.keys():
323
329
  found = obj
324
330
  return found
@@ -57,6 +57,12 @@ the same run. agy runs through `caddis_spend.py run` (usage log, timeout, depth
57
57
  the prompt (no tools needed). The secret filter runs once, before any provider, agy included. The
58
58
  provider that gave each verdict is printed.
59
59
 
60
+ Reviewer chosen by author (owner decision, 12-13 Nov 2026): `--author <a> --tier <t>` builds the chain from
61
+ review_order(a, t) (agy-written code -> claude-sonnet, claude-opus at tier 2; Claude-written code -> agy-carbon).
62
+ A reviewer of the author's vendor never runs: an explicit --provider of that vendor exits 3 ("same-vendor
63
+ review refused"), a REVIEW_PROVIDER of that vendor (env or keys file) is dropped with a note, and the built
64
+ chain is filtered once more. No --author keeps the order above.
65
+
60
66
  Diff-size ceiling: an oversized diff sent to a chat-completions endpoint has been observed, live, to
61
67
  come back two different unsafe ways — an empty `content` field on an HTTP 200 (at least fails closed:
62
68
  no verdict line ⇒ exit 4), and, worse, a `REVIEW: CLEAN` verdict with no substantive engagement (a
@@ -68,11 +74,8 @@ narrower case: a SINGLE file larger than the ceiling, which cannot be split, or
68
74
  MAX_REVIEW_BATCHES. Refusal was the original behaviour and is kept for those two - a silent false
69
75
  CLEAN is the worst outcome this tool has - but it no longer fires on an ordinary large phase diff.
70
76
 
71
- agy limit: when agy-carbon is anywhere in the provider chain, each batch is ALSO packed so its whole
72
- prompt (fixed text, the file list of a multi-batch run, the diff) fits AGY_MAX_PROMPT_CHARS (28,000)
73
- as quoted on the command line, so batches are smaller (under about 27,000 diff chars; fewer when the diff has many `"`). A single file
74
- whose prompt cannot fit gets its own batch: agy skips it and the next provider reviews it; with no
75
- other provider that is exit 3. With no agy in the chain the 60,000 ceiling alone applies.
77
+ agy gets the prompt on stdin (stream-json), not on the command line, so agy batches follow the same
78
+ ceiling as every other provider.
76
79
 
77
80
  Stdlib-only (urllib) so it runs anywhere with no pip install.
78
81
  """
@@ -80,12 +83,14 @@ from __future__ import annotations
80
83
 
81
84
  import argparse
82
85
  import http.client
86
+ import importlib.util
83
87
  import json
84
88
  import os
85
89
  import shutil
86
90
  import signal
87
91
  import subprocess
88
92
  import sys
93
+ import tempfile
89
94
  import time
90
95
  import urllib.error
91
96
  import urllib.request
@@ -146,18 +151,54 @@ REVIEW_ORDER: tuple[str, ...] = (AGY_PROVIDER, "deepseek", "glm")
146
151
  # agy runs headless through caddis_spend.py run: plan mode (it needs no tools, the diff is in the prompt).
147
152
  AGY_MODEL = "gemini-4-carbon-medium" # owner, 12 Nov 2026; -high stalls past agy's 5-min stream idle timeout on reviews
148
153
  AGY_TIMEOUT_S = 15 * 60
149
- # The prompt is one command-line argument (`--print=<prompt>`). A Windows command line holds at most
150
- # 32,767 characters, so a larger prompt skips agy instead of failing to start. The limit applies to the
151
- # argument AS QUOTED (`agy_prompt_chars`): quoting escapes every `"`, so a diff of string literals costs more
152
- # than len(prompt). Each hop (oss_review -> caddis_spend -> caddis_hidden_desktop -> agy) quotes the same
153
- # argument once, not nested, so the cost is the same at every hop. The 4,767 chars left over hold the rest of
154
- # the longest command line: python, two script paths, the agy path and the fixed flags.
155
- WINDOWS_CMDLINE_MAX = 32_767
156
- AGY_MAX_PROMPT_CHARS = 28_000
154
+ # The prompt goes on stdin as one stream-json user event, never on the command line: a Windows command line
155
+ # holds at most 32,767 chars, and `--print=<prompt>` made batches shrink for agy. Verified live 13 Nov 2026 with a
156
+ # 40,000-char prompt. `--print=` must be empty and last; caddis_spend and caddis_hidden_desktop pass stdin through.
157
+ AGY_STREAM_FLAGS = ("--input-format", "stream-json", "--output-format", "stream-json")
157
158
  # `caddis_spend.py run` refusal code: 75 = headless depth at its limit, or the usage log could not be locked or
158
159
  # written. Never agy's own. (78 "cap not configured" is gone with the cap, 1 Nov 2026.)
159
160
  SPEND_REFUSED = (75,)
160
161
 
162
+ # Claude reviewers: `claude -p` through caddis_review.launch_claude (governor, depth guard, redaction), never a
163
+ # raw call. Provider name -> the `--model` alias. Only when named: the default chain (REVIEW_ORDER) has no Claude
164
+ # entry, because the default author is Claude. A vendored copy of this tool without caddis_review.py skips them.
165
+ CLAUDE_PROVIDERS: dict[str, str] = {"claude-sonnet": "sonnet", "claude-opus": "opus"}
166
+ CLAUDE_EFFORT = "high"
167
+ # `--author` and `--tier` choices. Only tier "2" changes the order (see review_order).
168
+ AUTHORS: tuple[str, ...] = ("agy", "claude", "opus", "sonnet", "haiku", "glm", "deepseek", "codex")
169
+ TIERS: tuple[str, ...] = ("0", "1-small", "1", "2")
170
+
171
+ # Reviewer chosen by author (owner decision, 12-13 Nov 2026): a vendor never reviews its own code.
172
+ # Keys: every `--author` choice and every provider name. "openrouter" is its own vendor: it is never in an order.
173
+ VENDOR_OF: dict[str, str] = {
174
+ "claude": "anthropic", "opus": "anthropic", "sonnet": "anthropic", "haiku": "anthropic",
175
+ "claude-sonnet": "anthropic", "claude-opus": "anthropic",
176
+ "agy": "google", "agy-carbon": "google", "agy-carbon-medium": "google", "agy-carbon-high": "google",
177
+ "deepseek": "deepseek", "glm": "zhipu", "codex": "openai", "openrouter": "openrouter",
178
+ }
179
+ REVIEW_ORDER_BY_AUTHOR: dict[str, tuple[str, ...]] = {
180
+ "anthropic": REVIEW_ORDER,
181
+ "google": ("claude-sonnet", "deepseek", "glm"),
182
+ }
183
+ _OTHER_VENDOR_ORDER: tuple[str, ...] = (AGY_PROVIDER, "deepseek", "glm", "claude-sonnet")
184
+
185
+
186
+ def review_order(author: str | None, tier: str) -> tuple[str, ...]:
187
+ """The reviewer chain for code written by `author` at review `tier`. No entry shares the author's vendor.
188
+ Tier "2" swaps claude-sonnet for claude-opus. Raises ValueError for an unknown author."""
189
+ if author is None:
190
+ return REVIEW_ORDER_BY_AUTHOR["anthropic"]
191
+ if author not in VENDOR_OF:
192
+ raise ValueError(f"unknown author {author!r}; expected one of {', '.join(sorted(VENDOR_OF))}")
193
+ vendor = VENDOR_OF[author]
194
+ if vendor in REVIEW_ORDER_BY_AUTHOR:
195
+ order = REVIEW_ORDER_BY_AUTHOR[vendor]
196
+ else:
197
+ order = tuple(name for name in _OTHER_VENDOR_ORDER if VENDOR_OF[name] != vendor)
198
+ if tier == "2":
199
+ order = tuple("claude-opus" if name == "claude-sonnet" else name for name in order)
200
+ return order
201
+
161
202
  # On HTTP 429, wait for `Retry-After` once per provider per run, at most this long.
162
203
  RETRY_AFTER_CAP_S = 60.0
163
204
 
@@ -285,14 +326,27 @@ def _parse_keys_file(path: str) -> dict[str, str]:
285
326
  return out
286
327
 
287
328
 
329
+ def named_provider_source(args: argparse.Namespace, env: dict[str, str]) -> tuple[str, str]:
330
+ """(provider, source) the caller chose, or ("", ""). Source: "flag" (--provider), "env" (process env
331
+ REVIEW_PROVIDER) or "keys" (REVIEW_PROVIDER in the keys file, ~/.caddis/keys.env). --author needs the
332
+ source: an explicit flag of the author's vendor is refused, a standing default of that vendor is dropped."""
333
+ if args.provider:
334
+ chosen, source = args.provider, "flag"
335
+ elif env.get("REVIEW_PROVIDER"):
336
+ chosen, source = env["REVIEW_PROVIDER"], "env"
337
+ else:
338
+ chosen = _parse_keys_file(env.get("CADDIS_KEYS_FILE") or DEFAULT_KEYS_FILE).get("REVIEW_PROVIDER")
339
+ source = "keys"
340
+ chosen = (chosen or "").strip().lower()
341
+ if not chosen:
342
+ return "", ""
343
+ return (AGY_PROVIDER if chosen in AGY_OLD_NAMES else chosen), source
344
+
345
+
288
346
  def named_provider(args: argparse.Namespace, env: dict[str, str]) -> str:
289
347
  """The provider the caller chose, or "". Order: --provider flag, process env REVIEW_PROVIDER,
290
348
  REVIEW_PROVIDER in the keys file (~/.caddis/keys.env), so a default is switched with one line there."""
291
- chosen = args.provider or env.get("REVIEW_PROVIDER")
292
- if not chosen:
293
- chosen = _parse_keys_file(env.get("CADDIS_KEYS_FILE") or DEFAULT_KEYS_FILE).get("REVIEW_PROVIDER")
294
- chosen = (chosen or "").strip().lower()
295
- return AGY_PROVIDER if chosen in AGY_OLD_NAMES else chosen
349
+ return named_provider_source(args, env)[0]
296
350
 
297
351
 
298
352
  def resolve_config(
@@ -484,12 +538,9 @@ def changed_paths(diff_text: str) -> list[str]:
484
538
  return paths
485
539
 
486
540
 
487
- def batch_diff(diff_text: str, max_chars: int, fits=None) -> list[str]:
541
+ def batch_diff(diff_text: str, max_chars: int) -> list[str]:
488
542
  """Pack whole files into as few batches as possible, each under `max_chars`.
489
543
 
490
- `fits(batch) -> bool`, when given, is a second test every batch must also pass (main() uses it to keep
491
- each whole agy prompt within the agy command-line limit).
492
-
493
544
  A single file larger than the ceiling gets its own batch and is sent anyway — it is
494
545
  over the limit either way, and reviewing it is strictly better than skipping it. The
495
546
  caller reports how many batches were used so an oversized single file is visible.
@@ -501,7 +552,7 @@ def batch_diff(diff_text: str, max_chars: int, fits=None) -> list[str]:
501
552
  current = ""
502
553
  for chunk in files:
503
554
  candidate = current + chunk
504
- if current and (len(candidate) > max_chars or (fits is not None and not fits(candidate))):
555
+ if current and len(candidate) > max_chars:
505
556
  batches.append(current)
506
557
  current = chunk
507
558
  else:
@@ -638,14 +689,79 @@ def _spend_script() -> Path | None:
638
689
  return None
639
690
 
640
691
 
641
- def agy_launcher() -> list[str] | None:
692
+ def _load_caddis_review():
693
+ """caddis_review as a module: beside this file in a bundle, else the source repo's scripts/ folder (the
694
+ `_spend_script` order). None when it is absent, broken or fails to import: this tool stays one stdlib file,
695
+ and a vendored copy without caddis_review.py only loses the Claude providers.
696
+ sys.path is restored afterwards. caddis_spend (launch_claude's lazy depth guard) is imported while the
697
+ folder is still on the path, so the guard still works after the restore."""
698
+ loaded = sys.modules.get("caddis_review")
699
+ if loaded is not None and callable(getattr(loaded, "launch_claude", None)):
700
+ return loaded
701
+ here = Path(__file__).resolve().parent
702
+ for candidate in (here / "caddis_review.py", here.parents[1] / "scripts" / "caddis_review.py"):
703
+ if not candidate.is_file():
704
+ continue
705
+ saved_path = list(sys.path)
706
+ sys.path.insert(0, str(candidate.parent))
707
+ try:
708
+ spec = importlib.util.spec_from_file_location("caddis_review", candidate)
709
+ if spec is None or spec.loader is None:
710
+ return None
711
+ module = importlib.util.module_from_spec(spec)
712
+ sys.modules["caddis_review"] = module # dataclasses look their module up while it executes
713
+ spec.loader.exec_module(module)
714
+ try:
715
+ import caddis_spend # noqa: F401
716
+ except Exception: # noqa: BLE001 - launch_claude runs without the depth guard, as it does today
717
+ pass
718
+ except Exception: # noqa: BLE001 - a broken file must not stop a review by another provider
719
+ sys.modules.pop("caddis_review", None)
720
+ return None
721
+ finally:
722
+ sys.path[:] = saved_path
723
+ if not callable(getattr(module, "launch_claude", None)) or not callable(
724
+ getattr(module, "_extract_review_text", None)):
725
+ sys.modules.pop("caddis_review", None)
726
+ return None
727
+ return module
728
+ return None
729
+
730
+
731
+ def _claude_available() -> bool:
732
+ """A Claude reviewer can run here: the claude CLI is on PATH AND caddis_review.py loads. The one check for
733
+ the chain, --check-config and an explicit --provider claude-*. The repo always has caddis_review.py, so the
734
+ CLI check is what tells a box without Claude Code apart."""
735
+ return bool(shutil.which("claude")) and _load_caddis_review() is not None
736
+
737
+
738
+ def call_claude(alias: str, prompt: str, cwd: str) -> str:
739
+ """One review by `claude -p --model <alias> --effort high` through caddis_review.launch_claude, in `cwd`.
740
+ A `caddis_review: ` line (timeout, start failure, non-zero exit, no governor, depth limit) or an empty
741
+ review is a ProviderFailure: NOT_RUN, and the chain falls back like any provider failure."""
742
+ module = _load_caddis_review()
743
+ if module is None:
744
+ raise ProviderSkipped("caddis_review.py is not beside this script or in the repo's scripts/ folder")
745
+ prefix = getattr(module, "_PREFIX", "caddis_review: ")
746
+ out = Path(tempfile.gettempdir()) / f"oss-review-{alias}-{os.getpid()}.md"
747
+ output = module.launch_claude(prompt, Path(cwd), out, model=alias, effort=CLAUDE_EFFORT)
748
+ if output.startswith(prefix):
749
+ raise ProviderFailure(output.strip().splitlines()[0])
750
+ text = module._extract_review_text(output)
751
+ if not (text or "").strip():
752
+ raise ProviderFailure(f"claude {alias} returned an empty review")
753
+ return text
754
+
755
+
756
+ def agy_launcher(caller: str = "oss-review") -> list[str] | None:
642
757
  """The command prefix that runs agy through `caddis_spend.py run`, or None when agy or caddis_spend is missing.
758
+ `caller` is the label caddis_spend logs the run under.
643
759
  Every agy call goes through `caddis_spend.py run` (usage log, timeout and depth guard; there is no EUR cap)."""
644
760
  agy = shutil.which("agy")
645
761
  spend = _spend_script()
646
762
  if not agy or spend is None:
647
763
  return None
648
- return [sys.executable, str(spend), "run", "--caller", "oss-review", "--", agy]
764
+ return [sys.executable, str(spend), "run", "--caller", caller, "--", agy]
649
765
 
650
766
 
651
767
  def _kill_tree(proc) -> None:
@@ -659,16 +775,17 @@ def _kill_tree(proc) -> None:
659
775
  proc.kill()
660
776
 
661
777
 
662
- def _run_capped(argv: list[str], timeout: float) -> tuple[int, str, str]:
663
- """Run `argv` with stdin closed; (exit, stdout, stderr). On timeout kill the whole tree and raise
664
- TimeoutError: a killed caddis_spend must not leave agy running on."""
778
+ def _run_capped(argv: list[str], timeout: float, stdin_text: str | None = None) -> tuple[int, str, str]:
779
+ """Run `argv`; (exit, stdout, stderr). stdin carries `stdin_text`, then closes (closed at once when None).
780
+ On timeout kill the whole tree and raise TimeoutError: a killed caddis_spend must not leave agy running on."""
665
781
  group = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt"
666
782
  else {"start_new_session": True})
667
783
  env = {**os.environ, "CADDIS_HEADLESS": "1"}
668
- proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
784
+ stdin = subprocess.DEVNULL if stdin_text is None else subprocess.PIPE
785
+ proc = subprocess.Popen(argv, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
669
786
  text=True, encoding="utf-8", errors="replace", env=env, **group)
670
787
  try:
671
- stdout, stderr = proc.communicate(timeout=timeout)
788
+ stdout, stderr = proc.communicate(input=stdin_text, timeout=timeout)
672
789
  except subprocess.TimeoutExpired:
673
790
  _kill_tree(proc)
674
791
  try:
@@ -682,53 +799,50 @@ def _run_capped(argv: list[str], timeout: float) -> tuple[int, str, str]:
682
799
  return proc.returncode, stdout or "", stderr or ""
683
800
 
684
801
 
685
- def _agy_document(stdout: str) -> dict | None:
686
- """The last agy JSON document (keys status/response) that starts a line of `stdout`.
802
+ def _agy_result(stdout: str) -> dict | None:
803
+ """The `result` object of the LAST stream-json line with `"event":"result"` in `stdout`, else None.
687
804
 
688
- Mirror of scripts/caddis_spend.py::_agy_document, duplicated so this tool stays one stdlib-only file.
689
- A `{` inside the model reply never starts a line of the raw output (it is inside a JSON string)."""
690
- decoder = json.JSONDecoder()
691
- text = stdout or ""
692
- starts = [0] if text.startswith("{") else []
693
- starts += [i + 1 for i, ch in enumerate(text) if ch == "\n" and text[i + 1:i + 2] == "{"]
805
+ agy `--output-format stream-json` writes one JSON event per line; the reply is the last result event:
806
+ {"event":"result","result":{"status":"SUCCESS","response":"...","usage":{...}}}. Other lines (init events,
807
+ `[caddis-governor] ...`) are skipped. The model reply is inside a JSON string, so it cannot pose as a line."""
694
808
  found = None
695
- for start in starts:
809
+ for line in (stdout or "").splitlines():
810
+ line = line.strip()
811
+ if not line.startswith("{"):
812
+ continue
696
813
  try:
697
- obj, _end = decoder.raw_decode(text, start)
814
+ obj = json.loads(line)
698
815
  except json.JSONDecodeError:
699
816
  continue
700
- if isinstance(obj, dict) and {"status", "response"} <= obj.keys():
701
- found = obj
817
+ if isinstance(obj, dict) and obj.get("event") == "result" and isinstance(obj.get("result"), dict):
818
+ found = obj["result"]
702
819
  return found
703
820
 
704
821
 
705
- def agy_prompt_chars(prompt: str) -> int:
706
- """What the prompt costs on the command line: the `--print=<prompt>` argument as subprocess quotes it."""
707
- return len(subprocess.list2cmdline([f"--print={prompt}"]))
822
+ def agy_stdin(prompt: str) -> str:
823
+ """The one stream-json user event agy reads on stdin, then a newline. `message` must be an object."""
824
+ return json.dumps({"event": "user", "message": {"content": prompt}}) + "\n"
708
825
 
709
826
 
710
- def call_agy(launcher: list[str], prompt: str, timeout: float = AGY_TIMEOUT_S) -> str:
711
- """One review by agy Carbon through `caddis_spend.py run` -> the reply text.
827
+ def call_agy(launcher: list[str], prompt: str, timeout: float = AGY_TIMEOUT_S, model: str = AGY_MODEL) -> str:
828
+ """One review by agy Carbon (`model`) through `caddis_spend.py run` -> the reply text.
712
829
 
713
- ProviderSkipped: caddis_spend refused (exit 75), agy is missing, or the prompt is too long for one argument.
714
- ProviderFailure: a non-zero exit, a status other than SUCCESS (ERROR, RESOURCE_EXHAUSTED), no JSON
715
- document, or an empty reply."""
716
- cost = agy_prompt_chars(prompt)
717
- if cost > AGY_MAX_PROMPT_CHARS:
718
- raise ProviderSkipped(f"prompt is {cost:,} chars once quoted, over the {AGY_MAX_PROMPT_CHARS:,}-char "
719
- "agy command-line limit", for_run=False)
720
- argv = [*launcher, "--model", AGY_MODEL, "--mode", "plan", "--output-format", "json",
721
- f"--print={prompt}"]
722
- code, stdout, stderr = _run_capped(argv, timeout)
830
+ The prompt goes on stdin (agy_stdin), never on the command line.
831
+ ProviderSkipped: caddis_spend refused (exit 75) or agy is missing.
832
+ ProviderFailure: a non-zero exit, a status other than SUCCESS (ERROR, RESOURCE_EXHAUSTED), no result
833
+ event, or an empty reply."""
834
+ argv = [*launcher, "--model", model, "--mode", "plan", *AGY_STREAM_FLAGS, "--print="]
835
+ code, stdout, stderr = _run_capped(argv, timeout, stdin_text=agy_stdin(prompt))
723
836
  if code in SPEND_REFUSED:
724
837
  raise ProviderSkipped(f"caddis_spend refused the agy call (exit {code}): "
725
838
  f"{stderr.strip()[-300:]}")
726
839
  if code == 127:
727
840
  raise ProviderSkipped(f"agy could not start: {stderr.strip()[-300:]}")
728
- doc = _agy_document(stdout)
729
- status = str(doc.get("status")) if doc else "no JSON document"
841
+ doc = _agy_result(stdout)
842
+ status = str(doc.get("status")) if doc else "no result event"
730
843
  if code != 0 or status != "SUCCESS":
731
- raise ProviderFailure(f"agy exit {code}, status {status}: {(stderr or stdout).strip()[-300:]}")
844
+ error = f" ({str(doc.get('error'))[:300]})" if doc and doc.get("error") else ""
845
+ raise ProviderFailure(f"agy exit {code}, status {status}{error}: {(stderr or stdout).strip()[-300:]}")
732
846
  response = doc.get("response")
733
847
  if not isinstance(response, str) or not response.strip():
734
848
  raise ProviderFailure("agy returned an empty response")
@@ -784,6 +898,110 @@ def _config_is_changed(diff_text: str) -> bool:
784
898
  return False
785
899
 
786
900
 
901
+ def build_chain(args: argparse.Namespace, env: dict[str, str]) -> list[tuple]:
902
+ """The reviewer chain: [(name, model, where, call(prompt) -> review), ...], first entry first.
903
+
904
+ One resolution for a real run and for --check-config, so "ready" means a real run has a reviewer.
905
+ Raises ConfigError when no reviewer is available, and when an explicit --provider is the author's
906
+ vendor. A same-vendor REVIEW_PROVIDER from the environment or the keys file is dropped with a note."""
907
+ author_vendor = VENDOR_OF[args.author] if args.author else None
908
+ author_order = review_order(args.author, args.tier) if args.author else REVIEW_ORDER
909
+
910
+ def _same_vendor(name: str) -> bool:
911
+ return author_vendor is not None and VENDOR_OF.get(name) == author_vendor
912
+
913
+ def _no_reviewer_for_author() -> str:
914
+ return (f"no non-author reviewer is available for author {args.author} (vendor {author_vendor}); "
915
+ f"the order is {', '.join(author_order)} and a same-vendor review never runs. ")
916
+
917
+ named, named_source = named_provider_source(args, env)
918
+ if named and _same_vendor(named):
919
+ if named_source == "flag":
920
+ raise ConfigError(f"same-vendor review refused: --provider {named} is the vendor of the author "
921
+ f"{args.author} ({author_vendor}). A vendor never reviews its own code; leave "
922
+ f"out --provider to use the order {', '.join(author_order)}.")
923
+ where = "the environment" if named_source == "env" else "the keys file"
924
+ sys.stderr.write(f"[cross-review] note: REVIEW_PROVIDER={named} from {where} is the author's vendor "
925
+ f"({author_vendor}); it is not used for this review.\n")
926
+ named = ""
927
+ # A custom ENDPOINT names exactly who reviews (REVIEW_BASE_URL/REVIEW_MODEL, the documented
928
+ # future-proofing path): it never falls back. A named preset falls back on a provider failure,
929
+ # and the switch is printed, so the reviewer is never misreported.
930
+ custom = bool(args.base_url or env.get("REVIEW_BASE_URL") or args.model or env.get("REVIEW_MODEL"))
931
+ # With nothing named, the default is agy Carbon. A custom endpoint with no provider named is an HTTP
932
+ # call (never agy), keyed as before and labelled "custom" (see below).
933
+ primary_provider = named or (HTTP_DEFAULT_PROVIDER if custom else DEFAULT_PROVIDER)
934
+ agy_cmd = agy_launcher()
935
+
936
+ def _http_entry(name: str, url: str, key: str, mdl: str):
937
+ return (name, mdl, url, lambda prompt: call_llm(url, key, mdl, prompt))
938
+
939
+ def _agy_entry(launcher: list[str]):
940
+ return (AGY_PROVIDER, AGY_MODEL, "caddis_spend run", lambda prompt: call_agy(launcher, prompt))
941
+
942
+ review_cwd = str(Path(args.cwd).resolve())
943
+
944
+ def _claude_entry(name: str):
945
+ alias = CLAUDE_PROVIDERS[name]
946
+ return (name, alias, "claude -p", lambda prompt: call_claude(alias, prompt, review_cwd))
947
+
948
+ if args.author and not named and not custom:
949
+ # Nothing named: the author's order alone builds the chain (the loop below), and its first
950
+ # available entry goes first. An unavailable entry is skipped, never an error.
951
+ chain = []
952
+ elif primary_provider in CLAUDE_PROVIDERS and not custom:
953
+ if not _claude_available():
954
+ raise ConfigError(f"{primary_provider} needs the claude CLI on PATH and caddis_review.py (beside "
955
+ "this script or in the repo's scripts/ folder); one of them is missing here.")
956
+ chain = [_claude_entry(primary_provider)]
957
+ elif primary_provider == AGY_PROVIDER and not custom:
958
+ if agy_cmd is not None:
959
+ chain = [_agy_entry(agy_cmd)]
960
+ elif named:
961
+ raise ConfigError(f"provider {AGY_PROVIDER!r} needs agy on PATH and caddis_spend.py "
962
+ "(beside this script or in the repo's scripts/ folder).")
963
+ else:
964
+ # The default degrades: no agy here, so the chain starts at the next provider with a key.
965
+ chain = []
966
+ else:
967
+ # A custom endpoint with no preset named is labelled "custom": its vendor is unknown, so the
968
+ # same-vendor filter never drops it (the owner named it). Keys resolve as before (the preset default).
969
+ label = named if named in PROVIDERS else ("custom" if custom else primary_provider)
970
+ chain = [_http_entry(label, *resolve_config(args, env, provider=primary_provider))]
971
+ # The rest of the chain in order: REVIEW_ORDER (agy -> DeepSeek -> GLM), or review_order(author, tier)
972
+ # with --author. A provider with no key, agy with no agy on PATH, or a Claude provider with no
973
+ # caddis_review.py is skipped: not an error, just nothing to fall back to.
974
+ if not custom:
975
+ for name in author_order:
976
+ if chain and name == chain[0][0]:
977
+ continue
978
+ if name == AGY_PROVIDER:
979
+ if agy_cmd is not None:
980
+ chain.append(_agy_entry(agy_cmd))
981
+ continue
982
+ if name in CLAUDE_PROVIDERS:
983
+ if _claude_available():
984
+ chain.append(_claude_entry(name))
985
+ continue
986
+ try:
987
+ chain.append(_http_entry(name, *resolve_config(args, env, provider=name, use_overrides=False)))
988
+ except ConfigError:
989
+ continue
990
+ # The same-vendor guard is a final filter on the built chain, so no path above (primary, fallback, a
991
+ # future edit) can put the author's vendor in front of its own code.
992
+ chain = [entry for entry in chain if not _same_vendor(entry[0])]
993
+ if not chain and args.author:
994
+ raise ConfigError(_no_reviewer_for_author()
995
+ + "Make claude (with caddis_review.py), agy or a provider key available, "
996
+ f"e.g. DEEPSEEK_API_KEY in {env.get('CADDIS_KEYS_FILE') or DEFAULT_KEYS_FILE}.")
997
+ if not chain:
998
+ raise ConfigError(
999
+ "no reviewer is available: agy is not on PATH (with caddis_spend.py) and no provider has an "
1000
+ "API key. Set $REVIEW_API_KEY, or add a key such as DEEPSEEK_API_KEY or GLM_API_KEY to "
1001
+ f"{env.get('CADDIS_KEYS_FILE') or DEFAULT_KEYS_FILE}, or install agy.")
1002
+ return chain
1003
+
1004
+
787
1005
  def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> int:
788
1006
  _force_utf8_stdio()
789
1007
  env = os.environ if env is None else env
@@ -792,7 +1010,8 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
792
1010
  help="git range to review (e.g. origin/main..HEAD); default = working tree")
793
1011
  parser.add_argument("--cwd", default=".", help="repo directory (default: cwd)")
794
1012
  parser.add_argument("--provider", default=None,
795
- help=f"preset: {', '.join(sorted(PROVIDERS))} or {AGY_PROVIDER} (default "
1013
+ help=f"preset: {', '.join(sorted(PROVIDERS))}, {AGY_PROVIDER} or "
1014
+ f"{', '.join(CLAUDE_PROVIDERS)} (default "
796
1015
  f"{DEFAULT_PROVIDER}, then the next available provider); env REVIEW_PROVIDER "
797
1016
  f"or REVIEW_PROVIDER in the keys file. "
798
1017
  f"A provider failure falls back in the order {' -> '.join(REVIEW_ORDER)}")
@@ -807,6 +1026,14 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
807
1026
  metavar="GLOB",
808
1027
  help="re-admit a file the secret-filter deny list would otherwise drop "
809
1028
  "(repeatable)")
1029
+ parser.add_argument("--author", default=None, choices=AUTHORS,
1030
+ help="who wrote the change. The chain then follows review_order(author, tier) and a "
1031
+ "reviewer of the author's vendor never runs (an explicit --provider of that vendor "
1032
+ "exits 3). Default: none, the order "
1033
+ f"{' -> '.join(REVIEW_ORDER)}")
1034
+ parser.add_argument("--tier", default="1", choices=TIERS,
1035
+ help="review tier from `caddis_gate.py review-tier` (default 1). Tier 2 gives "
1036
+ "agy-written code claude-opus instead of claude-sonnet")
810
1037
  args = parser.parse_args(argv)
811
1038
 
812
1039
  # --check-config is deliberately NON-INTERACTIVE. This script runs headless — from CI, from a
@@ -817,16 +1044,28 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
817
1044
  if args.check_config:
818
1045
  # agy Carbon is the default reviewer and needs no key: agy on PATH plus caddis_spend.py is enough.
819
1046
  available = ([AGY_PROVIDER] if agy_launcher() is not None else []) + configured_providers(env)
820
- if not available:
821
- sys.stderr.write(
822
- "no second-vendor reviewer is configured: no API key anywhere, and no agy on PATH\n"
823
- " (with caddis_spend.py) for the default agy-carbon reviewer.\n"
824
- " Cross-review needs one — the whole point is a reviewer that does not share this\n"
825
- " model's blind spots, so a same-vendor fallback would be no review at all.\n"
826
- f" Add a key to {env.get('CADDIS_KEYS_FILE') or DEFAULT_KEYS_FILE}, e.g.\n"
827
- " GLM_API_KEY=<your-key>\n")
1047
+ if _claude_available():
1048
+ available += list(CLAUDE_PROVIDERS)
1049
+ # The chain resolution a real run uses, in every case, so "ready" means a real run has a reviewer.
1050
+ try:
1051
+ chain = build_chain(args, env)
1052
+ except ConfigError as exc:
1053
+ if available:
1054
+ sys.stderr.write(f"{exc}\n Providers available here: {', '.join(available)}.\n")
1055
+ else:
1056
+ sys.stderr.write(
1057
+ "no second-vendor reviewer is configured: no API key anywhere, and no agy on PATH\n"
1058
+ " (with caddis_spend.py) for the default agy-carbon reviewer.\n"
1059
+ " Cross-review needs one — the whole point is a reviewer that does not share this\n"
1060
+ " model's blind spots, so a same-vendor fallback would be no review at all.\n"
1061
+ f" Add a key to {env.get('CADDIS_KEYS_FILE') or DEFAULT_KEYS_FILE}, e.g.\n"
1062
+ " GLM_API_KEY=<your-key>\n")
828
1063
  return EXIT_CONFIG
829
- print(f"cross-review is ready. Providers available: {', '.join(available)}")
1064
+ print(f"cross-review is ready. Providers available: {', '.join(available) or 'none (custom endpoint)'}")
1065
+ if args.author:
1066
+ print(f"review order for author {args.author} (tier {args.tier}): "
1067
+ f"{', '.join(review_order(args.author, args.tier))}")
1068
+ print(f"reviewers here, in order: {', '.join(entry[0] for entry in chain)}")
830
1069
  return EXIT_CLEAN
831
1070
 
832
1071
  try:
@@ -870,53 +1109,8 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
870
1109
  scope_line = (f"REVIEW-SCOPE: PARTIAL ({len(dropped)} file(s) excluded by the secret filter: "
871
1110
  f"{', '.join(dropped)})" if dropped else "")
872
1111
 
873
- named = named_provider(args, env)
874
- # A custom ENDPOINT names exactly who reviews (REVIEW_BASE_URL/REVIEW_MODEL, the documented
875
- # future-proofing path): it never falls back. A named preset falls back on a provider failure,
876
- # and the switch is printed, so the reviewer is never misreported.
877
- custom = bool(args.base_url or env.get("REVIEW_BASE_URL") or args.model or env.get("REVIEW_MODEL"))
878
- # With nothing named, the default is agy Carbon. A custom endpoint with no provider named is an HTTP
879
- # call (never agy), keyed and labelled as before.
880
- primary_provider = named or (HTTP_DEFAULT_PROVIDER if custom else DEFAULT_PROVIDER)
881
- agy_cmd = agy_launcher()
882
-
883
- def _http_entry(name: str, url: str, key: str, mdl: str):
884
- return (name, mdl, url, lambda prompt: call_llm(url, key, mdl, prompt))
885
-
886
- def _agy_entry(launcher: list[str]):
887
- return (AGY_PROVIDER, AGY_MODEL, "caddis_spend run", lambda prompt: call_agy(launcher, prompt))
888
-
889
1112
  try:
890
- if primary_provider == AGY_PROVIDER and not custom:
891
- if agy_cmd is not None:
892
- chain = [_agy_entry(agy_cmd)]
893
- elif named:
894
- raise ConfigError(f"provider {AGY_PROVIDER!r} needs agy on PATH and caddis_spend.py "
895
- "(beside this script or in the repo's scripts/ folder).")
896
- else:
897
- # The default degrades: no agy here, so the chain starts at the next provider with a key.
898
- chain = []
899
- else:
900
- chain = [_http_entry(primary_provider, *resolve_config(args, env))]
901
- # The rest of the chain in policy order (agy -> DeepSeek -> GLM). A provider with no key, or
902
- # agy with no agy on PATH, is skipped: not an error, just nothing to fall back to.
903
- if not custom:
904
- for name in REVIEW_ORDER:
905
- if chain and name == chain[0][0]:
906
- continue
907
- if name == AGY_PROVIDER:
908
- if agy_cmd is not None:
909
- chain.append(_agy_entry(agy_cmd))
910
- continue
911
- try:
912
- chain.append(_http_entry(name, *resolve_config(args, env, provider=name, use_overrides=False)))
913
- except ConfigError:
914
- continue
915
- if not chain:
916
- raise ConfigError(
917
- "no reviewer is available: agy is not on PATH (with caddis_spend.py) and no provider has an "
918
- "API key. Set $REVIEW_API_KEY, or add a key such as DEEPSEEK_API_KEY or GLM_API_KEY to "
919
- f"{env.get('CADDIS_KEYS_FILE') or DEFAULT_KEYS_FILE}, or install agy.")
1113
+ chain = build_chain(args, env)
920
1114
  except ConfigError as exc:
921
1115
  sys.stderr.write(f"{exc}\n")
922
1116
  return EXIT_CONFIG
@@ -944,16 +1138,7 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
944
1138
  max_diff_chars = int(env_val) if env_val.isdigit() else DEFAULT_MAX_DIFF_CHARS
945
1139
  branch = current_branch(args.cwd)
946
1140
  whole_change = changed_paths(diff_text)
947
- # With agy in the chain, every batch must also fit agy: the WHOLE prompt (fixed text, the file list of
948
- # a multi-batch run, the diff) as quoted on the command line. Without this, a 36k phase diff was one
949
- # 60k-ceiling batch that agy skipped, and a machine with no other key got exit 3 and no review.
950
- # A single file that cannot fit still gets its own batch: agy skips it, and the next provider reviews it.
951
- agy_in_chain = any(name == AGY_PROVIDER for name, *_ in chain)
952
-
953
- def _fits_agy(batch: str) -> bool:
954
- return agy_prompt_chars(build_review_prompt(batch, branch, args.range, whole_change)) <= AGY_MAX_PROMPT_CHARS
955
-
956
- batches = batch_diff(diff_text, max_diff_chars, _fits_agy if agy_in_chain else None) or [diff_text]
1141
+ batches = batch_diff(diff_text, max_diff_chars) or [diff_text]
957
1142
  # Batching only helps when the diff HAS file boundaries to cut on. A single file (or a
958
1143
  # blob with no `diff --git` headers) larger than the ceiling cannot be split, and sending
959
1144
  # it anyway would reintroduce exactly the silent false-CLEAN the ceiling exists to stop.
@@ -994,17 +1179,12 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
994
1179
  "reporting a verdict that looks whole.\n"
995
1180
  " Narrow --range to a smaller commit span, or raise --max-diff-chars if you know "
996
1181
  "your endpoint's real limit.\n"
997
- + (f" agy-carbon is in the provider chain, so each batch prompt is also kept within "
998
- f"{AGY_MAX_PROMPT_CHARS:,} command-line chars.\n" if agy_in_chain else "")
999
1182
  )
1000
1183
  return EXIT_ERROR
1001
1184
  if len(batches) > 1:
1002
1185
  print(
1003
1186
  f"[cross-review] diff is {len(diff_text):,} chars — reviewing in {len(batches)} batches split on "
1004
- f"file boundaries (ceiling {max_diff_chars:,} diff chars"
1005
- + (f"; agy-carbon is in the chain, so each whole prompt also stays within {AGY_MAX_PROMPT_CHARS:,} "
1006
- "command-line chars" if agy_in_chain else "")
1007
- + "). Verdict is CLEAN only if every batch is clean."
1187
+ f"file boundaries (ceiling {max_diff_chars:,} diff chars). Verdict is CLEAN only if every batch is clean."
1008
1188
  )
1009
1189
 
1010
1190
  # Per run: a provider that failed (429, 5xx, timeout, empty reply, caddis_spend refusal) gets no more calls,
@@ -77,17 +77,17 @@ writes. This line used to prefix the flag itself, which turned that into a doubl
77
77
  /caddis:cross-review -> the working tree, agy Carbon
78
78
  /caddis:cross-review --range main..HEAD -> that range
79
79
  /caddis:cross-review --provider glm -> GLM eyes
80
+ /caddis:cross-review --author agy --tier 2 -> Claude Opus reviews agy-written code
81
+ /caddis:cross-review --author claude -> agy Carbon medium reviews Claude-written code
80
82
  ```
81
83
  Optional: `--base-url <url>`, `--model <id>` (env always overrides the preset).
82
84
 
83
85
  **A large diff is batched, not refused.** Over `REVIEW_MAX_DIFF_CHARS` (default 60,000) the tool splits
84
- on whole-file boundaries and reviews each batch, and the verdict is CLEAN only if every batch is. When agy
85
- Carbon is anywhere in the provider chain, each batch is also kept small enough that its **whole prompt** fits
86
- the agy command line (28,000 chars once quoted, so under about 27,000 diff chars, fewer when the diff has many `"`). A **single file** too
87
- big for agy gets its own batch: agy skips it and the next provider reviews it. With no other provider (no
88
- DeepSeek or GLM key), that file gives exit **3**. Exit **4** means a **single file** over the 60,000 ceiling,
89
- or more batches than the cap. When you see either, review that one file separately (or add a key for an
90
- HTTP provider), not a narrower `--range`; don't raise `--max-diff-chars` blind.
86
+ on whole-file boundaries and reviews each batch, and the verdict is CLEAN only if every batch is. agy gets
87
+ the prompt on stdin (stream-json), not on the command line, so agy batches follow only
88
+ `REVIEW_MAX_DIFF_CHARS`, the same as every other provider. Exit **4** means a **single file** over the
89
+ 60,000 ceiling, or more batches than the cap. When you see it, review that one file separately, not a
90
+ narrower `--range`; don't raise `--max-diff-chars` blind.
91
91
 
92
92
  **The verdict is the last line.** Only the last non-empty line of the reply counts, and it must be
93
93
  exactly `REVIEW: CLEAN` or `REVIEW: BLOCKING`. A reply that quotes the marker earlier and ends some other
@@ -115,7 +115,7 @@ a reason.
115
115
  justify why one is a false positive). Fix it, then re-review only the fix diff. After 3 rounds, ask the owner (rule 3).
116
116
  - **4 — error** → no verdict parsed, or a git/endpoint failure. Read stderr; do NOT treat as clean.
117
117
  - **3 — could not run** → no key (see Prerequisite), the secret filter refused, an explicit `--range` has
118
- no changes, or every provider
118
+ no changes, a same-vendor review refused (`--author` and the chosen provider share a vendor), or every provider
119
119
  failed (429, 5xx, timeout, empty reply). Read stderr. A provider failure is not a verdict: re-run later.
120
120
 
121
121
  ## Three rules: one attempt, one review
@@ -159,10 +159,9 @@ must never ask for CPU burners, stress tests, load tests or "every core". `caddi
159
159
  this wording. The host guard kills runaway agent processes. On 2026-09-13, 32 all-core busy loops
160
160
  froze CI on the dev box.
161
161
 
162
- - **review lane (every phase that touches code)** — cross-vendor review by a vendor that did NOT
163
- write the code: `/caddis:cross-review --range main..HEAD`
164
- (Claude or GLM implemented) or `--provider glm` (DeepSeek-adjacent work). Never same-vendor. Never a
165
- Claude reviewer subagent, unless every other-vendor provider failed; the executor says so in the review file.
162
+ - **review lane (every phase that touches code)** — the reviewer is chosen by the author:
163
+ `/caddis:cross-review --range main..HEAD --author <agy|claude> --tier <TIER>`. Agy-written code gets Claude
164
+ (Sonnet; Opus at tier 2). Claude-written code gets agy Carbon medium. A same-vendor review never runs.
166
165
 
167
166
  **The `Lane:` line is a routing directive read by `/caddis:implement`, not a note.** An interactive
168
167
  session that is handed a phase belonging to another lane spawns that lane rather than absorbing the
@@ -85,8 +85,8 @@ and 95-154 turns per session were started by background events. Each turn re-rea
85
85
  (source checkout: `claude-harness/scripts/caddis_routing.py`). Opus stays for plans, designs and
86
86
  critical-code subagents (`plan-writer`, `critical-phase`).
87
87
  - **Escalation.** Escalate to Opus through a SMALL subagent (by-reference brief, reply ≤ 10 lines), never `/model opus` mid-session (the prompt cache is per model, so a switch at 200k re-writes the whole cache), when: a card fails again after its one fix card; a measurement fails a rule (isolate the cause first, then give the owner options); a plan amendment changes the design, not only facts; a risk-high phase reaches review. A fresh Opus session only to write a new plan or a redesign.
88
- - **One phase review.** Run `/caddis:cross-review --range <base>..HEAD` (one other vendor; agy Carbon by default).
89
- Never use a Claude reviewer subagent. Exception: every other-vendor provider failed. Then say so in the review file.
88
+ - **One phase review.** Run `/caddis:cross-review --range <base>..HEAD --author <Implemented-By of the phase: agy or claude> --tier <TIER>`.
89
+ The reviewer is chosen by the author: agy-written code gets Claude (Sonnet; Opus at tier 2), Claude-written code gets agy Carbon medium. A same-vendor review never runs.
90
90
  - **Mechanical tasks** (literal tests, moves, deletes, renames) go to agy through
91
91
  `python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_spend.py" run --caller lane-pN -- agy ...`.
92
92
  - **Fewer wake-ups.** Run one `ci-watch` per PR head. When it times out on a queued run, watch that run once
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "caddis-extras",
3
- "version": "1.3.53",
3
+ "version": "1.3.54",
4
4
  "description": "caddis-extras — the long-tail skills for the Antigravity (agy) caddis plugin; install alongside caddis for the full set."
5
5
  }
@@ -511,8 +511,8 @@ Invent no new machinery. Everything needed already ships:
511
511
  | Cross-vendor one-shot, no repo context | `/ask-glm` / `/ask-deepseek` |
512
512
  | Per-phase model + lane assignment in a plan | `/caddis:feature-plan` — every phase already carries **Model**, **Lane**, and a cross-review provider |
513
513
 
514
- **Reviewer rule (standing):** the reviewer is always a different vendor than whoever wrote the code.
515
- Claude or GLM implemented → agy Carbon reviews by default (DeepSeek, then GLM, as fallbacks). Never same-vendor.
514
+ **Reviewer rule (standing):** the reviewer is chosen by the author, and is never the same vendor.
515
+ Agy-written code gets Claude (Sonnet; Opus at tier 2). Claude-written code gets agy Carbon medium. Pass `--author` and `--tier` to `/caddis:cross-review`.
516
516
 
517
517
  Full command/billing decision table: `docs/guide/multi-model-workflow.md`.
518
518
 
@@ -1,8 +1,8 @@
1
1
  {
2
- "poolVersion": "1.3.195",
2
+ "poolVersion": "1.3.196",
3
3
  "bundles": {
4
- "antigravity-plugin": "1.3.195",
5
- "antigravity-plugin-extras": "1.3.53",
4
+ "antigravity-plugin": "1.3.196",
5
+ "antigravity-plugin-extras": "1.3.54",
6
6
  "codex": "unknown"
7
7
  }
8
8
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caddis/cli",
3
- "version": "0.4.111",
3
+ "version": "0.4.112",
4
4
  "description": "Install, update and diagnose the caddis dev harness across every coding agent you use (Claude Code, agy/Antigravity, and more).",
5
5
  "keywords": [
6
6
  "caddis",