@caddis/cli 0.4.90 → 0.4.92

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_gate.py +8 -8
  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 +113 -31
  20. package/bundles/antigravity-plugin/scripts/caddis_review.py +1 -1
  21. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +22 -40
  22. package/bundles/antigravity-plugin/scripts/caddis_routing.py +1 -1
  23. package/bundles/antigravity-plugin/scripts/caddis_spend.py +121 -138
  24. package/bundles/antigravity-plugin/scripts/caddis_workstreams.py +60 -17
  25. package/bundles/antigravity-plugin/scripts/check_doc_coverage.py +17 -0
  26. package/bundles/antigravity-plugin/scripts/oss_review.py +102 -35
  27. package/bundles/antigravity-plugin/scripts/roadmap-recheck.ps1 +4 -2
  28. package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +6 -0
  29. package/bundles/antigravity-plugin/scripts/schemas/hub-spend.schema.json +6 -0
  30. package/bundles/antigravity-plugin/scripts/templates/coordinator.md +1 -1
  31. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +17 -4
  32. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +18 -6
  33. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +6 -1
  34. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +12 -2
  35. package/bundles/antigravity-plugin/skills/implement/SKILL.md +11 -7
  36. package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +8 -7
  37. package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +2 -2
  38. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  39. package/bundles/antigravity-plugin-extras/skills/cross-review/SKILL.md +5 -5
  40. package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +8 -7
  41. package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +2 -2
  42. package/bundles/manifest.json +3 -3
  43. package/package.json +1 -1
@@ -1,47 +1,39 @@
1
1
  #!/usr/bin/env python3
2
- """caddis_spend - one global spend cap for agy, in EUR per rolling 24 hours, on this machine.
2
+ """caddis_spend - the agy usage log and the `run` wrapper for every agy launch caddis makes.
3
3
 
4
- Why: on 7 Oct 2026 two unsupervised overnight agy runs cost EUR 793 in one billing day. Nothing in
5
- caddis capped money (caddis_governor caps CPU and memory only). Every agy launch that caddis makes
6
- through a lane (`caddis_lanes.run_lane`, which ci-watch also uses) or a plan Lane line
7
- (`caddis_spend.py run -- agy ...`) goes through `reserve()` before it starts and `settle()` after it ends.
8
- The roadmap/plan runner (`caddis_roadmap_run.py --engine agy`) reserves before each agy session and settles after it.
4
+ History: on 7 Oct 2026 two unattended overnight agy runs cost EUR 793 in one billing day. caddis then
5
+ had a spend cap here (EUR per rolling 24 h). The owner removed the cap on 1 Nov 2026. The usage log stays,
6
+ so agy spend stays visible, and the owner's rule "cost-heavy runs need approval first" stays as text.
7
+ Nothing in this file refuses an agy launch because of money. Instead, at or above an advise level (EUR 300
8
+ committed in 24 h, or CADDIS_SPEND_ADVISE_EUR), `run` prints one `caddis_spend: ADVISORY:` line to stderr before
9
+ the launch and after the settle, and `status` / `check` add ` - ADVISORY (>= EUR <level>)`. Exit codes do not
10
+ change. The committed EUR comes from the prices below, so with no prices it stays 0 and no advisory shows.
9
11
 
10
- Config `~/.caddis/spend-cap.toml` (the owner writes it; caddis never does):
12
+ Every agy launch that caddis makes through a lane (`caddis_lanes.run_lane`, which ci-watch also uses), a
13
+ plan Lane line (`caddis_spend.py run -- agy ...`) or the roadmap/plan runner (`caddis_roadmap_run.py
14
+ --engine agy`) calls `reserve()` before it starts and `settle()` after it ends.
11
15
 
12
- [agy]
13
- eur_per_24h = 200
14
- reserve_eur_per_call = 10 # what a call still running, or killed, is assumed to cost
15
- eur_per_million_input_tokens = 0 # from Google Cloud billing; 0 = unset
16
- eur_per_million_output_tokens = 0
16
+ Log `~/.caddis/spend/agy.jsonl`, append-only. A `pending` line is written under a file lock before the
17
+ launch and a `settled` line with the same id after it. A settled line holds the token counts and an EUR
18
+ estimate. A pending line with no settled line (a crash) counts its `reserve_eur` (now 0) for 24 h.
17
19
 
