@caddis/cli 0.4.90 → 0.4.91

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 (34) 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_budget.py +26 -2
  14. package/bundles/antigravity-plugin/scripts/caddis_checkout_guard.py +31 -2
  15. package/bundles/antigravity-plugin/scripts/caddis_docs_pr.py +8 -0
  16. package/bundles/antigravity-plugin/scripts/caddis_guide.json +3 -3
  17. package/bundles/antigravity-plugin/scripts/caddis_handoff.py +73 -45
  18. package/bundles/antigravity-plugin/scripts/caddis_lanes.py +96 -14
  19. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +6 -4
  20. package/bundles/antigravity-plugin/scripts/caddis_workstreams.py +60 -17
  21. package/bundles/antigravity-plugin/scripts/check_doc_coverage.py +17 -0
  22. package/bundles/antigravity-plugin/scripts/oss_review.py +89 -24
  23. package/bundles/antigravity-plugin/scripts/templates/coordinator.md +1 -1
  24. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +17 -4
  25. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +17 -5
  26. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +5 -0
  27. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +12 -2
  28. package/bundles/antigravity-plugin/skills/implement/SKILL.md +4 -1
  29. package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +2 -1
  30. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  31. package/bundles/antigravity-plugin-extras/skills/cross-review/SKILL.md +5 -5
  32. package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +2 -1
  33. package/bundles/manifest.json +3 -3
  34. package/package.json +1 -1
@@ -908,8 +908,47 @@ def oss_review_path() -> Path | None:
908
908
  return source if source.exists() else None
909
909
 
910
910
 
911
- def run_review(worktree: Path, env: dict, timeout_s: int = 900) -> ReviewResult:
912
- fake_review = os.environ.get("CADDIS_REVIEW_FAKE")
911
+ # The lane review timeout. oss_review cannot tell the lane its batch count in advance, so the bound is generous:
912
+ # every batch may take one full agy call, plus a margin for the 429 waits, the HTTP fallbacks and start-up.
913
+ # Mirrors of `.github/tools/oss_review.py` (AGY_TIMEOUT_S, MAX_REVIEW_BATCHES); a test fails if they drift.
914
+ # A timeout before the last batch would always kill a review of 2+ batches (the old 900 s equalled one agy call).
915
+ REVIEW_AGY_CALL_TIMEOUT_S = 15 * 60
916
+ REVIEW_MAX_BATCHES = 12
917
+ REVIEW_TIMEOUT_MARGIN_S = 600
918
+ LANE_REVIEW_TIMEOUT_S = REVIEW_MAX_BATCHES * REVIEW_AGY_CALL_TIMEOUT_S + REVIEW_TIMEOUT_MARGIN_S
919
+ # oss_review prints this line before its verdict when the secret filter dropped files: CLEAN then covers only part.
920
+ _PARTIAL_SCOPE = re.compile(r"(?m)^REVIEW-SCOPE: PARTIAL\b")
921
+
922
+
923
+ def _review_fake() -> str | None:
924
+ """CADDIS_REVIEW_FAKE, honoured only inside a pytest run (pytest sets PYTEST_CURRENT_TEST, and child processes
925
+ inherit it). A copy left exported in a shell would otherwise fake every later real lane review."""
926
+ fake = os.environ.get("CADDIS_REVIEW_FAKE")
927
+ if not fake:
928
+ return None
929
+ if os.environ.get("PYTEST_CURRENT_TEST"):
930
+ return fake
931
+ print("[caddis-lanes] CADDIS_REVIEW_FAKE is ignored outside a pytest run; running the real review",
932
+ file=sys.stderr)
933
+ return None
934
+
935
+
936
+ def _kill_tree(proc: subprocess.Popen) -> None:
937
+ """Kill the child and everything it started (taskkill /T on Windows, the process group on POSIX)."""
938
+ if sys.platform == "win32":
939
+ try:
940
+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True, timeout=15)
941
+ except (OSError, subprocess.TimeoutExpired):
942
+ proc.kill()
943
+ else:
944
+ try:
945
+ os.killpg(proc.pid, signal.SIGKILL)
946
+ except (ProcessLookupError, PermissionError):
947
+ proc.kill()
948
+
949
+
950
+ def run_review(worktree: Path, env: dict, timeout_s: int = LANE_REVIEW_TIMEOUT_S) -> ReviewResult:
951
+ fake_review = _review_fake()
913
952
  if fake_review:
914
953
  return ReviewResult(fake_review, 0 if fake_review == "CLEAN" else 1, f"fake review: {fake_review}")
915
954
 
@@ -917,26 +956,56 @@ def run_review(worktree: Path, env: dict, timeout_s: int = 900) -> ReviewResult:
917
956
  if path is None:
918
957
  return ReviewResult("MISSING", None, "oss_review.py not found")
919
958
 
959
+ # Its own process group (Windows) or session (POSIX): a timeout kills caddis_spend and agy too, not only
960
+ # oss_review, so nothing runs on and spends after the lane gave up.
961
+ group = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if sys.platform == "win32"
962
+ else {"start_new_session": True})
963
+ argv = [sys.executable, str(path), "--cwd", str(worktree)]
920
964
  try:
