polyctl 0.7.0__py3-none-any.whl

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 (99) hide show
  1. polyctl/__init__.py +7 -0
  2. polyctl/__main__.py +5 -0
  3. polyctl/a2a.py +226 -0
  4. polyctl/a2a_mcp.py +546 -0
  5. polyctl/acp.py +417 -0
  6. polyctl/adapters/README.md +101 -0
  7. polyctl/adapters/aider.json +32 -0
  8. polyctl/adapters/amazon-q.json +15 -0
  9. polyctl/adapters/amp.json +16 -0
  10. polyctl/adapters/antigravity.json +120 -0
  11. polyctl/adapters/claude-code.json +229 -0
  12. polyctl/adapters/cloud-generic.json +57 -0
  13. polyctl/adapters/codex.json +47 -0
  14. polyctl/adapters/command-code.json +45 -0
  15. polyctl/adapters/copilot.json +17 -0
  16. polyctl/adapters/cursor-agent.json +29 -0
  17. polyctl/adapters/deepseek.json +13 -0
  18. polyctl/adapters/droid.json +34 -0
  19. polyctl/adapters/gemini.json +30 -0
  20. polyctl/adapters/grok.json +22 -0
  21. polyctl/adapters/hermes.json +34 -0
  22. polyctl/adapters/kilocode.json +30 -0
  23. polyctl/adapters/kimi.json +23 -0
  24. polyctl/adapters/kiro.json +332 -0
  25. polyctl/adapters/ollama.json +29 -0
  26. polyctl/adapters/omp.json +34 -0
  27. polyctl/adapters/openai-api.json +68 -0
  28. polyctl/adapters/opencode.json +162 -0
  29. polyctl/adapters/pi.json +24 -0
  30. polyctl/adapters/pr-agent.json +54 -0
  31. polyctl/adapters/profiles.json +9 -0
  32. polyctl/adapters/qoder.json +163 -0
  33. polyctl/adapters/qwen.json +27 -0
  34. polyctl/adapters/reasonix.json +25 -0
  35. polyctl/adapters/rewriters/rtk.json +24 -0
  36. polyctl/adapters/trae.json +31 -0
  37. polyctl/adapters/vendors.json +42 -0
  38. polyctl/adapters/warp.json +88 -0
  39. polyctl/allowlist.py +1756 -0
  40. polyctl/api_review.py +920 -0
  41. polyctl/cli.py +835 -0
  42. polyctl/conformance_harness.py +9 -0
  43. polyctl/demo.py +503 -0
  44. polyctl/drivers.py +146 -0
  45. polyctl/email.py +160 -0
  46. polyctl/features.py +98 -0
  47. polyctl/journal.py +144 -0
  48. polyctl/language.py +945 -0
  49. polyctl/lib.py +1296 -0
  50. polyctl/matrix.py +660 -0
  51. polyctl/mcp.py +1362 -0
  52. polyctl/ntfy.py +169 -0
  53. polyctl/outbound.py +39 -0
  54. polyctl/parts/__init__.py +5 -0
  55. polyctl/parts/cli_authority.py +2615 -0
  56. polyctl/parts/cli_channels.py +1325 -0
  57. polyctl/parts/cli_checks.py +2293 -0
  58. polyctl/parts/cli_completion.py +686 -0
  59. polyctl/parts/cli_evidence.py +141 -0
  60. polyctl/parts/cli_gain.py +375 -0
  61. polyctl/parts/cli_harness.py +392 -0
  62. polyctl/parts/cli_hooks.py +1816 -0
  63. polyctl/parts/cli_install.py +638 -0
  64. polyctl/parts/cli_lanes.py +106 -0
  65. polyctl/parts/cli_maintenance.py +2536 -0
  66. polyctl/parts/cli_next.py +248 -0
  67. polyctl/parts/cli_pr.py +53 -0
  68. polyctl/parts/cli_project.py +2857 -0
  69. polyctl/parts/cli_review.py +5158 -0
  70. polyctl/parts/cli_status.py +898 -0
  71. polyctl/parts/lib_adapters.py +2933 -0
  72. polyctl/parts/lib_alarms.py +2106 -0
  73. polyctl/parts/lib_events.py +224 -0
  74. polyctl/parts/lib_evidence.py +412 -0
  75. polyctl/parts/lib_gates.py +2099 -0
  76. polyctl/parts/lib_lanes.py +829 -0
  77. polyctl/parts/lib_mail.py +1541 -0
  78. polyctl/parts/lib_next.py +652 -0
  79. polyctl/parts/lib_pr.py +331 -0
  80. polyctl/parts/lib_slices.py +3337 -0
  81. polyctl/parts/lib_state.py +2415 -0
  82. polyctl/parts/lib_transcript.py +4118 -0
  83. polyctl/pressure.py +325 -0
  84. polyctl/prices.json +47 -0
  85. polyctl/procs.py +1194 -0
  86. polyctl/settings.py +505 -0
  87. polyctl/skill/SKILL.md +365 -0
  88. polyctl/skillkit.py +503 -0
  89. polyctl/storage.py +2055 -0
  90. polyctl/telegram.py +327 -0
  91. polyctl/tiers.py +123 -0
  92. polyctl/verdicts.py +41 -0
  93. polyctl/watchdog.py +3887 -0
  94. polyctl/web.py +337 -0
  95. polyctl-0.7.0.dist-info/METADATA +235 -0
  96. polyctl-0.7.0.dist-info/RECORD +99 -0
  97. polyctl-0.7.0.dist-info/WHEEL +4 -0
  98. polyctl-0.7.0.dist-info/entry_points.txt +5 -0
  99. polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,141 @@