18
- Every value must be a finite number above 0. Anything else means NOT CONFIGURED, and every agy launch is
19
- refused (fail closed).
20
+ Prices (optional): when `~/.caddis/spend-cap.toml` has an `[agy]` table with
21
+ `eur_per_million_input_tokens` and `eur_per_million_output_tokens` (finite numbers above 0), a settled
22
+ line records EUR from the token counts. Every other key in that file (an old `eur_per_24h`, a reserve) is
23
+ ignored, and with no valid prices EUR is recorded as 0 with `estimated: true`. caddis never writes the file.
20
24
 
21
- Log `~/.caddis/spend/agy.jsonl`, append-only. A `pending` line is written under a file lock before the
22
- launch and a `settled` line with the same id after it. A pending line with no valid settled line keeps
23
- counting its reserve for 24 h, so a killed or crashed call is never free, and two callers cannot both
24
- pass the check with the last EUR of the cap.
25
-
26
- Limits (by design, see .caddis/plans/caddis-next.md Phase 4):
27
- - The cap is per machine. The only cap across machines is a Google Cloud budget alert.
28
- - agy started by hand, or by a script outside caddis, is not covered.
29
- - The cap file and the log are plain files of this user: any process of this user, including an agy
30
- session started with --dangerously-skip-permissions, can edit them. The cap stops accidents and
31
- runaway loops; it is not a security boundary against a hostile local process.
32
- - The check runs at launch. A long call can cost more than its reserve before it is settled; an
33
- estimated settle records its duration so the overshoot is visible.
25
+ Limits:
26
+ - The log is per machine. agy started by hand, or by a script outside caddis, is not logged.
34
27
  - EUR is an estimate from token counts and the owner's prices, not the real bill.
35
28
 
36
29
  CLI:
37
- python caddis_spend.py check exit 0 allowed, 1 over cap, 3 not configured
38
- python caddis_spend.py status prints the committed spend of the last 24 h
30
+ python caddis_spend.py check always exit 0; prints the status line
31
+ python caddis_spend.py status [--json] prints the logged spend of the last 24 h
39
32
  python caddis_spend.py run --caller X -- agy ...
40
- reserve, run, settle. Returns agy's own exit code, or 75 over the cap / could not lock,
41
- or 78 not configured, or 124 when the command ran past its time limit (--timeout-s, else
42
- CADDIS_SPEND_RUN_TIMEOUT_S, else 3600 s) and its process tree was killed. 75 and 78 are never
43
- agy's own codes for a refusal, so a caller can tell "the cap refused" from "agy failed". Each
44
- refusal also prints a `caddis_spend:` line.
33
+ log, run, settle. Returns agy's own exit code, or 75 when the headless depth is at its limit or the
34
+ log could not be locked or written, or 124 when the command ran past its time limit (--timeout-s,
35
+ else CADDIS_SPEND_RUN_TIMEOUT_S, else 3600 s) and its process tree was killed. Each refusal also
36
+ prints a `caddis_spend:` line.
45
37
  On Windows the command runs on a hidden desktop (caddis_hidden_desktop.py), so the console windows agy opens
46
38
  for its tools never show; CADDIS_AGY_VISIBLE=1 runs it on the normal desktop.
