@caddis/cli 0.4.89 → 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 (43) 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_fleet.py +10 -5
  17. package/bundles/antigravity-plugin/scripts/caddis_guide.json +3 -3
  18. package/bundles/antigravity-plugin/scripts/caddis_handoff.py +73 -45
  19. package/bundles/antigravity-plugin/scripts/caddis_lanes.py +96 -14
  20. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +136 -67
  21. package/bundles/antigravity-plugin/scripts/caddis_workstreams.py +86 -20
  22. package/bundles/antigravity-plugin/scripts/check_doc_coverage.py +17 -0
  23. package/bundles/antigravity-plugin/scripts/oss_review.py +89 -24
  24. package/bundles/antigravity-plugin/scripts/templates/coordinator.md +1 -1
  25. package/bundles/antigravity-plugin/skills/code-review/SKILL.md +2 -0
  26. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +17 -4
  27. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +18 -5
  28. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +5 -0
  29. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +18 -4
  30. package/bundles/antigravity-plugin/skills/implement/SKILL.md +23 -2
  31. package/bundles/antigravity-plugin/skills/park/SKILL.md +1 -0
  32. package/bundles/antigravity-plugin/skills/preflight/SKILL.md +1 -0
  33. package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +2 -1
  34. package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +8 -1
  35. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  36. package/bundles/antigravity-plugin-extras/skills/cross-review/SKILL.md +6 -5
  37. package/bundles/codex/.codex/skills/coding/code-review/SKILL.md +2 -0
  38. package/bundles/codex/.codex/skills/workflow/preflight/SKILL.md +1 -0
  39. package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +2 -1
  40. package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +8 -1
  41. package/bundles/manifest.json +3 -3
  42. package/dist/cli.js +12 -4
  43. package/package.json +1 -1
@@ -30,6 +30,10 @@ _BAD_REF = re.compile(r"[\x00-\x20\x7f~^:?*\[\\]")
30
30
  _NEXT = re.compile(r"^## Next step[^\n]*\n(.*?)(?=^## |\Z)", re.MULTILINE | re.DOTALL)
31
31
  _MAX_INDEX = 800
32
32
  _INDEX_MARKER = "<!-- caddis-workstream-index-v1 -->\n"
33
+ # `generated.by` of a relay that migrate-legacy writes.
34
+ _MIGRATED_BY = "caddis_workstreams.py migrate-legacy"
35
+ # The relay size budget in scripts/caddis_budget.py (`.caddis/relay/*.md`, chars).
36
+ _RELAY_BUDGET_CHARS = 4000
33
37
 
34
38
 
35
39
  @dataclass(frozen=True)
@@ -198,6 +202,27 @@ def _free_backup(path: Path) -> Path:
198
202
  raise ValueError(f"too many backups next to {path.name}")
199
203
 
200
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
+
201
226
  def _header_text(meta: dict) -> str:
202
227
  """Relay header lines in the shape caddis_frontmatter.parse reads back: scalars, one nested
203
228
  map or one list per key. Every value is folded to one line, so no value can add a field."""
@@ -467,6 +492,25 @@ class MigrationReport(dict):
467
492
  def backups(self) -> list[str]:
468
493
  return self["backups"]
469
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
+
500
+
501
+ def _utc_z(value: object = None) -> str:
502
+ """`value` (an ISO time; naive means UTC) or now, as relay headers write it: UTC, seconds, `Z`.
503
+ An unreadable value gives now, as the migration did before."""
504
+ when = datetime.now(timezone.utc)
505
+ if value:
506
+ try:
507
+ when = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
508
+ except ValueError:
509
+ pass
510
+ if when.tzinfo is None:
511
+ when = when.replace(tzinfo=timezone.utc)
512
+ return when.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
513
+
470
514
 
471
515
  def migrate_legacy(root: Path) -> MigrationReport:
472
516
  """Run the locked migration, then make sure an index exists when there was nothing to do.
@@ -524,6 +568,8 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
524
568
 
525
569
  candidates: dict[str, str] = {}
526
570
  conflicts: list[str] = []
571
+ trimmed: list[str] = []
572
+ legacy_bak: Path | None = None
527
573
 
528
574
  # 1. Process legacy relay.md
529
575
  if has_legacy_relay:
@@ -547,14 +593,19 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
547
593
  relay_name = "legacy"
548
594
 
549
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")
550
598
  # No header, or an opening --- with no closing one: keep the whole file as the body.
551
599
  header_closed = split_document(candidate_text)[1] != candidate_text
552
600
  if not candidate_text.startswith("---\n") or not header_closed:
553
- now_iso = datetime.now(timezone.utc).isoformat()
554
- candidate_text = (
555
- f"---\ntype: relay\nworkstream: {relay_name}\nbranch: main\n"
556
- f"session_id: legacy-migrated\nplan:\ngenerated:\n at: {now_iso}\n---\n\n"
557
- 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"
558
609
  )
559
610
  else:
560
611
  meta = parse(candidate_text)
@@ -575,9 +626,13 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
575
626
  meta["plan"] = ""
576
627
  modified = True
577
628
  if not isinstance(meta.get("generated"), dict) or not meta["generated"].get("at"):
578
- # Keep the original time from an inline "{ by: x, at: y }" map; else now.
579
- inline = re.search(r"\bat:\s*([0-9][0-9T:.+\-Z]+)", str(meta.get("generated", "")))
580
- meta["generated"] = {"at": inline.group(1) if inline else datetime.now(timezone.utc).isoformat()}
629
+ # Keep the original author and time from an inline "{ by: x, at: y }" map; else
630
+ # this script, now.
631
+ inline = str(meta.get("generated", ""))
632
+ by = re.search(r"\bby:\s*([^,}\n]+)", inline)
633
+ at = re.search(r"\bat:\s*([0-9][0-9T:.+\-Z]+)", inline)
634
+ meta["generated"] = {"by": by.group(1).strip() if by else _MIGRATED_BY,
635
+ "at": _utc_z(at.group(1) if at else None)}
581
636
  modified = True
582
637
  if modified:
583
638
  # Plain writer: the plugin ships no YAML library, and this runs in user installs.
@@ -588,6 +643,11 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
588
643
  _validate_relay(relay_name, candidate_text)
589
644
  except Exception as exc:
590
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)
591
651
 
592
652
  target_path = relay_dir / f"{_name(relay_name)}.md"
593
653
  if target_path.is_file() and not target_path.is_symlink():
@@ -629,17 +689,11 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
629
689
  branch = frame.get("branch") or "main"
630
690
  session_id = frame.get("session_id") or "legacy-migrated"
631
691
  resume = frame.get("resumePointer") or "next step unrecorded"
632
- pushed = frame.get("pushedAt") or datetime.now(timezone.utc).isoformat()
633
- try:
634
- datetime.fromisoformat(str(pushed).replace("Z", "+00:00"))
635
- except ValueError:
636
- pushed = datetime.now(timezone.utc).isoformat()
637
-
638
692
  # _header_text folds every value to one line: a newline in workstreams.json
639
693
  # must not add or break header fields.
640
694
  header = _header_text({"type": "relay", "workstream": frame_name, "branch": str(branch),
641
695
  "session_id": str(session_id), "plan": str(plan or ""),
642
- "generated": {"at": str(pushed)}})
696
+ "generated": {"by": _MIGRATED_BY, "at": _utc_z(frame.get("pushedAt"))}})
643
697
  candidate_text = (f"---\n{header}---\n\n# Relay — {frame_name}\n\n"
644
698
  f"## Next step (exact)\n{' '.join(str(resume).split())}\n")
645
699
  try:
@@ -665,6 +719,8 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
665
719
 
666
720
  # Write candidates
667
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())
668
724
  migrated: list[str] = []
669
725
  for name, text in candidates.items():
670
726
  # Locked compare-and-swap on the target: a session that wrote this relay after the
@@ -693,15 +749,13 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
693
749
  legacy_ws.unlink()
694
750
  backups.append(bak_path.name)
695
751
 
696
- if has_legacy_relay:
697
- bak_path = _free_backup(artifact / "relay.md.bak")
698
- bak_path.write_bytes(index_file.read_bytes())
752
+ if legacy_bak is not None: # already saved above; the old relay.md goes now
699
753
  index_file.unlink()
700
- backups.append(bak_path.name)
754
+ backups.append(legacy_bak.name)
701
755
 
702
756
  # Render index outside the lock so render_index can acquire its own lock
703
757
  render_index(root, None, None)
704
- return MigrationReport(status="migrated", migrated=migrated, conflicts=[], backups=backups)
758
+ return MigrationReport(status="migrated", migrated=migrated, conflicts=[], backups=backups, trimmed=trimmed)
705
759
 
706
760
 
707
761
  def main(argv: list[str] | None = None) -> int:
@@ -776,6 +830,10 @@ def main(argv: list[str] | None = None) -> int:
776
830
  elif args.command == "write":
777
831
  content = args.file.read_text(encoding="utf-8")
778
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
779
837
  res = write_relay(args.root, args.name, content, expected)
780
838
  if res.status != "written":
781
839
  # The caller must see what changed; nothing was written.
@@ -826,6 +884,10 @@ def main(argv: list[str] | None = None) -> int:
826
884
  except ValueError as exc:
827
885
  sys.stderr.write(f"cannot read existing relay: {exc}\n")
828
886
  return 1
887
+ refusal = _over_budget(args.name, content)
888
+ if refusal:
889
+ sys.stderr.write(refusal + "\n")
890
+ return 1
829
891
  try:
830
892
  res = write_relay(args.root, args.name, content, expected)
831
893
  except ValueError as exc:
@@ -850,6 +912,10 @@ def main(argv: list[str] | None = None) -> int:
850
912
  print(f"Migration status: {report.status}")
851
913
  for conflict in report.conflicts:
852
914
  print(f" conflict: {conflict}")
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]}")
853
919
  return 0 if report.status in ("clean", "migrated") else 1
854
920
  elif args.command == "list":
855
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. |
@@ -61,6 +61,8 @@ Check for:
61
61
 
62
62
  ## Review Output Format
63
63
 
64
+ In a caddis repo, save a review note in `.caddis/reviews/`, never in `.caddis/parking-lot/`: that folder holds only items to do later, one item per file, `type: parking-lot`.
65
+
64
66
  ```markdown
65
67
  ## Code Review Summary
66
68
 
@@ -229,14 +229,26 @@ and 7.3. While the queue is frozen (section 5 step 1), do steps 3.1 to 3.3 only.
229
229
  `GH_TOKEN=$(gh auth token -u <account>) python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_lanes.py" ci-watch --run <id> --repo <owner/name>`,
230
230
  in the background (`run_in_background: true`). When its `RESULT:` line comes, check M1 again.
231
231
  9. Send `merge-warning <PR> <watched sha> in 2 min. Reply ack <PR> <sha> or hold.` to every live peer
232
- (design 7.3), and `queue set --repo <R> --pr <n> --state merging`. Send `re-warn <PR> <sha>` after any coordinator
233
- restart and after any new head on a warned PR. Old acks do not count.
232
+ that has a stake in this repo (design 7.3), and `queue set --repo <R> --pr <n> --state merging`. Send
233
+ `re-warn <PR> <sha>` after any coordinator restart and after any new head on a warned PR. Old acks do not count.
234
+ Stake test, run for each live peer at the warning (design 7.3a). A peer has a stake when ANY of these
235
+ holds: its cwd is inside the checkout or one of its worktrees (for example under
236
+ `.worktrees/<repo>/`); the queue or the ledger lists a PR, branch or plan phase of that peer in this
237
+ repo; or it has sent `ready` or `phase` for this repo. Anything else is no stake. When the cwd is
238
+ unknown or you are unsure, the peer has a stake. A peer with no stake gets no warning and is not in
239
+ `acked`. Run the test again for a new peer that you see after the warning. A peer with a stake gets
240
+ the warning; step 3.11 checks again.
234
241
  10. Collect the acks (M2). Wait the full `peer_ack.warning_min` minutes after the warning, even when every
235
242
  ack comes early. For that wait, run `sleep 120` (`peer_ack.warning_min` x 60 s) with the Bash tool
236
243
  and `run_in_background: true`, or use the Monitor tool, and act on its exit notice; never a
237
244
  foreground sleep. Answer messages while it runs. No ack after 5 min: one nudge. After 10 min: tell
238
245
  the owner. A peer that waits on the owner cannot answer: tell the owner "ack needed from <name>; it
239
246
  waits on you". Do not write the ack file yet (step 3.13).
247
+ A peer with a stake still needs `ack <PR> <sha>`, and a `hold` still stops the merge. If a peer answers
248
+ `no stake <PR>`, or says it has "no hold" and that this is "not an owner ack", run the stake test. No stake:
249
+ record a skip for that PR (step 3.13, `skipped_no_stake`), not a missing ack, and send it no nudge. A
250
+ stake: that reply is not an ack; ask for `ack <PR> <sha>` or `hold`. A peer message never carries owner
251
+ consent. A skip never applies to a peer with a stake.
240
252
  11. Check again that the default branch is idle (M1, the same `gh run list` as step 3.8), just before the
241
253
  merge. If a run started, wait for it (step 3.8). If the warning went out more than 30 min ago, warn
242
254
  again (step 3.9).
@@ -264,11 +276,12 @@ and 7.3. While the queue is frozen (section 5 step 1), do steps 3.1 to 3.3 only.
264
276
  last path part of the first `worktree` line of `git worktree list --porcelain` (the repo's main
265
277
  checkout), NOT the repo id `<R>`. The content is exactly:
266
278
  ```
267
- {"pr": <n>, "head": "<full sha>", "acked": [<names>], "skipped_waiting": [<names waiting on the owner>], "at": "<UTC ISO 8601 with Z>"}
279
+ {"pr": <n>, "head": "<full sha>", "acked": [<names>], "skipped_waiting": [<names waiting on the owner>], "skipped_no_stake": [<names with no stake>], "at": "<UTC ISO 8601 with Z>"}
268
280
  ```
269
281
  `acked` lists every peer that sent `ack <PR> <sha>` for this head, by its session name. An unnamed
270
282
  peer is listed under the first 8 characters of its session id (the hook uses the same name). A peer
271
- that waits on the owner goes under `skipped_waiting`, never under `acked`. Interim mode: also put
283
+ that waits on the owner goes under `skipped_waiting`, never under `acked`. A peer with no stake (step 3.9)
284
+ goes under `skipped_no_stake`, never under `acked`. Interim mode: also put
272
285
  your own name `<N>` in `acked` (the PR's session runs the merge, and its hook counts you as a peer).
273
286
  Target mode: you run the merge, so `acked` must list the PR's session too. The hook refuses an ack
274
287
  file older than 30 min.
@@ -81,10 +81,21 @@ writes. This line used to prefix the flag itself, which turned that into a doubl
81
81
  Optional: `--base-url <url>`, `--model <id>` (env always overrides the preset).
82
82
 
83
83
  **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. Exit **4**
85
- now means the narrower case — a **single file** too big to split, or more batches than the cap. When you
86
- see it, the fix is usually to review that one file separately, not to narrow `--range`; don't raise
87
- `--max-diff-chars` blind.
84
+ on whole-file boundaries and reviews each batch, and the verdict is CLEAN only if every batch is. When agy
85
+ Argon 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.
91
+
92
+ **The verdict is the last line.** Only the last non-empty line of the reply counts, and it must be
93
+ exactly `REVIEW: CLEAN` or `REVIEW: BLOCKING`. A reply that quotes the marker earlier and ends some other
94
+ way has no verdict (exit 4). An explicit `--range` with no changes is exit **3** (a review of nothing is not
95
+ CLEAN); the working tree with no changes is still CLEAN. When the secret filter drops some files, the
96
+ output ends with `REVIEW-SCOPE: PARTIAL (<n> file(s) excluded by the secret filter: <names>)` and then the
97
+ overall `REVIEW:` line. The exit code does not change, but the excluded files were **not reviewed**: say so,
98
+ and never report the result as a full CLEAN.
88
99
 
89
100
  **Do not alternate providers on a schedule.** The order is the owner policy (21 Oct 2026): **agy Argon,
90
101
  then DeepSeek, then GLM** (`REVIEW_ORDER` in `oss_review.py`). A named `--provider` goes first; on a provider failure
@@ -103,7 +114,8 @@ a reason.
103
114
  - **1 — REVIEW: BLOCKING** → read the printed findings, then **FIX each blocking item** (or explicitly
104
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).
105
116
  - **4 — error** → no verdict parsed, or a git/endpoint failure. Read stderr; do NOT treat as clean.
106
- - **3 — could not run** → no key (see Prerequisite), the secret filter refused, or every provider
117
+ - **3 — could not run** → no key (see Prerequisite), the secret filter refused, an explicit `--range` has
118
+ no changes, or every provider
107
119
  failed (429, 5xx, timeout, empty reply). Read stderr. A provider failure is not a verdict: re-run later.
108
120
 
109
121
  ## Three rules: one attempt, one review
@@ -124,6 +136,7 @@ change, so a batch does not report the others as missing.
124
136
  emitted by this tool** — across caddis 2 always means an advisory note, and a review
125
137
  has no advisory verdict.
126
138
  - A different vendor means a different style; weigh its findings on merit, don't cargo-cult them.
139
+ - Save review notes in `.caddis/reviews/`, never in `.caddis/parking-lot/`: that folder holds only items to do later, one item per file, `type: parking-lot` (`/caddis:park`).
127
140
  - **Never use `find`, `Get-ChildItem -Recurse`, or any other filesystem-wide search to locate
128
141
  `oss_review.py`.** Check only the two paths above. On Git Bash under Windows, `find /` (or any
129
142
  search rooted at `/`) walks every mounted drive, not just the repo — it can hang or take minutes.
@@ -422,6 +422,11 @@ Status words (one vocabulary, `scripts/caddis_status.py`): done is `done`, `merg
422
422
  `in progress`, `blocked` and `moved` name the other states; anything else (`not started`, `☐`) is to do. A cell
423
423
  that says `pending` is never done.
424
424
 
425
+ The plan's frontmatter `status:` is a different axis from these cells. Use only the known words:
426
+ `draft` (being written), `proposed` (written, not agreed), `ready` (agreed, waiting), `current` (work is under
427
+ way), then `done` or `superseded`. Never `in-progress`, `active` or `wip`: `check_doc_coverage.py` warns on
428
+ them and suggests the nearest known word.
429
+
425
430
  ## Per-symbol grep preflight (before the plan is committed)
426
431
  Check every name a card gives: each symbol, file, line number and CSS variable. Use one grep per name
427
432
  (Grep, or `git grep -n`) before you commit the plan. Fix the card when a name or a line number differs.