921
- completed = subprocess.run(
922
- [sys.executable, str(path), "--cwd", str(worktree)],
965
+ proc = subprocess.Popen(
966
+ argv,
923
967
  cwd=worktree,
924
968
  env=env,
925
- capture_output=True,
969
+ stdout=subprocess.PIPE,
970
+ stderr=subprocess.PIPE,
926
971
  text=True,
927
972
  encoding="utf-8",
928
973
  errors="replace",
929
- timeout=timeout_s,
974
+ **group,
930
975
  )
931
- except subprocess.TimeoutExpired as exc:
932
- captured = _as_text(exc.stdout) + _as_text(exc.stderr)
933
- tail = (captured + f"\ntimed out after {timeout_s}s").lstrip("\n")[-3000:]
934
- return ReviewResult("MISSING", None, tail)
935
976
  except OSError as exc:
936
977
  return ReviewResult("MISSING", None, str(exc)[-3000:])
978
+ try:
979
+ stdout, stderr = proc.communicate(timeout=timeout_s)
980
+ except subprocess.TimeoutExpired:
981
+ _kill_tree(proc)
982
+ try:
983
+ stdout, stderr = proc.communicate(timeout=30)
984
+ except subprocess.TimeoutExpired:
985
+ stdout, stderr = "", ""
986
+ captured = _as_text(stdout) + _as_text(stderr)
987
+ tail = (captured + f"\ntimed out after {timeout_s}s; process tree killed").lstrip("\n")[-3000:]
988
+ return ReviewResult("MISSING", None, tail)
937
989
 
938
- status = {0: "CLEAN", 1: "BLOCKING"}.get(completed.returncode, "MISSING")
939
- return ReviewResult(status, completed.returncode, _combined_output(completed)[-3000:])
990
+ output = _combined_output(subprocess.CompletedProcess(argv, proc.returncode, stdout, stderr))
991
+ status = {0: "CLEAN", 1: "BLOCKING"}.get(proc.returncode, "MISSING")
992
+ if status == "CLEAN" and _PARTIAL_SCOPE.search(output):
993
+ status = "PARTIAL"
994
+ return ReviewResult(status, proc.returncode, output[-3000:])
995
+
996
+
997
+ def lane_commit_reason(worktree: Path, branch: str, base_sha: str) -> str:
998
+ """Why the lane worktree holds commits the review did not see, or ''.
999
+
1000
+ The review covers uncommitted work only, and accept merges the whole lane branch. So both the worktree HEAD
1001
+ and the branch tip must still be the base: a new commit, an amended base, or a commit on a detached HEAD
1002
+ (or on the branch before a detach back to the base) all fail one of the two."""
1003
+ head = _git_output(worktree, "rev-parse", "HEAD")
1004
+ tip = _git_output(worktree, "rev-parse", "--verify", f"refs/heads/{branch}")
1005
+ if head == base_sha and tip == base_sha:
1006
+ return ""
1007
+ return (f"the lane committed work that was not reviewed (worktree HEAD {head[:7]}, branch {branch} at "
1008
+ f"{tip[:7]}, base {base_sha[:7]}); the review covers uncommitted work only")
940
1009
 
941
1010
 
942
1011
  def changed_files(worktree: Path) -> list[str]:
@@ -1964,7 +2033,12 @@ def _run_post_checks(
1964
2033
  return "stop", EXIT_NOT_RUN
1965
2034
 
1966
2035
  review_started = time.monotonic()
1967
- review = run_review(worktree, dict(os.environ))
2036
+ committed = lane_commit_reason(worktree, str(packet["branch"]), str(packet["base_sha"]))
2037
+ if committed:
2038
+ # No review: it would cover only the uncommitted part and could print CLEAN over the commit.
2039
+ review = ReviewResult("COMMITTED", None, committed)
2040
+ else:
2041
+ review = run_review(worktree, dict(os.environ))
1968
2042
  review_s = time.monotonic() - review_started
1969
2043
  pythons = list(before)
1970
2044
  if pythons:
@@ -1979,7 +2053,7 @@ def _run_post_checks(
1979
2053
  freeze_unchanged = None
1980
2054
 
1981
2055
  gates_passed = all(gate.passed for gate in gates)
1982
- if gates_passed and freeze_unchanged is not False:
2056
+ if gates_passed and freeze_unchanged is not False and not committed:
1983
2057
  next_step = "review"
1984
2058
  exit_code = EXIT_OK
1985
2059
  else:
@@ -2255,6 +2329,9 @@ def _accept_command(
2255
2329
  if review_status != "CLEAN" and not override_reason:
2256
2330
  if review_status == "BLOCKING":
2257
2331
  print("refusing: review BLOCKING; pass --override-review with a reason")
2332
+ elif review_status == "PARTIAL":
2333
+ print("refusing: review PARTIAL (the secret filter dropped files, so CLEAN covers only part of "
2334
+ "the diff); review the dropped files, or pass --override-review with a reason")
2258
2335
  else:
2259
2336
  # MISSING = no verdict (provider down, 429, secret-filter refusal). Anything else
2260
2337
  # that is not CLEAN (absent, null, unknown, lowercase) is also no valid verdict.
@@ -2272,6 +2349,11 @@ def _accept_command(
2272
2349
 
2273
2350
  wt = _worktree_from_packet(packet)
2274
2351
  _validate_packet_worktree(repo, plan, args.phase, args.attempt, wt)
2352
+ # Not overridable: --override-review accepts a verdict, and no verdict covers a lane commit.
2353
+ committed = lane_commit_reason(wt.path, wt.branch, wt.base_sha)
2354
+ if committed:
2355
+ print(f"refusing: {_printable(committed)}; abandon and redo the phase")
2356
+ return EXIT_FAIL
2275
2357
  files = packet.get("changed_files")
2276
2358
  if not isinstance(files, list) or not files:
2277
2359
  print("refusing: packet has no changed files")
@@ -7,7 +7,8 @@ thin shim over this file. The programme layer (programme folders, ledger, budget
7
7
  One session: stop checks (STOP file, session, hour and dollar caps); for agy, a reservation under the global spend cap
8
8
  (`caddis_spend.py`, settled after the session); read the relay hash; launch ONE session through the governor with the
9
9
  resume prompt and `CADDIS_HEADLESS=1` in its environment; parse its JSON result (cost, error); read the relay status
10
- line; decide. CONTINUE with an unchanged relay is `FAILED no progress`; three sessions in a row with no newly closed
10
+ line; decide. A relay the session did not change (same hash as before it, any status line) is `FAILED no relay
11
+ written`, so a status an earlier session wrote is never acted on again; three sessions in a row with no newly closed
11
12
  row is `BLOCKED stuck`.
12
13
 
13
14
  Plan mode (`--plan <slug>`, decision D-I, design section 8.5) runs `.caddis/plans/<slug>.md`. A closed row in its
@@ -2406,19 +2407,20 @@ def _launch(cmd: list[str], cwd: Path, timeout_s: float, stdin_text: str | None
2406
2407
 
2407
2408
  def _decide(engine: str, outcome: _Outcome, result: dict | None, relay_text: str, hash_before: str | None,
2408
2409
  hash_after: str | None) -> _Stop | None:
2409
- """None to go on; else the stop. A missing or bad status line is FAILED, never CONTINUE (design 8.1)."""
2410
+ """None to go on; else the stop. A missing or bad status line is FAILED, never CONTINUE (design 8.1). A relay
2411
+ this session did not change is FAILED whatever its status: its line belongs to an earlier session (audit 10)."""
2410
2412
  failed = _session_failed(engine, outcome, result)
2411
2413
  if failed is not None:
2412
2414
  return failed
2413
2415
  if hash_after is None:
2414
2416
  return _Stop("FAILED no relay", caddis_exit.BLOCKED)
2417
+ if hash_after == hash_before:
2418
+ return _Stop("FAILED no relay written", caddis_exit.BLOCKED)
2415
2419
  try:
2416
2420
  kind, arg = caddis_workstreams.parse_status(relay_text)
2417
2421
  except ValueError as exc:
2418
2422
  return _Stop(f"FAILED bad status line: {exc}", caddis_exit.BLOCKED)
2419
2423
  if kind == "CONTINUE":
2420
- if hash_after == hash_before:
2421
- return _Stop("FAILED no progress", caddis_exit.BLOCKED)
2422
2424
  return None
2423
2425
  if kind == "FAILED":
2424
2426
  return _Stop(f"FAILED {arg}", caddis_exit.BLOCKED, from_relay=True, status=(kind, arg))
@@ -202,6 +202,27 @@ def _free_backup(path: Path) -> Path:
202
202
  raise ValueError(f"too many backups next to {path.name}")
203
203
 
204
204
 
205
+ def _over_budget(name: str, text: str) -> str | None:
206
+ """The refusal message when ``text`` is over the relay size budget; None when it fits.
207
+
208
+ ``.caddis/relay/`` is git-ignored, so git keeps no history of an old relay: the message says to back up first."""
209
+ if len(text) <= _RELAY_BUDGET_CHARS:
210
+ return None
211
+ return (f"relay rejected: {len(text)} chars is over the {_RELAY_BUDGET_CHARS}-char relay budget. "
212
+ f"Rewrite it to the current state only. Back up the old text first (copy .caddis/relay/{name}.md to "
213
+ f".caddis/relay/{name}.md.bak): .caddis/relay/ is git-ignored, so git keeps no history.")
214
+
215
+
216
+ def _pointer_body(name: str, backup: str) -> str:
217
+ """A short relay body for a migrated relay that is over the budget: the full text stays in ``backup``."""
218
+ return (f"# Relay — {name}\n\n## Current workstream\n"
219
+ f"Migrated from the old relay. It was over the {_RELAY_BUDGET_CHARS}-char relay budget, "
220
+ "so only this pointer is kept here.\n\n"
221
+ f"## Next step (exact)\nRead `.caddis/{backup}` (the full old relay), then rewrite this relay to the "
222
+ "current state only.\n\n"
223
+ f"## Read first on resume\n- `.caddis/{backup}` — the full old relay text\n")
224
+
225
+
205
226
  def _header_text(meta: dict) -> str:
206
227
  """Relay header lines in the shape caddis_frontmatter.parse reads back: scalars, one nested
207
228
  map or one list per key. Every value is folded to one line, so no value can add a field."""
@@ -471,6 +492,11 @@ class MigrationReport(dict):
471
492
  def backups(self) -> list[str]:
472
493
  return self["backups"]
473
494
 
495
+ @property
496
+ def trimmed(self) -> list[str]:
497
+ """Migrated relays that were over the budget and now hold a pointer to the backup."""
498
+ return self.get("trimmed", [])
499
+
474
500
 
475
501
  def _utc_z(value: object = None) -> str:
476
502
  """`value` (an ISO time; naive means UTC) or now, as relay headers write it: UTC, seconds, `Z`.
@@ -542,6 +568,8 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
542
568
 
543
569
  candidates: dict[str, str] = {}
544
570
  conflicts: list[str] = []
571
+ trimmed: list[str] = []
572
+ legacy_bak: Path | None = None
545
573
 
546
574
  # 1. Process legacy relay.md
547
575
  if has_legacy_relay:
@@ -565,14 +593,19 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
565
593
  relay_name = "legacy"
566
594
 
567
595
  candidate_text = raw_relay
596
+ # The full old text is saved here before any relay is written; an oversized relay points to it.
597
+ legacy_bak = _free_backup(artifact / "relay.md.bak")
568
598
  # No header, or an opening --- with no closing one: keep the whole file as the body.
569
599
  header_closed = split_document(candidate_text)[1] != candidate_text
570
600
  if not candidate_text.startswith("---\n") or not header_closed:
571
- candidate_text = (
572
- f"---\ntype: relay\nworkstream: {relay_name}\nbranch: main\n"
573
- f"session_id: legacy-migrated\nplan:\ngenerated:\n by: {_MIGRATED_BY}\n"
574
- f" at: {_utc_z()}\n---\n\n"
575
- f"# Relay — {relay_name}\n\n## Next step (exact)\n{raw_relay}\n"
601
+ head = (f"---\ntype: relay\nworkstream: {relay_name}\nbranch: main\n"
602
+ f"session_id: legacy-migrated\nplan:\ngenerated:\n by: {_MIGRATED_BY}\n"
603
+ f" at: {_utc_z()}\n---\n\n")
604
+ # The old text keeps its own headings, so it gets its own section, not the Next step.
605
+ candidate_text = head + (
606
+ f"# Relay — {relay_name}\n\n## Next step (exact)\n"
607
+ "Read the migrated notes below, then rewrite this relay to the current state only.\n\n"
608
+ f"## Migrated notes\n{raw_relay}\n"
576
609
  )
577
610
  else:
578
611
  meta = parse(candidate_text)
@@ -610,6 +643,11 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
610
643
  _validate_relay(relay_name, candidate_text)
611
644
  except Exception as exc:
612
645
  return MigrationReport(status="conflict", migrated=[], conflicts=[f"invalid-legacy-relay: {exc}"], backups=[])
646
+ if len(candidate_text) > _RELAY_BUDGET_CHARS:
647
+ # Keep the header; the body becomes a pointer. The full text is in the backup, outside the budget scope.
648
+ head = candidate_text[:len(candidate_text) - len(split_document(candidate_text)[1])]
649
+ candidate_text = head.rstrip("\n") + "\n\n" + _pointer_body(relay_name, legacy_bak.name)
650
+ trimmed.append(relay_name)
613
651
 
614
652
  target_path = relay_dir / f"{_name(relay_name)}.md"
615
653
  if target_path.is_file() and not target_path.is_symlink():
@@ -681,6 +719,8 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
681
719
 
682
720
  # Write candidates
683
721
  relay_dir.mkdir(parents=True, exist_ok=True)
722
+ if legacy_bak is not None: # before any relay: a pointer in a relay must never name a missing file
723
+ legacy_bak.write_bytes(index_file.read_bytes())
684
724
  migrated: list[str] = []
685
725
  for name, text in candidates.items():
686
726
  # Locked compare-and-swap on the target: a session that wrote this relay after the
@@ -709,15 +749,13 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
709
749
  legacy_ws.unlink()
710
750
  backups.append(bak_path.name)
711
751
 
712
- if has_legacy_relay:
713
- bak_path = _free_backup(artifact / "relay.md.bak")
714
- bak_path.write_bytes(index_file.read_bytes())
752
+ if legacy_bak is not None: # already saved above; the old relay.md goes now
715
753
  index_file.unlink()
716
- backups.append(bak_path.name)
754
+ backups.append(legacy_bak.name)
717
755
 
718
756
  # Render index outside the lock so render_index can acquire its own lock
719
757
  render_index(root, None, None)
720
- return MigrationReport(status="migrated", migrated=migrated, conflicts=[], backups=backups)
758
+ return MigrationReport(status="migrated", migrated=migrated, conflicts=[], backups=backups, trimmed=trimmed)
721
759
 
722
760
 
723
761
  def main(argv: list[str] | None = None) -> int:
@@ -792,6 +830,10 @@ def main(argv: list[str] | None = None) -> int:
792
830
  elif args.command == "write":
793
831
  content = args.file.read_text(encoding="utf-8")
794
832
  expected = None if args.expected_hash in (None, "none") else args.expected_hash
833
+ refusal = _over_budget(args.name, content)
834
+ if refusal:
835
+ sys.stderr.write(refusal + "\n")
836
+ return 1
795
837
  res = write_relay(args.root, args.name, content, expected)
796
838
  if res.status != "written":
797
839
  # The caller must see what changed; nothing was written.
@@ -842,6 +884,10 @@ def main(argv: list[str] | None = None) -> int:
842
884
  except ValueError as exc:
843
885
  sys.stderr.write(f"cannot read existing relay: {exc}\n")
844
886
  return 1
887
+ refusal = _over_budget(args.name, content)
888
+ if refusal:
889
+ sys.stderr.write(refusal + "\n")
890
+ return 1
845
891
  try:
846
892
  res = write_relay(args.root, args.name, content, expected)
847
893
  except ValueError as exc:
@@ -866,13 +912,10 @@ def main(argv: list[str] | None = None) -> int:
866
912
  print(f"Migration status: {report.status}")
867
913
  for conflict in report.conflicts:
868
914
  print(f" conflict: {conflict}")
869
- # The old relay is kept verbatim, so it can be over the relay budget. Say so once, here;
870
- # caddis_budget.py keeps reporting it until someone trims it.
871
- for name in report.migrated:
872
- size = len(read_relay(args.root, name)[0])
873
- if size > _RELAY_BUDGET_CHARS:
874
- print(f" note: .caddis/relay/{name}.md is {size} chars, over the {_RELAY_BUDGET_CHARS}-char "
875
- "relay budget (the old relay is kept verbatim); trim it to the current state or delete it")
915
+ # An oversized old relay is cut to a pointer; say once where the full text went.
916
+ for name in report.trimmed:
917
+ print(f" note: .caddis/relay/{name}.md was over the {_RELAY_BUDGET_CHARS}-char relay budget, so it holds "
918
+ f"a pointer; the full old text is in .caddis/{report.backups[0]}")
876
919
  return 0 if report.status in ("clean", "migrated") else 1
877
920
  elif args.command == "list":
878
921
  try:
@@ -203,6 +203,21 @@ TRUST_STATUS_VALUES: frozenset[str] = frozenset({
203
203
  "open", "doing", "dropped", # caddis parking-lot (`done` shared above)
204
204
  })
205
205
 
206
+ # Words writers reach for that are not in the vocabulary, mapped to the nearest known word. An explicit map, not
207
+ # fuzzy matching: "in-progress" is not close to "doing" by spelling. `open`/`doing`/`done` are the parking-lot
208
+ # words, `proposed` is the plan word for "written, not yet agreed".
209
+ STATUS_SYNONYMS: dict[str, str] = {
210
+ "in-progress": "doing", "in_progress": "doing", "inprogress": "doing", "in progress": "doing",
211
+ "active": "doing", "wip": "doing", "started": "doing",
212
+ "final": "done", "complete": "done", "completed": "done", "closed": "done", "finished": "done",
213
+ "resolved": "done",
214
+ "todo": "open", "new": "open", "pending": "open", "backlog": "open",
215
+ "planned": "proposed", "proposal": "proposed",
216
+ "cancelled": "dropped", "canceled": "dropped", "abandoned": "dropped", "rejected": "dropped",
217
+ "obsolete": "superseded", "replaced": "superseded",
218
+ "approved": "ready",
219
+ }
220
+
206
221
  _FRONTMATTER_RE = re.compile(r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL)
207
222
  _ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
208
223
  _ISO_DATETIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})?$")
@@ -300,9 +315,11 @@ def trust_signal_warnings(text: str) -> list[str]:
300
315
  # sentence ("DRAFT — approved shape (Option 2), awaiting go"); vetting those would nag
301
316
  # about prose that predates the field's vocabulary. A one-word typo still surfaces.
302
317
  if value and " " not in value and value.lower() not in TRUST_STATUS_VALUES:
318
+ hint = STATUS_SYNONYMS.get(value.lower())
303
319
  warns.append(
304
320
  f"`status: {value}` is not a known value "
305
321
  f"({', '.join(sorted(TRUST_STATUS_VALUES))})"
322
+ + (f"; did you mean `{hint}`?" if hint else "")
306
323
  )
307
324
 
308
325
  if "stale_after" in meta:
@@ -31,13 +31,22 @@ Exit codes (fail-closed):
31
31
  1 REVIEW: BLOCKING — one or more blocking issues
32
32
  2 unused — advisory is not a review verdict
33
33
  3 could not run — REVIEW_API_KEY missing, OR the pre-send secret filter refused (a
34
- denylisted path / possible secret; see secret_filter.py), OR every
34
+ denylisted path / possible secret; see secret_filter.py), OR an explicit
35
+ --range has no changes (a review of nothing is not CLEAN), OR every
35
36
  provider failed with a PROVIDER failure: HTTP 429, any 5xx, a timeout, a
36
- connection error, an empty reply, an agy error status, or the agy spend
37
- cap refused — actionable message on stderr/stdout either way
37
+ connection error, an empty reply, an agy error status, the agy spend
38
+ cap refused, or a one-file prompt too long for agy with no other provider
39
+ — actionable message on stderr/stdout either way
38
40
  4 error — no diff verdict parsed, git failure, other endpoint/parse failure, or the diff
39
41
  exceeds REVIEW_MAX_DIFF_CHARS (see below — never silently downgraded to CLEAN)
40
42
 
43
+ Verdict: only the LAST non-empty line of each reply counts, and it must be exactly `REVIEW: CLEAN` or
44
+ `REVIEW: BLOCKING` (backticks, asterisks and whitespace around it are allowed). Anything else is no
45
+ verdict (exit 4). When the secret filter drops some files, the output ends with
46
+ `REVIEW-SCOPE: PARTIAL (<n> file(s) excluded by the secret filter: <names>)` and then the overall
47
+ `REVIEW:` line. The exit code is unchanged; a caller that needs the whole change reviewed looks
48
+ for that exact text.
49
+
41
50
  Provider chain (owner policy, 2026-10-21; was deepseek first from 2026-10-16): agy-argon -> deepseek -> glm.
42
51
  A named --provider goes first, then the rest in policy order; a provider with no key (or no agy on PATH)
43
52
  is skipped. With no provider named, the chain starts at the first provider that is available. A provider failure
@@ -58,6 +67,12 @@ narrower case: a SINGLE file larger than the ceiling, which cannot be split, or
58
67
  MAX_REVIEW_BATCHES. Refusal was the original behaviour and is kept for those two - a silent false
59
68
  CLEAN is the worst outcome this tool has - but it no longer fires on an ordinary large phase diff.
60
69
 
70
+ agy limit: when agy-argon is anywhere in the provider chain, each batch is ALSO packed so its whole
71
+ prompt (fixed text, the file list of a multi-batch run, the diff) fits AGY_MAX_PROMPT_CHARS (28,000)
72
+ 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
73
+ whose prompt cannot fit gets its own batch: agy skips it and the next provider reviews it; with no
74
+ other provider that is exit 3. With no agy in the chain the 60,000 ceiling alone applies.
75
+
61
76
  Stdlib-only (urllib) so it runs anywhere with no pip install.
62
77
  """
63
78
  from __future__ import annotations
@@ -130,7 +145,12 @@ REVIEW_ORDER: tuple[str, ...] = (AGY_PROVIDER, "deepseek", "glm")
130
145
  AGY_MODEL = "gemini-4-argon-high"
131
146
  AGY_TIMEOUT_S = 15 * 60
132
147
  # The prompt is one command-line argument (`--print=<prompt>`). A Windows command line holds at most
133
- # 32,767 characters, so a larger prompt skips agy instead of failing to start.
148
+ # 32,767 characters, so a larger prompt skips agy instead of failing to start. The limit applies to the
149
+ # argument AS QUOTED (`agy_prompt_chars`): quoting escapes every `"`, so a diff of string literals costs more
150
+ # than len(prompt). Each hop (oss_review -> caddis_spend -> caddis_hidden_desktop -> agy) quotes the same
151
+ # argument once, not nested, so the cost is the same at every hop. The 4,767 chars left over hold the rest of
152
+ # the longest command line: python, two script paths, the agy path and the fixed flags.
153
+ WINDOWS_CMDLINE_MAX = 32_767
134
154
  AGY_MAX_PROMPT_CHARS = 28_000
135
155
  # `caddis_spend.py run` refusal codes: 75 over the cap or no lock, 78 cap not configured. Never agy's own.
136
156
  SPEND_REFUSED = (75, 78)
@@ -460,9 +480,12 @@ def changed_paths(diff_text: str) -> list[str]:
460
480
  return paths
461
481
 
462
482
 
463
- def batch_diff(diff_text: str, max_chars: int) -> list[str]:
483
+ def batch_diff(diff_text: str, max_chars: int, fits=None) -> list[str]:
464
484
  """Pack whole files into as few batches as possible, each under `max_chars`.
465
485
 
486
+ `fits(batch) -> bool`, when given, is a second test every batch must also pass (main() uses it to keep
487
+ each whole agy prompt within the agy command-line limit).
488
+
466
489
  A single file larger than the ceiling gets its own batch and is sent anyway — it is
467
490
  over the limit either way, and reviewing it is strictly better than skipping it. The
468
491
  caller reports how many batches were used so an oversized single file is visible.
@@ -473,11 +496,12 @@ def batch_diff(diff_text: str, max_chars: int) -> list[str]:
473
496
  batches: list[str] = []
474
497
  current = ""
475
498
  for chunk in files:
476
- if current and len(current) + len(chunk) > max_chars:
499
+ candidate = current + chunk
500
+ if current and (len(candidate) > max_chars or (fits is not None and not fits(candidate))):
477
501
  batches.append(current)
478
502
  current = chunk
479
503
  else:
480
- current += chunk
504
+ current = candidate
481
505
  if current:
482
506
  batches.append(current)
483
507
  return batches
@@ -530,7 +554,8 @@ def build_review_prompt(diff_text: str, branch: str, rng: str | None,
530
554
  )
531
555
  return part_note + (
532
556
  f"Perform an adversarial code review of the changes on branch '{branch}' ({scope}). "
533
- "The unified diff is provided below. Judge, in priority order: (1) correctness — logic "
557
+ "The full unified diff is provided below. Do not run any commands or tools: headless "
558
+ "agy auto-denies them and then returns an empty reply. Judge, in priority order: (1) correctness — logic "
534
559
  "bugs, wrong results, missed edge cases; (2) tests — would a test fail without this "
535
560
  "change, and are the stated behaviors covered; (3) security — injection, auth, secret "
536
561
  "exposure, unvalidated input; (4) conventions — the repo's stated rules; (5) simplicity. "
@@ -545,13 +570,16 @@ def build_review_prompt(diff_text: str, branch: str, rng: str | None,
545
570
 
546
571
 
547
572
  def classify_verdict(text: str) -> bool | None:
548
- """CLEAN→True, BLOCKING→False, neither→None. Fail-closed: any blocking signal wins."""
549
- u = text.upper()
550
- if "REVIEW: BLOCKING" in u:
551
- return False
552
- if "REVIEW: CLEAN" in u:
553
- return True
554
- return None
573
+ """CLEAN→True, BLOCKING→False, anything else→None (fail-closed: exit 4).
574
+
575
+ Only the LAST non-empty line counts, as the prompt asks, and it must be exactly `REVIEW: CLEAN` or
576
+ `REVIEW: BLOCKING` (surrounding backticks, asterisks and whitespace are allowed). A substring match
577
+ anywhere counted a reply that QUOTES the marker as a verdict (audit, 29 Oct 2026)."""
578
+ lines = [line for line in (text or "").splitlines() if line.strip()]
579
+ if not lines:
580
+ return None
581
+ last = lines[-1].strip().strip("`*").strip()
582
+ return {"REVIEW: CLEAN": True, "REVIEW: BLOCKING": False}.get(last)
555
583
 
556
584
 
557
585
  def call_llm(base_url: str, api_key: str, model: str, prompt: str, timeout: int = 180) -> str:
@@ -670,14 +698,20 @@ def _agy_document(stdout: str) -> dict | None:
670
698
  return found
671
699
 
672
700
 
701
+ def agy_prompt_chars(prompt: str) -> int:
702
+ """What the prompt costs on the command line: the `--print=<prompt>` argument as subprocess quotes it."""
703
+ return len(subprocess.list2cmdline([f"--print={prompt}"]))
704
+
705
+
673
706
  def call_agy(launcher: list[str], prompt: str, timeout: float = AGY_TIMEOUT_S) -> str:
674
707
  """One review by agy Argon through the spend cap -> the reply text.
675
708
 
676
709
  ProviderSkipped: the cap refused, agy is missing, or the prompt is too long for one argument.
677
710
  ProviderFailure: a non-zero exit, a status other than SUCCESS (ERROR, RESOURCE_EXHAUSTED), no JSON
678
711
  document, or an empty reply."""
679
- if len(prompt) > AGY_MAX_PROMPT_CHARS:
680
- raise ProviderSkipped(f"prompt is {len(prompt):,} chars, over the {AGY_MAX_PROMPT_CHARS:,}-char "
712
+ cost = agy_prompt_chars(prompt)
713
+ if cost > AGY_MAX_PROMPT_CHARS:
714
+ raise ProviderSkipped(f"prompt is {cost:,} chars once quoted, over the {AGY_MAX_PROMPT_CHARS:,}-char "
681
715
  "agy command-line limit", for_run=False)
682
716
  argv = [*launcher, "--model", AGY_MODEL, "--mode", "plan", "--output-format", "json",
683
717
  f"--print={prompt}"]
@@ -826,6 +860,11 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
826
860
  print("REVIEW: REFUSED — every changed file is excluded")
827
861
  return EXIT_CONFIG
828
862
  diff_text = filter_result.kept_diff
863
+ # A verdict on the rest of the change is not a verdict on the whole change. This line goes just before
864
+ # the final `REVIEW:` line. Callers look for this exact text (lanes must not accept a partial review).
865
+ dropped = filter_result.dropped_paths
866
+ scope_line = (f"REVIEW-SCOPE: PARTIAL ({len(dropped)} file(s) excluded by the secret filter: "
867
+ f"{', '.join(dropped)})" if dropped else "")
829
868
 
830
869
  named = named_provider(args, env)
831
870
  # A custom ENDPOINT names exactly who reviews (REVIEW_BASE_URL/REVIEW_MODEL, the documented
@@ -878,6 +917,13 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
878
917
  sys.stderr.write(f"{exc}\n")
879
918
  return EXIT_CONFIG
880
919
 
920
+ if not diff_text.strip() and args.range:
921
+ # An explicit range with no changes is a wrong range far more often than a finished one (for example
922
+ # HEAD..HEAD after a commit). A review of nothing is not CLEAN: could not run.
923
+ sys.stderr.write(f"could not run: the range {args.range} has no changes, so there is nothing to review. "
924
+ "A review of nothing is not CLEAN. Check the range (for example origin/main..HEAD), "
925
+ "or leave out --range to review the working tree.\n")
926
+ return EXIT_CONFIG
881
927
  if not diff_text.strip():
882
928
  # Says what was scanned, not just that nothing was found. This branch used to fire
883
929
  # on a tree full of NEW files (they are invisible to `git diff HEAD`) and report
@@ -892,7 +938,18 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
892
938
  if max_diff_chars is None:
893
939
  env_val = (env.get("REVIEW_MAX_DIFF_CHARS") or "").strip()
894
940
  max_diff_chars = int(env_val) if env_val.isdigit() else DEFAULT_MAX_DIFF_CHARS
895
- batches = batch_diff(diff_text, max_diff_chars) or [diff_text]
941
+ branch = current_branch(args.cwd)
942
+ whole_change = changed_paths(diff_text)
943
+ # With agy in the chain, every batch must also fit agy: the WHOLE prompt (fixed text, the file list of
944
+ # a multi-batch run, the diff) as quoted on the command line. Without this, a 36k phase diff was one
945
+ # 60k-ceiling batch that agy skipped, and a machine with no other key got exit 3 and no review.
946
+ # A single file that cannot fit still gets its own batch: agy skips it, and the next provider reviews it.
947
+ agy_in_chain = any(name == AGY_PROVIDER for name, *_ in chain)
948
+
949
+ def _fits_agy(batch: str) -> bool:
950
+ return agy_prompt_chars(build_review_prompt(batch, branch, args.range, whole_change)) <= AGY_MAX_PROMPT_CHARS
951
+
952
+ batches = batch_diff(diff_text, max_diff_chars, _fits_agy if agy_in_chain else None) or [diff_text]
896
953
  # Batching only helps when the diff HAS file boundaries to cut on. A single file (or a
897
954
  # blob with no `diff --git` headers) larger than the ceiling cannot be split, and sending
898
955
  # it anyway would reintroduce exactly the silent false-CLEAN the ceiling exists to stop.
@@ -933,17 +990,19 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
933
990
  "reporting a verdict that looks whole.\n"
934
991
  " Narrow --range to a smaller commit span, or raise --max-diff-chars if you know "
935
992
  "your endpoint's real limit.\n"
993
+ + (f" agy-argon is in the provider chain, so each batch prompt is also kept within "
994
+ f"{AGY_MAX_PROMPT_CHARS:,} command-line chars.\n" if agy_in_chain else "")
936
995
  )
937
996
  return EXIT_ERROR
938
997
  if len(batches) > 1:
939
998
  print(
940
- f"[cross-review] diff is {len(diff_text):,} chars, over the {max_diff_chars:,} "
941
- f"ceiling — reviewing in {len(batches)} batches split on file boundaries. "
942
- "Verdict is CLEAN only if every batch is clean."
999
+ f"[cross-review] diff is {len(diff_text):,} chars — reviewing in {len(batches)} batches split on "
1000
+ f"file boundaries (ceiling {max_diff_chars:,} diff chars"
1001
+ + (f"; agy-argon is in the chain, so each whole prompt also stays within {AGY_MAX_PROMPT_CHARS:,} "
1002
+ "command-line chars" if agy_in_chain else "")
1003
+ + "). Verdict is CLEAN only if every batch is clean."
943
1004
  )
944
1005
 
945
- branch = current_branch(args.cwd)
946
-
947
1006
  # Per run: a provider that failed (429, 5xx, timeout, empty reply, cap refusal) gets no more calls,
948
1007
  # and each provider waits for a 429 Retry-After at most once. Hammering a throttled provider with
949
1008
  # more, smaller calls is the 18-19 Oct 2026 failure.
@@ -1024,7 +1083,6 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
1024
1083
  out += got
1025
1084
  return out, []
1026
1085
 
1027
- whole_change = changed_paths(diff_text)
1028
1086
  verdicts: list[bool | None] = []
1029
1087
  for batch_no, batch in enumerate(batches, 1):
1030
1088
  label = f" (batch {batch_no}/{len(batches)})" if len(batches) > 1 else ""
@@ -1044,6 +1102,8 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
1044
1102
  if any(v is False for v in verdicts):
1045
1103
  # An earlier batch already found a blocking issue. A later failure must not hide it behind
1046
1104
  # NOT_RUN (3), which reads as "nothing found, retry". Fail closed and report the finding.
1105
+ if scope_line:
1106
+ print(scope_line)
1047
1107
  print("REVIEW: BLOCKING (an earlier batch blocked; the remaining batches were not reviewed)")
1048
1108
  return EXIT_BLOCKING
1049
1109
  return EXIT_CONFIG if not_run else EXIT_ERROR
@@ -1066,6 +1126,11 @@ def main(argv: list[str] | None = None, env: dict[str, str] | None = None) -> in
1066
1126
  if unparsed:
1067
1127
  print("[cross-review] a chunk with no verdict is NOT a pass — the overall result "
1068
1128
  "below is fail-closed.")
1129
+ if scope_line and verdict is not None:
1130
+ # The model's own verdict line came earlier (and the ledger may follow it), so restate the overall
1131
+ # verdict here: the scope line sits directly above the last `REVIEW:` line.
1132
+ print(scope_line)
1133
+ print("REVIEW: CLEAN" if verdict else "REVIEW: BLOCKING")
1069
1134
  if verdict is True:
1070
1135
  return EXIT_CLEAN
1071
1136
  if verdict is False:
@@ -27,7 +27,7 @@ What the keys mean:
27
27
  | `reviews.count` | How many reviews a PR needs before it is ready. |
28
28
  | `reviews.stop_on` | Which review findings stop a merge. `blocking`: only blocking findings. |
29
29
  | `peer_ack.warning_min` | Minutes between the merge warning and the merge. |
30
- | `peer_ack.ack_file` | Where each peer writes its ack: `{head, acked[], at}`. An ack older than 30 minutes does not count. |
30
+ | `peer_ack.ack_file` | Where each peer writes its ack: `{head, acked[], at}`. An ack older than 30 minutes does not count. Only a peer with a stake in the repo must ack: its folder is in the repo or a worktree of it, or the coordinator lists one of its PRs, branches or plan phases, or it sent `ready` or `phase`. A peer with no stake is not warned and is not in `acked[]`. |
31
31
  | `deploy.event` | The event that starts the deploy run (for example `push`). |
32
32
  | `deploy.jobs` | The number of jobs in the deploy run. |
33
33
  | `deploy.tag` | The release tag scheme. With `calver`, the tag must point at the merge SHA. |