47
39
  """
@@ -58,30 +50,43 @@ import sys
58
50
  import time
59
51
  import uuid
60
52
  from contextlib import contextmanager
61
- from dataclasses import dataclass
62
53
  from datetime import datetime, timedelta, timezone
63
54
  from pathlib import Path
64
55
 
65
56
  EXIT_OK = 0
66
- EXIT_OVER_CAP = 1 # `check` only
67
- EXIT_NOT_CONFIGURED = 3 # `check` only
68
- RUN_REFUSED = 75 # `run`: over the cap, or could not lock (EX_TEMPFAIL)
69
- RUN_NOT_CONFIGURED = 78 # `run`: not configured (EX_CONFIG)
57
+ EXIT_LOG_ERROR = 1 # `status` only: the log could not be read
58
+ RUN_REFUSED = 75 # `run`: headless depth at its limit, or the log could not be locked or written (EX_TEMPFAIL)
70
59
  RUN_TIMEOUT = 124 # `run`: the child ran past its time limit and its process tree was killed (as timeout(1))
71
60
  DEFAULT_RUN_TIMEOUT_S = 3600.0 # one hour: a run over about 1 hour needs the owner's approval anyway
72
61
  # No console window for the child on Windows (robustness #19; see no_window.py: never DETACHED_PROCESS).
73
62
  _NO_WINDOW_KW = {"creationflags": 0x08000000} if os.name == "nt" else {}
74
63
  LOCK_TIMEOUT_S = 10.0
75
- NOT_CONFIGURED_MESSAGE = ("caddis_spend: spend cap not configured: set eur_per_24h, reserve_eur_per_call and both "
76
- "token prices (finite, above 0) in ~/.caddis/spend-cap.toml; every agy launch is refused "
77
- "until then")
64
+ # Advisory, never a refusal: at or above this committed EUR in 24 h, `run` and `status` say so. The owner may change it
65
+ # with CADDIS_SPEND_ADVISE_EUR (a finite number above 0; anything else means this default).
66
+ ADVISE_EUR_PER_24H = 300.0
67
+ ADVISE_VAR = "CADDIS_SPEND_ADVISE_EUR"
68
+
69
+
70
+ def advise_eur(env=None) -> float:
71
+ """The advisory level in EUR per 24 h: CADDIS_SPEND_ADVISE_EUR when it is a finite number above 0, else 300."""
72
+ env = os.environ if env is None else env
73
+ try:
74
+ value = float(str(env.get(ADVISE_VAR, "")).strip())
75
+ except ValueError:
76
+ return ADVISE_EUR_PER_24H
77
+ return value if math.isfinite(value) and value > 0 else ADVISE_EUR_PER_24H
78
+
79
+
80
+ def advisory_line(committed: float, level: float) -> str:
81
+ return (f"caddis_spend: ADVISORY: EUR {committed:.2f} committed in the last 24 h on this machine "
82
+ f"(advise level EUR {level:g}). No cap applies. Tell the owner.")
78
83
 
79
84
 
80
85
  # Recursion guard on headless starts (robustness #19). Every launcher of a headless caddis session passes
81
86
  # CADDIS_HEADLESS_DEPTH one higher than it got, and refuses to launch once the depth is at the limit, so a
82
87
  # headless session that starts a headless session that starts one... ends after MAX_HEADLESS_DEPTH levels.
83
88
  # The owner may change the limit with CADDIS_HEADLESS_MAX_DEPTH. This stops accidents and loops; a hostile
84
- # process can reset the variable, like the cap file (see the Limits above).
89
+ # process can reset the variable.
85
90
  HEADLESS_DEPTH_VAR = "CADDIS_HEADLESS_DEPTH"
86
91
  MAX_HEADLESS_DEPTH = 3
87
92
 
@@ -112,19 +117,8 @@ def bump_headless_depth(env) -> dict:
112
117
  return out
113
118
 
114
119
 
115
- class NotConfigured(Exception):
116
- """The cap file is missing, unreadable, or holds a value that is not a finite number above 0."""
117
-
118
-
119
- @dataclass
120
- class Cap:
121
- eur_per_24h: float
122
- reserve: float
123
- price_in: float
124
- price_out: float
125
-
126
-
127
- def _cap_path(home: Path) -> Path:
120
+ def _prices_path(home: Path) -> Path:
121
+ """The optional price file. Only its two token prices are read; any cap value in it is ignored."""
128
122
  return home / ".caddis" / "spend-cap.toml"
129
123
 
130
124
 
@@ -132,26 +126,24 @@ def _log_path(home: Path) -> Path:
132
126
  return home / ".caddis" / "spend" / "agy.jsonl"
133
127
 
134
128
 
135
- def _positive(value) -> float:
136
- """A finite float above 0, or ValueError (bool and NaN/inf rejected)."""
137
- if isinstance(value, bool):
138
- raise ValueError(f"not a number: {value!r}")
139
- number = float(value)
140
- if not math.isfinite(number) or number <= 0:
141
- raise ValueError(f"must be a finite number above 0: {value!r}")
142
- return number
143
-
144
-
145
- def load_cap(home: Path) -> Cap:
129
+ def load_prices(home: Path) -> tuple[float, float] | None:
130
+ """(EUR per million input tokens, EUR per million output tokens) from the `[agy]` table of the optional price
131
+ file, or None when the file is missing or unreadable, or a price is not a finite number above 0."""
146
132
  import tomllib
147
133
 
148
- path = _cap_path(home)
149
134
  try:
150
- data = tomllib.loads(path.read_text(encoding="utf-8")).get("agy", {})
151
- return Cap(_positive(data["eur_per_24h"]), _positive(data.get("reserve_eur_per_call", 10)),
152
- _positive(data["eur_per_million_input_tokens"]), _positive(data["eur_per_million_output_tokens"]))
153
- except (OSError, ValueError, KeyError, TypeError, AttributeError, tomllib.TOMLDecodeError) as exc:
154
- raise NotConfigured(f"{path}: {exc}") from exc
135
+ data = tomllib.loads(_prices_path(home).read_text(encoding="utf-8")).get("agy", {})
136
+ prices = (data["eur_per_million_input_tokens"], data["eur_per_million_output_tokens"])
137
+ except (OSError, ValueError, KeyError, TypeError, AttributeError, tomllib.TOMLDecodeError):
138
+ return None
139
+ numbers = []
140
+ for value in prices:
141
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
142
+ return None
143
+ if not math.isfinite(value) or value <= 0:
144
+ return None
145
+ numbers.append(float(value))
146
+ return numbers[0], numbers[1]
155
147
 
156
148
 
157
149
  @contextmanager
@@ -251,10 +243,10 @@ def _amount(value) -> float | None:
251
243
 
252
244
  def committed_last_24h(home: Path, now: datetime) -> float:
253
245
  """Valid settled EUR, plus the reserve of every pending call with no valid settled line, newer than 24 h.