1
+ """Evidence: a platform lane's run recorded from CI, and what the recorded runs still vouch for (LANE-EVIDENCE).
2
+
3
+ A part of src/polyctl/cli.py, run in its namespace by `_part` as the parts split out of it are; it is
4
+ not importable on its own.
5
+
6
+ `polyctl gain` reads `.polyctl/ledger/platform-runs.jsonl` and nothing wrote it. `polyctl evidence record`
7
+ reads a lane's CI run through `gh` and writes one row from what the run reports, and `polyctl
8
+ evidence show` reads the newest row of each platform back with how far HEAD has moved since -
9
+ or every row. The same readings feed `polyctl doctor --check`, which names a newest run that is not
10
+ on this repository, not finished, not successful, not on a commit HEAD holds as an ancestor, or
11
+ past `evidence.max_commits_behind`.
12
+ """
13
+ import json
14
+ import time
15
+
16
+
17
+ def _evidence_when(at):
18
+ """When a row was recorded, as a person reads a date."""
19
+ if not isinstance(at, (int, float)) or isinstance(at, bool):
20
+ return "at an unknown time"
21
+ return time.strftime("%Y-%m-%d %H:%M", time.localtime(at))
22
+
23
+
24
+ def _evidence_state(row):
25
+ """The word and the tone a row is shown with: red, stale or green."""
26
+ if not row["green"]:
27
+ return C["red"], "red"
28
+ if row["stale"]:
29
+ return C["yellow"], "stale"
30
+ return C["green"], "green"
31
+
32
+
33
+ def _evidence_where(row):
34
+ """What the row's run and commit still say about HEAD, in the words a person reads."""
35
+ commit = str(row.get("commit") or "")
36
+ if not row.get("on_repository", True):
37
+ repo = row.get("repository") or "another repository"
38
+ return f"on {repo}, not this repository"
39
+ if not row.get("finished", True):
40
+ return f"{row.get('status') or 'unfinished'} at {commit[:10] or 'no commit'}"
41
+ if row["known"] and row["behind"] is not None:
42
+ return f"at {commit[:10]}, {row['behind']} commit(s) behind HEAD"
43
+ if row["known"]:
44
+ return f"at {commit[:10]}, not an ancestor of HEAD"
45
+ if commit:
46
+ return f"at {commit[:10]}, which this repository cannot place"
47
+ return "with no commit recorded"
48
+
49
+
50
+ def _evidence_counts(row):
51
+ """How a row's jobs and conclusion read on one line."""
52
+ conclusion = row.get("conclusion") or row.get("status") or "unknown"
53
+ if row.get("jobs_total") is not None:
54
+ return f"{row.get('jobs_passed') or 0}/{row['jobs_total']} job(s) passed ({conclusion})"
55
+ return str(conclusion)
56
+
57
+
58
+ def cmd_evidence(cfg, args):
59
+ """Record a platform lane's CI run as evidence, and say what the recorded runs still vouch for (LANE-EVIDENCE).
60
+
61
+ `record` reads the CI run through `gh` and appends one row to the chained
62
+ `.polyctl/ledger/platform-runs.jsonl`: the platform, the run's id, its status and conclusion,
63
+ its head commit, its repository, and its jobs. `show` reads the newest row of
64
+ each platform with how far HEAD has moved since, or every row with `--all`; a run that is
65
+ not on this repository, not finished, not successful, or not on a commit HEAD holds as an
66
+ ancestor never reads as green and vouches for nothing. `polyctl gain` shows the same rows, and
67
+ `polyctl doctor --check` names a newest run that is red, unplaceable, or past
68
+ `evidence.max_commits_behind`.
69
+ """
70
+ if getattr(args, "action", None) == "record":
71
+ return _evidence_record(cfg, args)
72
+ return _evidence_show(cfg, args)
73
+
74
+
75
+ def _evidence_record(cfg, args):
76
+ missing = [flag for flag, value in (("--platform", args.platform), ("--run", args.run))
77
+ if value is None or not str(value).strip()]
78
+ if missing:
79
+ print(f"{C['red']}nothing recorded{C['reset']}: record needs {', '.join(missing)}")
80
+ print(f"{C['dim']}polyctl evidence record --platform windows --run <id>{C['reset']}")
81
+ return 2
82
+ gh = A.runnable_binary("gh")
83
+ if not gh:
84
+ print(f"{C['red']}nothing recorded{C['reset']}: gh is not on this machine (PATH, binaries.extra_dirs, "
85
+ "the usual install directories): polyctl reads a lane's run only through GitHub's CLI. Install it and "
86
+ "run `gh auth login`")
87
+ return 1
88
+ root = cfg["root"]
89
+ try:
90
+ row = A.record_platform_run(root, platform=args.platform, run=args.run, gh=gh)
91
+ except (TypeError, ValueError) as exc:
92
+ print(f"{C['red']}nothing recorded{C['reset']}: {exc}")
93
+ return 2
94
+ except A.GhUnreadable as exc:
95
+ print(f"{C['red']}nothing recorded{C['reset']}: {exc}")
96
+ return 1
97
+ except Exception as exc:
98
+ print(f"{C['red']}nothing recorded{C['reset']}: the ledger could not be written "
99
+ f"({type(exc).__name__}: {exc})")
100
+ return 1
101
+ reading = A.platform_run_reading(root, cfg, row)
102
+ _, state = _evidence_state(reading)
103
+ commit = (row.get("commit") or "")[:10] or "no commit"
104
+ print(f"recorded {row['platform']} run {row['run']} ({state}): {_evidence_counts(row)} "
105
+ f"at {commit} ({row['suite']})")
106
+ return 0
107
+
108
+
109
+ def _evidence_show(cfg, args):
110
+ from .storage import _unattested_repair, unattested_in_tree
111
+ root = cfg["root"]
112
+ try:
113
+ foreign, attested = unattested_in_tree(root, A.PLATFORM_RUNS_FILE, A.PLATFORM_RUNS_CHAIN)
114
+ if getattr(args, "all", False):
115
+ rows = [A.platform_run_reading(root, cfg, row) for row in A.platform_runs(root)]
116
+ else:
117
+ rows = A.platform_run_summaries(root, cfg)
118
+ except Exception as exc:
119
+ print(f"{C['red']}{A.PLATFORM_RUNS_FILE} cannot be read{C['reset']}: {type(exc).__name__}: {exc}")
120
+ return 1
121
+ if getattr(args, "json", False):
122
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
123
+ return 0
124
+ print(f"{C['b']}polyctl evidence{C['reset']} {C['dim']}{A.PLATFORM_RUNS_FILE}{C['reset']}")
125
+ if foreign:
126
+ print(f" {C['yellow']}unattested{C['reset']} {A.PLATFORM_RUNS_FILE} holds "
127
+ f"{_unattested_repair(foreign, attested)}")
128
+ if not rows:
129
+ print(f" {C['dim']}no platform run recorded in {A.PLATFORM_RUNS_FILE}{C['reset']}")
130
+ print(f" {C['dim']}record one after a lane runs in CI: "
131
+ f"polyctl evidence record --platform windows --run <id>{C['reset']}")
132
+ return 0
133
+ bound = S.get(cfg, "evidence.max_commits_behind")
134
+ print(f" {C['dim']}{len(rows)} row(s), "
135
+ f"{'oldest first' if getattr(args, 'all', False) else 'the newest of each platform'}; "
136
+ f"evidence.max_commits_behind {bound}{C['reset']}")
137
+ for row in rows:
138
+ tone, state = _evidence_state(row)
139
+ print(f" {row['platform']:<10} {tone}{state:<8}{C['reset']} run {row.get('run')} · {row.get('suite')} · "
140
+ f"{_evidence_counts(row)} · {_evidence_where(row)} · {_evidence_when(row.get('at'))}")
141
+ return 0
@@ -0,0 +1,375 @@
1
+ """Gain: what polyctl measured, from the ledgers it already keeps (GAIN).
2
+
3
+ A part of src/polyctl/cli.py, run in its namespace by `_part` as the parts split out of it are; it is
4
+ not importable on its own.
5
+
6
+ One surface for the questions a person asks between slices: is work landing, what is it costing,
7
+ is review converging, what is the watchdog doing, and what did the lanes last prove. Every number
8
+ is read from a store polyctl wrote - the board, the review and slice ledgers, the implementer's own
9
+ transcript, the watchdog's logs - and nothing is estimated or inferred from a counter that does
10
+ not exist. `polyctl stats` reads outcomes alone, `polyctl cost` spend alone, `polyctl credits` the account
11
+ alone; this is the one place that reads them together, with a daily trend.
12
+ """
13
+ import os
14
+ import time
15
+ from datetime import datetime, timedelta
16
+
17
+ EVIDENCE_FILE = A.PLATFORM_RUNS_FILE
18
+ CLASSES = ("product", "analysis", "ceremony", "coordination")
19
+ BOARD_ORDER = ("running", "queued", "blocked", "verified", "inbox", "done", "rejected")
20
+
21
+
22
+ def _gain_number(value):
23
+ """A count a person reads at a glance: 1,204; 42k; 1.82M."""
24
+ if value is None:
25
+ return "—"
26
+ value = float(value)
27
+ if value >= 1_000_000:
28
+ return f"{value / 1_000_000:.2f}M"
29
+ if value >= 10_000:
30
+ return f"{value / 1_000:.0f}k"
31
+ return f"{value:,.0f}"
32
+
33
+
34
+ def _gain_hours(value):
35
+ return f"{value:g}h" if value is not None else "—"
36
+
37
+
38
+ def _gain_share(part, total):
39
+ return round(100 * part / total) if total else 0
40
+
41
+
42
+ def _gain_since(args):
43
+ """The window the command names, or None for everything recorded."""
44
+ when = A.parse_time(args.since) if getattr(args, "since", None) else None
45
+ return when
46
+
47
+
48
+ def _gain_project(cfg, project, when, days):
49
+ """Everything one project's ledgers say in this window, as values and not as text."""
50
+ root = cfg["root"]
51
+ since = when.moment() if when else None
52
+ out = {"project": project, "root": root, "window": when.label() if when else "whole history"}
53
+ try:
54
+ outcomes = [row for row in A.slice_outcomes(root, project)
55
+ if since is None or (row["landed_at"] or 0) >= since]
56
+ out["slices"] = A.outcome_stats(outcomes) if outcomes else None
57
+ out["slice_rows"] = outcomes
58
+ except Exception as exc:
59
+ out["slices"], out["slice_rows"] = None, []
60
+ out["slices_error"] = f"{type(exc).__name__}: {exc}"
61
+ try:
62
+ from .storage import read_chained_jsonl
63
+ rows = [row for row in read_chained_jsonl(A.review_ledger_path(root), A.REVIEW_CHAIN)
64
+ if isinstance(row, dict) and (since is None or (row.get("at") or 0) >= since)]
65
+ out["reviews"] = {
66
+ "rows": len(rows),
67
+ "approved": sum(1 for row in rows if row.get("verdict") == "APPROVED"),
68
+ "changes": sum(1 for row in rows if row.get("verdict") == "NEEDS_CHANGES"),
69
+ "other": sum(1 for row in rows if row.get("verdict") not in ("APPROVED", "NEEDS_CHANGES")),
70
+ "retrospective": sum(1 for row in rows if row.get("kind") == "commit-range"),
71
+ "reviewers": len({row.get("reviewer") for row in rows if row.get("reviewer")}),
72
+ "fallback": sum(1 for row in rows if row.get("fallback")),
73
+ }
74
+ except Exception as exc:
75
+ out["reviews"] = None
76
+ out["reviews_error"] = f"{type(exc).__name__}: {exc}"
77
+ try:
78
+ out["board"] = {state: len(items) for state, items in A.board(root).items()}
79
+ except Exception:
80
+ out["board"] = {}
81
+ turns = []
82
+ try:
83
+ costs = A.turn_costs(cfg, since=since)
84
+ turns = costs["turns"]
85
+ total = costs["total"]
86
+ delegated = sum(float(row.get("delegated") or 0) for row in costs["by_class"].values())
87
+ out["spend"] = {
88
+ "unit": costs["unit"], "total": total, "turns": len(turns), "delegated": delegated,
89
+ "classes": {name: {"turns": row["turns"], "usage": row["usage"],
90
+ "share": _gain_share(row["usage"], total),
91
+ "wasted": row.get("wasted", 0)}
92
+ for name, row in costs["by_class"].items()},
93
+ "overhead_share": _gain_share(sum(costs["by_class"].get(name, {}).get("usage", 0)
94
+ for name in ("ceremony", "coordination")), total),
95
+ "wasted": sum(row.get("wasted", 0) for row in costs["by_class"].values()),
96
+ "tool_calls": sum(row.get("tool_calls") or 0 for row in costs["turns"]),
97
+ "polyctl_commands": dict(costs["polyctl_commands"].most_common(6)),
98
+ }
99
+ except Exception as exc:
100
+ out["spend"] = None
101
+ out["spend_error"] = f"{type(exc).__name__}: {exc}"
102
+ try:
103
+ hunts = sum(1 for row in A.hunter_rows(root) if row.get("event") == "run"
104
+ and (since is None or (row.get("at") or 0) >= since))
105
+ except Exception:
106
+ hunts = 0
107
+ try:
108
+ notices = [row for row in A.notices(root, limit=10 ** 9, include_suppressed=True)
109
+ if since is None or (row.get("at") or 0) >= since]
110
+ except Exception:
111
+ notices = []
112
+ out["activity"] = {
113
+ "wakes": len(A.spawn_times(root, "architect_wake", since)),
114
+ "refills": len(A.spawn_times(root, "refill", since)),
115
+ "nudges": len(A.spawn_times(root, "nudge", since)),
116
+ "hunts": hunts,
117
+ "notices": len(notices),
118
+ "notices_sent": sum(1 for row in notices if row.get("sent")),
119
+ }
120
+ try:
121
+ from .storage import _unattested_repair, unattested_in_tree
122
+ foreign, attested = unattested_in_tree(root, EVIDENCE_FILE, A.PLATFORM_RUNS_CHAIN)
123
+ out["evidence"] = A.platform_run_summaries(root, cfg)
124
+ if foreign:
125
+ out["evidence_unattested"] = _unattested_repair(foreign, attested)
126
+ except Exception as exc:
127
+ out["evidence"] = None
128
+ out["evidence_error"] = f"{type(exc).__name__}: {exc}"
129
+ out["daily"] = _gain_daily(out, days, turns)
130
+ return out
131
+
132
+
133
+ def _gain_daily(project, days, turns):
134
+ """Spend and landings per day, for the last `days` days that end today."""
135
+ days = max(1, int(days or 14))
136
+ last = datetime.now().date()
137
+ first = last - timedelta(days=days - 1)
138
+ spend, landed = {}, {}
139
+ # The day is the turn's own: a long session that crossed midnight is charged where each turn started.
140
+ for row in turns:
141
+ if row.get("start"):
142
+ day = datetime.fromtimestamp(row["start"]).date()
143
+ spend[day] = spend.get(day, 0.0) + float(row.get("usage") or 0)
144
+ for row in project.get("slice_rows") or []:
145
+ if row.get("landed_at"):
146
+ day = datetime.fromtimestamp(row["landed_at"]).date()
147
+ landed[day] = landed.get(day, 0) + 1
148
+ return [{"date": (first + timedelta(days=offset)).isoformat(),
149
+ "spend": spend.get(first + timedelta(days=offset), 0.0),
150
+ "landed": landed.get(first + timedelta(days=offset), 0)}
151
+ for offset in range(days)]
152
+
153
+
154
+ def _gain_quota(cfg):
155
+ """The implementer's own account, when its adapter declares a lookup polyctl can run."""
156
+ ident = A.implementer_adapter_id(cfg)
157
+ api = A.usage_api(ident)
158
+ if not ident:
159
+ return {"adapter": "", "readable": False, "why": "no implementer adapter is configured"}
160
+ if not api:
161
+ return {"adapter": ident, "readable": False,
162
+ "why": "its adapter declares no account lookup polyctl can run"}
163
+ try:
164
+ account = A.account_usage(adapter_id=ident)
165
+ except Exception as exc:
166
+ return {"adapter": ident, "readable": True, "error": f"{type(exc).__name__}: {exc}"}
167
+ if not account:
168
+ return {"adapter": ident, "readable": True, "error": "the lookup returned nothing"}
169
+ if account.get("error") or account.get("expired"):
170
+ return {"adapter": ident, "readable": True,
171
+ "error": account.get("error") or "the account's token expired"}
172
+ used, limit = float(account.get("used") or 0), float(account.get("limit") or 0)
173
+ return {"adapter": ident, "readable": True, "used": used, "limit": limit,
174
+ "percent": round(100 * used / limit, 1) if limit else None,
175
+ "plan": account.get("plan"), "reset_at": account.get("reset_at")}
176
+
177
+
178
+ def _gain_totals(projects):
179
+ """The same headline over every project read: slices, spend and turns."""
180
+ slices = sum((row.get("slices") or {}).get("slices", 0) for row in projects)
181
+ spend = sum((row.get("spend") or {}).get("total", 0) for row in projects)
182
+ turns = sum((row.get("spend") or {}).get("turns", 0) for row in projects)
183
+ return {"slices": slices, "spend": spend, "turns": turns}
184
+
185
+
186
+ def cmd_gain(cfg, args):
187
+ """What polyctl measured here: slices, spend, reviews, activity, evidence and the daily trend (GAIN).
188
+
189
+ Read from the stores polyctl writes as it works; nothing is estimated, and a store that cannot be
190
+ read is named rather than shown as zero. `--all` reads every registered project. `--quota`
191
+ asks the implementer's account (one request) only when it is named.
192
+ """
193
+ when = _gain_since(args)
194
+ if getattr(args, "all", False):
195
+ roots = A.recall_roots(cfg["root"])
196
+ else:
197
+ roots = [(cfg.get("project") or A.project_key(cfg["root"]), cfg["root"])]
198
+ projects = []
199
+ for project, root in roots:
200
+ if os.path.realpath(root) == os.path.realpath(cfg["root"]):
201
+ grown = dict(cfg, root=root)
202
+ else:
203
+ try:
204
+ grown = dict(A.load_config(root), root=root)
205
+ except Exception as exc:
206
+ projects.append({"project": project, "root": root, "window": when.label() if when else
207
+ "whole history", "error": f"{type(exc).__name__}: {exc}"})
208
+ continue
209
+ try:
210
+ row = _gain_project(grown, project, when, getattr(args, "days", 14))
211
+ except Exception as exc:
212
+ row = {"project": project, "root": root, "window": when.label() if when else "whole history",
213
+ "error": f"{type(exc).__name__}: {exc}"}
214
+ if getattr(args, "quota", False) and "error" not in row:
215
+ row["quota"] = _gain_quota(grown)
216
+ projects.append(row)
217
+ if getattr(args, "json", False):
218
+ payload = {"projects": projects} if getattr(args, "all", False) else projects[0]
219
+ if getattr(args, "all", False) and len(projects) > 1:
220
+ payload["total"] = _gain_totals(projects)
221
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
222
+ return 0
223
+ for number, project in enumerate(projects):
224
+ if number:
225
+ print()
226
+ _gain_show(project, args)
227
+ if getattr(args, "all", False) and len(projects) > 1:
228
+ total = _gain_totals(projects)
229
+ print(f"\n{b}total{reset} {total['slices']} slice(s) · {_gain_number(total['spend'])} spent in "
230
+ f"{total['turns']} turn(s)")
231
+ return 0
232
+
233
+
234
+ def _gain_show(project, args):
235
+ """One project's block, in the order a person reads it: landed, reviewed, queued, spent, done."""
236
+ b, dim, reset, yellow, red = C["b"], C["dim"], C["reset"], C["yellow"], C["red"]
237
+ print(f"{b}polyctl gain · {project['project']}{reset} {dim}{project.get('window')}{reset}")
238
+ if project.get("error"):
239
+ print(f" {red}cannot read this project{reset}: {project['error']}")
240
+ return
241
+ stats = project.get("slices")
242
+ if stats:
243
+ parts = [f"{stats['slices']} landed", f"{stats['waived']} waived" if stats["waived"] else None,
244
+ f"{stats['product_lines']['median']} product lines median"
245
+ if stats.get("product_lines") else None]
246
+ print(f" {'slices':<10} " + " · ".join(part for part in parts if part))
247
+ detail = []
248
+ if stats.get("hours"):
249
+ detail.append(f"ready→landed median {_gain_hours(stats['hours']['median'])}, "
250
+ f"p90 {_gain_hours(stats['hours']['p90'])}")
251
+ if stats.get("rounds"):
252
+ detail.append(f"review rounds median {stats['rounds']['median']}")
253
+ if stats.get("first_pass_pct") is not None:
254
+ detail.append(f"{stats['first_pass_pct']}% first pass")
255
+ if stats.get("defects_pct") is not None:
256
+ detail.append(f"{stats['defects_pct']}% defect found later")
257
+ if detail:
258
+ print(f" {'':<10} " + " · ".join(detail))
259
+ for tier, count in (stats.get("tiers") or {}).items():
260
+ if tier:
261
+ print(f" {'':<10} {yellow}{count} on {tier}{reset}")
262
+ else:
263
+ why = project.get("slices_error")
264
+ print(f" {'slices':<10} {dim}{'cannot read the ledgers: ' + why if why else 'no landed slice in this window'}{reset}")
265
+ reviews = project.get("reviews")
266
+ if reviews is None:
267
+ print(f" {'reviews':<10} {dim}cannot read the review ledger: {project.get('reviews_error')}{reset}")
268
+ elif reviews["rows"]:
269
+ print(f" {'reviews':<10} {reviews['rows']} recorded · {reviews['approved']} approved · "
270
+ f"{reviews['changes']} changes · {reviews['other']} other · {reviews['reviewers']} reviewer(s)"
271
+ + (f" · {reviews['fallback']} fallback" if reviews["fallback"] else "")
272
+ + (f" · {reviews['retrospective']} retrospective" if reviews["retrospective"] else ""))
273
+ else:
274
+ print(f" {'reviews':<10} {dim}no review recorded in this window{reset}")
275
+ board = project.get("board") or {}
276
+ if board:
277
+ print(f" {'board':<10} " + " · ".join(f"{state} {board.get(state, 0)}" for state in BOARD_ORDER
278
+ if state in board))
279
+ spend = project.get("spend")
280
+ if spend is None:
281
+ print(f" {'spend':<10} {dim}cannot read the transcript: {project.get('spend_error')}{reset}")
282
+ elif spend["turns"]:
283
+ unit = spend["unit"] if spend["unit"] not in ("", "unit") else "units"
284
+ print(f" {'spend':<10} {_gain_number(spend['total'])} {unit} in {spend['turns']} turns · "
285
+ f"{_gain_number(spend['tool_calls'])} tool calls · {spend['wasted']} wasted turns")
286
+ shares = [f"{name} {row['share']}%" for name, row in spend["classes"].items() if row["usage"]]
287
+ if shares:
288
+ print(f" {'':<10} " + " · ".join(shares))
289
+ print(f" {'':<10} {spend['overhead_share']}% of spend in ceremony + coordination"
290
+ + (f" · {_gain_number(spend['delegated'])} delegated" if spend["delegated"] else ""))
291
+ if spend["polyctl_commands"]:
292
+ print(f" {'':<10} {dim}polyctl: " + ", ".join(f"{name} {count}"
293
+ for name, count in spend["polyctl_commands"].items()) + reset)
294
+ else:
295
+ print(f" {'spend':<10} {dim}no implementer turn in this window{reset}")
296
+ activity = project.get("activity") or {}
297
+ print(f" {'activity':<10} {activity.get('wakes', 0)} wakes · {activity.get('refills', 0)} refills · "
298
+ f"{activity.get('nudges', 0)} nudges · {activity.get('hunts', 0)} hunts · "
299
+ f"{activity.get('notices', 0)} notices ({activity.get('notices_sent', 0)} sent)")
300
+ evidence = project.get("evidence")
301
+ if evidence is None:
302
+ print(f" {'evidence':<10} {dim}cannot read {EVIDENCE_FILE}: {project.get('evidence_error')}{reset}")
303
+ elif evidence:
304
+ said = []
305
+ for row in evidence:
306
+ _, state = _evidence_state(row)
307
+ shown = state if state == "green" else f"{red if state == 'red' else yellow}{state}{reset}"
308
+ said.append(f"{row['platform']} {shown} {_evidence_where(row)}")
309
+ print(f" {'evidence':<10} " + " · ".join(said))
310
+ if project.get("evidence_unattested"):
311
+ print(f" {'':<10} {yellow}{EVIDENCE_FILE} holds {project['evidence_unattested']}{reset}")
312
+ elif project.get("evidence_unattested"):
313
+ print(f" {'evidence':<10} {dim}no platform run recorded here ({EVIDENCE_FILE} holds "
314
+ f"{project['evidence_unattested']}){reset}")
315
+ else:
316
+ print(f" {'evidence':<10} {dim}no platform run recorded ({EVIDENCE_FILE}){reset}")
317
+ quota = project.get("quota")
318
+ if quota is not None:
319
+ if not quota.get("readable"):
320
+ print(f" {'quota':<10} {dim}{quota.get('adapter') or 'no adapter'}: {quota.get('why')}{reset}")
321
+ elif quota.get("error"):
322
+ print(f" {'quota':<10} {yellow}{quota.get('adapter')}: {quota['error']}{reset}")
323
+ else:
324
+ tone = red if (quota.get("percent") or 0) > 90 else yellow if (quota.get("percent") or 0) > 70 else ""
325
+ reset_at = time.strftime("%d %b", time.localtime(quota["reset_at"])) if quota.get("reset_at") else "?"
326
+ print(f" {'quota':<10} {tone}{quota.get('plan') or quota.get('adapter')} "
327
+ f"{quota.get('percent')}% used{reset} · {_gain_number(quota['limit'] - quota['used'])} remaining"
328
+ f" · resets {reset_at}")
329
+ if getattr(args, "slices", False) and project.get("slice_rows"):
330
+ print(f" {dim}slices{reset}")
331
+ for row in project["slice_rows"]:
332
+ marks = " → ".join(row.get("verdicts") or []) or "waived"
333
+ facts = [f"{row['rounds']} round(s)" if row.get("rounds") else None,
334
+ _gain_hours(row.get("hours")) if row.get("hours") is not None else None,
335
+ f"{row['size']['kinds']['product']['added'] + row['size']['kinds']['product']['deleted']} "
336
+ "product lines" if isinstance(row.get("size"), dict) else None,
337
+ "defect found later" if row.get("defect_found") else None,
338
+ f"tier {row['tier']}" if row.get("tier") else None]
339
+ print(f" {row['slice']:<16} {marks} {dim}{' · '.join(fact for fact in facts if fact)}{reset}")
340
+ if getattr(args, "sources", False):
341
+ spent = _gain_source_of(project)
342
+ print(f" {'sources':<10} {dim}.polyctl/board.md · .polyctl/ledger/reviews.jsonl · .polyctl/ledger/slices.jsonl · "
343
+ f"{EVIDENCE_FILE} · {spent}{reset}")
344
+ daily = project.get("daily") or []
345
+ if any(row["spend"] or row["landed"] for row in daily):
346
+ print(f"\n {dim}last {len(daily)} days{'':<12}spend landed{reset}")
347
+ peak = max(row["spend"] for row in daily) or 1
348
+ for row in daily:
349
+ width = round(18 * row["spend"] / peak) if row["spend"] else 0
350
+ bar = "█" * min(width, 18) + ("" if not row["spend"] else "▏")
351
+ print(f" {row['date'][5:]:<6} {bar:<19} {_gain_number(row['spend']):>8} {row['landed']:>6}")
352
+ else:
353
+ print(f"\n {dim}no spend or landing in the last {len(daily)} days{reset}")
354
+
355
+
356
+ def _gain_source_of(project):
357
+ """The transcript a project's spend was read from, named as the adapter resolved it."""
358
+ try:
359
+ cfg = dict(A.load_config(project["root"]), root=project["root"])
360
+ path, _ = A.session_paths(cfg)
361
+ except Exception:
362
+ path = None
363
+ return f"transcript: {path}" if path else "no transcript resolved"
364
+
365
+
366
+ def cmd_export(cfg, args):
367
+ """Export the project's ledger as OpenTelemetry traces in the OTLP/JSON encoding (EXPORT-OTLP)."""
368
+ payload = A.export_otlp(cfg["root"], cfg, attested=bool(getattr(args, "attested", False)))
369
+ text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
370
+ if args.out:
371
+ from .storage import replace_file_durably
372
+ replace_file_durably(os.path.expanduser(args.out), text.encode(UTF8))
373
+ return 0
374
+ sys.stdout.write(text)
375
+ return 0