246
+ This is a report only; nothing refuses a launch on it.
254
247
 
255
- A settled line with a bad `eur` does not count as settled, so its pending reserve keeps counting.
256
- A pending line with a bad reserve (only a hand edit can write one; reserve() always writes a valid
257
- value) counts as 0."""
248
+ A settled line with a bad `eur` does not count as settled, so its pending reserve keeps counting (reserve()
249
+ now writes 0; older lines may hold a reserve). A pending line with a bad reserve (a hand edit) counts as 0."""
258
250
  since = now - timedelta(hours=24)
259
251
  records = _read(home)
260
252
  settled: dict[str, float] = {}
@@ -275,36 +267,33 @@ def committed_last_24h(home: Path, now: datetime) -> float:
275
267
  return total
276
268
 
277
269
 
278
- def reserve(home: Path, caller: str, now: datetime) -> str | None:
279
- """Book a pending call. None when it would go over the cap. Raises NotConfigured or TimeoutError."""
280
- cap = load_cap(home)
270
+ def reserve(home: Path, caller: str, now: datetime) -> str:
271
+ """Write a `pending` line for a call about to start and return its id. Never refuses for money.
272
+ Raises TimeoutError when the log cannot be locked, OSError when it cannot be written."""
281
273
  with _locked(home):
282
- if committed_last_24h(home, now) + cap.reserve > cap.eur_per_24h:
283
- return None
284
274
  rid = uuid.uuid4().hex
285
275
  _append(home, {"kind": "pending", "id": rid, "ts": now.isoformat(), "caller": caller,
286
- "pid": os.getpid(), "reserve_eur": cap.reserve})
276
+ "pid": os.getpid(), "reserve_eur": 0})
287
277
  return rid
288
278
 
289
279
 
290
280
  def settle(home: Path, rid: str, tokens: tuple[int, int] | None, now: datetime,
291
281
  duration_s: float | None = None) -> float:
292
- """Record the real cost of a reserved call; with no token counts, its reserve (estimated, with duration)."""
293
- try:
294
- cap = load_cap(home)
295
- except NotConfigured:
296
- cap = None
282
+ """Write the `settled` line of a call. With token counts and valid prices: the EUR from the counts. With counts
283
+ but no prices: the counts and EUR 0, estimated. With no counts: the pending line's reserve (0 for new lines),
284
+ estimated. The duration is recorded when given."""
285
+ prices = load_prices(home)
297
286
  record: dict = {"kind": "settled", "id": rid, "ts": now.isoformat()}
298
- if tokens is None or cap is None:
287
+ if tokens is None:
299
288
  pending = next((r for r in _read(home) if r.get("kind") == "pending" and r.get("id") == rid), {})
300
- eur = _amount(pending.get("reserve_eur"))
301
- if eur is None:
302
- eur = cap.reserve if cap else 0.0
289
+ eur = _amount(pending.get("reserve_eur")) or 0.0
303
290
  record.update({"tokens_in": 0, "tokens_out": 0, "eur": round(eur, 4), "estimated": True})
304
291
  else:
305
292
  t_in, t_out = tokens
306
- eur = t_in / 1e6 * cap.price_in + t_out / 1e6 * cap.price_out
307
- record.update({"tokens_in": t_in, "tokens_out": t_out, "eur": round(eur, 4), "estimated": False})
293
+ eur = 0.0 if prices is None else t_in / 1e6 * prices[0] + t_out / 1e6 * prices[1]
294
+ # Zero tokens cost exactly 0 (nothing ran); other counts with no prices are an estimate.
295
+ estimated = prices is None and (t_in, t_out) != (0, 0)
296
+ record.update({"tokens_in": t_in, "tokens_out": t_out, "eur": round(eur, 4), "estimated": estimated})
308
297
  if duration_s is not None:
309
298
  record["duration_s"] = round(duration_s, 1)
310
299
  with _locked(home):
@@ -344,7 +333,7 @@ def _count(value) -> int | None:
344
333
  def tokens_from_output(stdout: str) -> tuple[int, int] | None:
345
334
  """(usage.input_tokens, usage.output_tokens) from agy's JSON document; output_tokens includes thinking
346
335
  tokens (sample: 27249 in, 85 out of which 84 thinking, total 27334). None when not readable, or when a
347
- count is not a non-negative integer (then the call settles at its reserve)."""
336
+ count is not a non-negative integer (then the call settles as estimated)."""
348
337
  doc = _agy_document(stdout)
349
338
  usage = doc.get("usage") if doc else None
350
339
  if not isinstance(usage, dict):
@@ -426,35 +415,30 @@ def _run_child(argv: list[str], env: dict, timeout_s: float) -> tuple[int | None
426
415
  except BaseException:
427
416
  # Ctrl-C or any other error while waiting: the child (agy, spending) must not outlive us. It runs in its
428
417
  # own session/group, so it does not get our SIGINT. Kill the tree, then let the exception go on; run()
429
- # settles the reserve in its `finally`.
418
+ # settles the call in its `finally`.
430
419
  _kill_tree(proc)
431
420
  raise
432
421
 
433
422
 
434
423
  def run(argv: list[str], caller: str, home: Path, timeout_s: float | None = None) -> int:
435
- """Reserve, run agy, settle. Returns agy's exit code, or RUN_REFUSED (75) / RUN_NOT_CONFIGURED (78) /
436
- RUN_TIMEOUT (124: the child ran past `timeout_s`, default run_timeout_s(); its process tree was killed and the
437
- call is booked at its reserve)."""
424
+ """Log, run agy, settle. Returns agy's exit code, or RUN_REFUSED (75: headless depth at its limit, or the log
425
+ could not be locked or written) / RUN_TIMEOUT (124: the child ran past `timeout_s`, default run_timeout_s(); its
426
+ process tree was killed and the call is settled as estimated). Money never refuses a start."""
438
427
  now = lambda: datetime.now(timezone.utc) # noqa: E731
439
428
  try:
440
- env = bump_headless_depth(os.environ) # before the reserve: a refused start costs nothing
429
+ env = bump_headless_depth(os.environ) # before the pending line: a refused start writes nothing
441
430
  except HeadlessDepthExceeded as exc:
442
431
  print(str(exc), file=sys.stderr)
443
432
  return RUN_REFUSED
444
433
  try:
445
434
  rid = reserve(home, caller, now())
446
- except NotConfigured:
447
- print(NOT_CONFIGURED_MESSAGE, file=sys.stderr)
448
- return RUN_NOT_CONFIGURED
449
435
  except TimeoutError as exc:
450
436
  print(str(exc), file=sys.stderr)
451
437
  return RUN_REFUSED
452
- except Exception as exc: # an unreadable log or file error: refuse with the refusal code, never exit 1
453
- print(f"caddis_spend: could not check the spend cap: {exc!r}", file=sys.stderr)
454
- return RUN_REFUSED
455
- if rid is None:
456
- print(f"caddis_spend: over cap: agy refused ({status_line(home, now())})", file=sys.stderr)
438
+ except Exception as exc: # a file error on the log: refuse with the refusal code, never exit 1
439
+ print(f"caddis_spend: could not write the spend log: {exc!r}", file=sys.stderr)
457
440
  return RUN_REFUSED
441
+ advise(home, now()) # already at the level before the launch: say so, then start anyway
458
442
  out = ""
459
443
  counts: tuple[int, int] | None = None
460
444
  started = time.monotonic()
@@ -465,7 +449,7 @@ def run(argv: list[str], caller: str, home: Path, timeout_s: float | None = None
465
449
  sys.stdout.write(out)
466
450
  sys.stderr.write(err)
467
451
  print(f"caddis_spend: {argv[0]} timed out after {limit:g}s; its process tree was killed "
468
- f"(booked at the reserve). Set CADDIS_SPEND_RUN_TIMEOUT_S or --timeout-s to change the limit.",
452
+ f"(settled as estimated). Set CADDIS_SPEND_RUN_TIMEOUT_S or --timeout-s to change the limit.",
469
453
  file=sys.stderr)
470
454
  return RUN_TIMEOUT
471
455
  # Tokens only from JSON mode: in text mode the model's own lines could pose as a usage document.
@@ -481,29 +465,38 @@ def run(argv: list[str], caller: str, home: Path, timeout_s: float | None = None
481
465
  finally:
482
466
  try:
483
467
  settle(home, rid, counts, now(), duration_s=time.monotonic() - started)
484
- except Exception as exc: # the pending reserve keeps counting; never lose agy's own result
468
+ except Exception as exc: # the pending line stays unsettled; never lose agy's own result
485
469
  print(f"caddis_spend: could not settle {rid}: {exc}", file=sys.stderr)
470
+ advise(home, now())
486
471
 
487
472
 
488
- def status_line(home: Path, now: datetime) -> str:
473
+ def advise(home: Path, now: datetime) -> None:
474
+ """Print the ADVISORY line to stderr when the committed EUR of the last 24 h is at or above the advise level.
475
+ Advice only: it never changes an exit code, and a log it cannot read prints nothing."""
489
476
  try:
490
- cap = f"{load_cap(home).eur_per_24h:g}"
491
- except NotConfigured:
492
- cap = "NOT CONFIGURED"
493
- return f"agy: EUR {committed_last_24h(home, now):.2f} of {cap} in the last 24 h on this machine"
477
+ committed, level = committed_last_24h(home, now), advise_eur()
478
+ except Exception:
479
+ return
480
+ if committed >= level:
481
+ print(advisory_line(committed, level), file=sys.stderr)
482
+
483
+
484
+ def status_line(home: Path, now: datetime) -> str:
485
+ committed, level = committed_last_24h(home, now), advise_eur()
486
+ line = f"agy: EUR {committed:.2f} in the last 24 h on this machine (no cap)"
487
+ return line + (f" - ADVISORY (>= EUR {level:g})" if committed >= level else "")
494
488
 
495
489
 
496
490
  def spend_json(home: Path, now: datetime | None = None) -> dict:
497
- """The spend status as one JSON-ready dict. It holds no key, no prompt and no caller name."""
491
+ """The spend status as one JSON-ready dict. It holds no key, no prompt and no caller name.
492
+ There is no cap: `configured` is always False and `cap_eur` and `reserve_eur` are always None (the keys stay for
493
+ the hub schema, scripts/schemas/hub-spend.schema.json). `advise_eur` is the advise level and `advisory` is True at
494
+ or above it."""
498
495
  now = now or datetime.now(timezone.utc)
499
- try:
500
- cap = load_cap(home)
501
- cap_eur, reserve_eur = float(cap.eur_per_24h), float(cap.reserve)
502
- except NotConfigured:
503
- cap_eur = reserve_eur = None
504
- return {"schema": 1, "configured": cap_eur is not None, "cap_eur": cap_eur,
505
- "committed_eur": round(committed_last_24h(home, now), 6), "reserve_eur": reserve_eur,
506
- "window_h": 24}
496
+ committed, level = committed_last_24h(home, now), advise_eur()
497
+ return {"schema": 1, "configured": False, "cap_eur": None,
498
+ "committed_eur": round(committed, 6), "reserve_eur": None,
499
+ "window_h": 24, "advise_eur": level, "advisory": committed >= level}
507
500
 
508
501
 
509
502
  def main(argv: list[str] | None = None) -> int:
@@ -514,7 +507,7 @@ def main(argv: list[str] | None = None) -> int:
514
507
  if "--" in raw:
515
508
  i = raw.index("--")
516
509
  raw, tail = raw[:i], raw[i + 1:]
517
- parser = argparse.ArgumentParser(description="global agy spend cap (EUR per rolling 24 h, this machine)")
510
+ parser = argparse.ArgumentParser(description="agy usage log and run wrapper (EUR per rolling 24 h, this machine)")
518
511
  sub = parser.add_subparsers(dest="cmd", required=True)
519
512
  sub.add_parser("check")
520
513
  p_status = sub.add_parser("status")
@@ -532,23 +525,13 @@ def main(argv: list[str] | None = None) -> int:
532
525
  print(json.dumps(spend_json(home, now)) if args.json else status_line(home, now))
533
526
  except Exception as exc:
534
527
  print(f"caddis_spend: could not read the spend log: {exc!r}", file=sys.stderr)
535
- return EXIT_NOT_CONFIGURED
528
+ return EXIT_LOG_ERROR
536
529
  return EXIT_OK
537
- if args.cmd == "check":
538
- try:
539
- cap = load_cap(home)
540
- except NotConfigured:
541
- print(NOT_CONFIGURED_MESSAGE, file=sys.stderr)
542
- return EXIT_NOT_CONFIGURED
530
+ if args.cmd == "check": # there is no cap: always 0, so no caller is blocked by it
543
531
  try:
544
- committed = committed_last_24h(home, now)
532
+ print(f"ok: {status_line(home, now)}")
545
533
  except Exception as exc:
546
- print(f"caddis_spend: could not read the spend log: {exc!r}", file=sys.stderr)
547
- return EXIT_NOT_CONFIGURED
548
- if committed + cap.reserve > cap.eur_per_24h:
549
- print(f"over cap: {status_line(home, now)}")
550
- return EXIT_OVER_CAP
551
- print(f"ok: {status_line(home, now)}")
534
+ print(f"ok: caddis_spend: could not read the spend log: {exc!r}")
552
535
  return EXIT_OK
553
536
  if not tail:
554
537
  parser.error("run needs the agy command after --")
@@ -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: