tempergraph 0.7.1__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 (232) hide show
  1. tempergraph/__init__.py +8 -0
  2. tempergraph/__main__.py +5 -0
  3. tempergraph/api.py +428 -0
  4. tempergraph/audit/__init__.py +305 -0
  5. tempergraph/audit/catalog.py +342 -0
  6. tempergraph/audit/definition.py +387 -0
  7. tempergraph/audit/history.py +414 -0
  8. tempergraph/audit/history_rules.py +268 -0
  9. tempergraph/audit/history_rules_more.py +244 -0
  10. tempergraph/audit/host.py +270 -0
  11. tempergraph/audit/owned.py +96 -0
  12. tempergraph/audit/prompts.py +89 -0
  13. tempergraph/audit/report.py +248 -0
  14. tempergraph/audit/revisit.py +220 -0
  15. tempergraph/audit/surface.py +224 -0
  16. tempergraph/audit/text_health.py +176 -0
  17. tempergraph/audit/tools.py +391 -0
  18. tempergraph/author/__init__.py +2 -0
  19. tempergraph/author/blueprint.py +346 -0
  20. tempergraph/author/compare.py +122 -0
  21. tempergraph/author/criteria_lint.py +200 -0
  22. tempergraph/author/draw.py +112 -0
  23. tempergraph/author/inventory.py +210 -0
  24. tempergraph/author/literals.py +138 -0
  25. tempergraph/author/scaffold.py +568 -0
  26. tempergraph/author/session.py +439 -0
  27. tempergraph/author/trial.py +391 -0
  28. tempergraph/author/verify.py +353 -0
  29. tempergraph/builtin/__init__.py +1 -0
  30. tempergraph/builtin/upgrade.py +288 -0
  31. tempergraph/catalog.py +134 -0
  32. tempergraph/check_helpers.py +99 -0
  33. tempergraph/cli/__init__.py +1 -0
  34. tempergraph/cli/audit.py +190 -0
  35. tempergraph/cli/author.py +361 -0
  36. tempergraph/cli/improve.py +564 -0
  37. tempergraph/cli/improve_review.py +111 -0
  38. tempergraph/cli/install.py +35 -0
  39. tempergraph/cli/main.py +1261 -0
  40. tempergraph/cli/observe_cli.py +544 -0
  41. tempergraph/cli/outcome.py +77 -0
  42. tempergraph/cli/schedule_cli.py +1090 -0
  43. tempergraph/cli/upgrade.py +126 -0
  44. tempergraph/cli/workflows.py +96 -0
  45. tempergraph/compiler/__init__.py +6 -0
  46. tempergraph/compiler/graph.py +305 -0
  47. tempergraph/compiler/state.py +229 -0
  48. tempergraph/constants.py +72 -0
  49. tempergraph/contracts.py +1025 -0
  50. tempergraph/data/executor_compat.json +11 -0
  51. tempergraph/data/promotion.json +35 -0
  52. tempergraph/data/release.json +20 -0
  53. tempergraph/detach.py +65 -0
  54. tempergraph/docs.py +90 -0
  55. tempergraph/durability/__init__.py +2 -0
  56. tempergraph/durability/alias.py +66 -0
  57. tempergraph/durability/carry.py +591 -0
  58. tempergraph/durability/checkpoint.py +179 -0
  59. tempergraph/durability/control.py +109 -0
  60. tempergraph/durability/engine_file.py +301 -0
  61. tempergraph/durability/lock.py +138 -0
  62. tempergraph/durability/status.py +390 -0
  63. tempergraph/engine_identity.py +42 -0
  64. tempergraph/executor_compat.py +56 -0
  65. tempergraph/executors/__init__.py +4 -0
  66. tempergraph/executors/binding.py +91 -0
  67. tempergraph/executors/capabilities.py +95 -0
  68. tempergraph/executors/claude.py +603 -0
  69. tempergraph/executors/launcher.py +394 -0
  70. tempergraph/executors/mcpconfig.py +156 -0
  71. tempergraph/executors/mcpproxy.py +216 -0
  72. tempergraph/executors/preflight.py +196 -0
  73. tempergraph/executors/registry.py +71 -0
  74. tempergraph/executors/scripted.py +18 -0
  75. tempergraph/executors/session.py +107 -0
  76. tempergraph/executors/standins.py +118 -0
  77. tempergraph/executors/summary.py +110 -0
  78. tempergraph/executors/viewcatalog.py +27 -0
  79. tempergraph/git.py +403 -0
  80. tempergraph/identity.py +65 -0
  81. tempergraph/improve/__init__.py +5 -0
  82. tempergraph/improve/analysis.py +437 -0
  83. tempergraph/improve/artifact.py +477 -0
  84. tempergraph/improve/autonomy.py +192 -0
  85. tempergraph/improve/bindings.py +191 -0
  86. tempergraph/improve/calibration.py +1016 -0
  87. tempergraph/improve/causes.py +416 -0
  88. tempergraph/improve/child.py +651 -0
  89. tempergraph/improve/codehost.py +520 -0
  90. tempergraph/improve/digest.py +472 -0
  91. tempergraph/improve/escape.py +100 -0
  92. tempergraph/improve/filing.py +1047 -0
  93. tempergraph/improve/harvest.py +158 -0
  94. tempergraph/improve/issue_context.py +192 -0
  95. tempergraph/improve/lenses.py +204 -0
  96. tempergraph/improve/lessons.py +233 -0
  97. tempergraph/improve/loop_report.py +138 -0
  98. tempergraph/improve/loop_summary.py +85 -0
  99. tempergraph/improve/lost.py +119 -0
  100. tempergraph/improve/measure.py +121 -0
  101. tempergraph/improve/params.py +98 -0
  102. tempergraph/improve/pause_facts.py +134 -0
  103. tempergraph/improve/pr_later.py +186 -0
  104. tempergraph/improve/prebinding.py +130 -0
  105. tempergraph/improve/promotion.py +413 -0
  106. tempergraph/improve/proposals.py +934 -0
  107. tempergraph/improve/record.py +322 -0
  108. tempergraph/improve/release.py +89 -0
  109. tempergraph/improve/reliability.py +457 -0
  110. tempergraph/improve/repeat.py +115 -0
  111. tempergraph/improve/review.py +910 -0
  112. tempergraph/improve/suites.py +586 -0
  113. tempergraph/improve/trials.py +525 -0
  114. tempergraph/install/__init__.py +11 -0
  115. tempergraph/install/bootstrap.py +133 -0
  116. tempergraph/install/environment.py +173 -0
  117. tempergraph/install/launch.py +37 -0
  118. tempergraph/install/python.py +53 -0
  119. tempergraph/install/reconcile.py +52 -0
  120. tempergraph/install/selfcheck.py +29 -0
  121. tempergraph/install/shim.py +81 -0
  122. tempergraph/install/update.py +400 -0
  123. tempergraph/model/__init__.py +0 -0
  124. tempergraph/model/diagram.py +185 -0
  125. tempergraph/model/flow.py +324 -0
  126. tempergraph/model/prompt_lint.py +203 -0
  127. tempergraph/model/retire.py +52 -0
  128. tempergraph/model/subworkflow.py +274 -0
  129. tempergraph/model/text.py +67 -0
  130. tempergraph/model/validate.py +1158 -0
  131. tempergraph/observe/__init__.py +1 -0
  132. tempergraph/observe/attention.py +196 -0
  133. tempergraph/observe/detail.py +773 -0
  134. tempergraph/observe/forget.py +138 -0
  135. tempergraph/observe/hooks.py +272 -0
  136. tempergraph/observe/labels.py +95 -0
  137. tempergraph/observe/overlay.py +46 -0
  138. tempergraph/observe/report.py +402 -0
  139. tempergraph/observe/risk_report.py +110 -0
  140. tempergraph/observe/rows.py +444 -0
  141. tempergraph/observe/sinks.py +793 -0
  142. tempergraph/observe/supervision_cost.py +797 -0
  143. tempergraph/observe/supervision_report.py +295 -0
  144. tempergraph/observe/switch_report.py +140 -0
  145. tempergraph/package/__init__.py +2 -0
  146. tempergraph/package/change_report.py +116 -0
  147. tempergraph/package/changelog.py +263 -0
  148. tempergraph/package/docs_check.py +115 -0
  149. tempergraph/package/importer.py +90 -0
  150. tempergraph/package/inventory.py +111 -0
  151. tempergraph/package/loader.py +250 -0
  152. tempergraph/package/manifest.py +256 -0
  153. tempergraph/package/readiness.py +124 -0
  154. tempergraph/package/registry.py +383 -0
  155. tempergraph/package/rules.py +128 -0
  156. tempergraph/package/scan.py +65 -0
  157. tempergraph/package/selftest.py +348 -0
  158. tempergraph/package/stamp.py +213 -0
  159. tempergraph/package/transforms.py +481 -0
  160. tempergraph/package/upgrade.py +625 -0
  161. tempergraph/provenance.py +183 -0
  162. tempergraph/py.typed +0 -0
  163. tempergraph/release.py +17 -0
  164. tempergraph/render/__init__.py +0 -0
  165. tempergraph/render/output.py +72 -0
  166. tempergraph/render/prompt.py +166 -0
  167. tempergraph/render/template.py +86 -0
  168. tempergraph/run/__init__.py +2 -0
  169. tempergraph/run/asking.py +233 -0
  170. tempergraph/run/audit.py +63 -0
  171. tempergraph/run/check_worker.py +167 -0
  172. tempergraph/run/checks.py +517 -0
  173. tempergraph/run/commands.py +210 -0
  174. tempergraph/run/complexity.py +268 -0
  175. tempergraph/run/contest.py +76 -0
  176. tempergraph/run/council.py +368 -0
  177. tempergraph/run/council_run.py +527 -0
  178. tempergraph/run/events.py +279 -0
  179. tempergraph/run/finalize.py +132 -0
  180. tempergraph/run/gate.py +747 -0
  181. tempergraph/run/guard.py +89 -0
  182. tempergraph/run/judging.py +357 -0
  183. tempergraph/run/ladder.py +230 -0
  184. tempergraph/run/log.py +600 -0
  185. tempergraph/run/mapping.py +183 -0
  186. tempergraph/run/nodes.py +2304 -0
  187. tempergraph/run/outcome.py +255 -0
  188. tempergraph/run/outcome_record.py +292 -0
  189. tempergraph/run/outcome_trust.py +99 -0
  190. tempergraph/run/rerun.py +351 -0
  191. tempergraph/run/reserve.py +85 -0
  192. tempergraph/run/resources.py +76 -0
  193. tempergraph/run/risk.py +231 -0
  194. tempergraph/run/runner.py +1579 -0
  195. tempergraph/run/scriptcache.py +178 -0
  196. tempergraph/run/selfcheck.py +105 -0
  197. tempergraph/run/session_record.py +72 -0
  198. tempergraph/run/subrun.py +278 -0
  199. tempergraph/run/supervision.py +125 -0
  200. tempergraph/run/tool_access.py +101 -0
  201. tempergraph/schedule/__init__.py +25 -0
  202. tempergraph/schedule/credentials.py +167 -0
  203. tempergraph/schedule/echo.py +169 -0
  204. tempergraph/schedule/exact.py +275 -0
  205. tempergraph/schedule/export.py +164 -0
  206. tempergraph/schedule/launch.py +89 -0
  207. tempergraph/schedule/ledger.py +133 -0
  208. tempergraph/schedule/loop.py +176 -0
  209. tempergraph/schedule/model.py +440 -0
  210. tempergraph/schedule/policies.py +414 -0
  211. tempergraph/schedule/store.py +150 -0
  212. tempergraph/schedule/tick.py +377 -0
  213. tempergraph/schedule/token.py +81 -0
  214. tempergraph/schedule/triggers.py +210 -0
  215. tempergraph/schedule/words.py +423 -0
  216. tempergraph/security/__init__.py +0 -0
  217. tempergraph/security/launch.py +25 -0
  218. tempergraph/security/scrub.py +58 -0
  219. tempergraph/settings.py +950 -0
  220. tempergraph/store/__init__.py +0 -0
  221. tempergraph/store/codelog.py +73 -0
  222. tempergraph/store/layout.py +198 -0
  223. tempergraph/store/logs.py +325 -0
  224. tempergraph/store/manifest.py +99 -0
  225. tempergraph/store/migrate.py +188 -0
  226. tempergraph/workspace.py +874 -0
  227. tempergraph-0.7.1.dist-info/METADATA +70 -0
  228. tempergraph-0.7.1.dist-info/RECORD +232 -0
  229. tempergraph-0.7.1.dist-info/WHEEL +5 -0
  230. tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
  231. tempergraph-0.7.1.dist-info/top_level.txt +2 -0
  232. tempergraph_pytest_plugin.py +64 -0
@@ -0,0 +1,544 @@
1
+ """Observability verbs of the CLI kept apart from the core verbs: `logs` and `store` (LOS-B14, LOS-B15).
2
+
3
+ `cli/main.py` adds these parsers and commands; every helper it shares (the environment, selectors, output) is
4
+ taken from there, so the verbs follow the same exit codes and output rules (CLI-B17, CLI-B18, CLI-B19).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from tempergraph.observe.rows import BY
15
+
16
+
17
+ def add_parsers(sub: Any) -> None:
18
+ lg = sub.add_parser("logs", help="one log of a run from the local store (LOS)")
19
+ lg.add_argument("selector")
20
+ lg.add_argument("--session", metavar="KEY", help="a session key, or <unit>[.<attempt>] with --kind check")
21
+ lg.add_argument("--kind", choices=("run", "raw", "activity", "stderr", "check", "hook", "engine"))
22
+ lg.add_argument("--follow", action="store_true")
23
+ lg.add_argument("--json", action="store_true", help="the file list as JSON (with no --kind)")
24
+ lg.add_argument("--timeout", type=float, help=argparse.SUPPRESS)
25
+ so = sub.add_parser("store", help="size, retention and export of the local store (LOS)")
26
+ ssub = so.add_subparsers(dest="action")
27
+ us = ssub.add_parser("usage")
28
+ us.add_argument("--json", action="store_true")
29
+ pr = ssub.add_parser("prune")
30
+ pr.add_argument("--older-than", type=float, default=30.0, metavar="DAYS")
31
+ pr.add_argument("--keep-failed", action=argparse.BooleanOptionalAction, default=True,
32
+ help="keep the logs of stopped or failed threads (the default); --no-keep-failed prunes them")
33
+ pr.add_argument("--schedules", action="store_true",
34
+ help="also drop scheduled-run ledger rows older than --older-than days (TCK-B23); kept without it")
35
+ pr.add_argument("--dry-run", action="store_true")
36
+ pr.add_argument("--json", action="store_true")
37
+ ex = ssub.add_parser("export")
38
+ ex.add_argument("selector")
39
+ ex.add_argument("path")
40
+ rp = sub.add_parser("report", help="cost and friction reports over this state root's runs (OBS-B15)")
41
+ rp.add_argument("window", nargs="?", default="30d", help="7d, 24h, 30d (the default) or all")
42
+ rp.add_argument("--by", choices=("unit", "executor", "version", "workflow", "host", "level", "schedule"), default=None)
43
+ rp.add_argument("--supervision", action="store_true", help="touches, levels, waits and supervision cost (SUP-B12)")
44
+ rp.add_argument("--loop", action="store_true", help="the self-improvement loop's own figures (IMD-B22)")
45
+ rp.add_argument("--switch", metavar="WORKFLOW/SWITCH", help="finished runs per arm and zone (CXR-B13)")
46
+ rp.add_argument("--risk", metavar="WORKFLOW", help="judge attempts per gate and risk level (JRK-B10)")
47
+ rp.add_argument("--json", action="store_true")
48
+ lb = sub.add_parser("label", help="a person's label on a gate judgement (FBK-B9 explicit)")
49
+ lb.add_argument("selector")
50
+ lb.add_argument("gate", metavar="UNIT")
51
+ lb.add_argument("--value", required=True, choices=("agree", "disagree"))
52
+ lb.add_argument("--criterion")
53
+ lb.add_argument("--attempt", type=int)
54
+ lb.add_argument("--caller", choices=("person", "agent", "pipeline", "orchestrator", "scheduler", "engine"))
55
+ lb.add_argument("--as-agent", action="store_true")
56
+ lb.add_argument("--caller-app")
57
+ lb.add_argument("--relayed", action="store_true")
58
+ lb.add_argument("--json", action="store_true")
59
+ sa = sub.add_parser("stats", help="per-user monthly run rows, and across machines from a sink (CST-B14, CST-B15, CST-B16)")
60
+ sa.add_argument("action", nargs="?", choices=("flush", "sync", "forget"))
61
+ sa.add_argument("--check", action="store_true",
62
+ help="with forget: print the state roots and rows it would remove and change nothing (CST-B17 to CST-B24)")
63
+ src = sa.add_mutually_exclusive_group()
64
+ src.add_argument("--source", metavar="SINK")
65
+ src.add_argument("--local", action="store_true")
66
+ sa.add_argument("--sync", action="store_true")
67
+ when = sa.add_mutually_exclusive_group()
68
+ when.add_argument("--month", metavar="YYYY-MM", help="the month to show; `stats forget` takes none (CST-B24)")
69
+ when.add_argument("--since", metavar="YYYY-MM-DD")
70
+ sa.add_argument("--by", choices=BY)
71
+ sa.add_argument("--projection", action="store_true")
72
+ sa.add_argument("--live", action="store_true")
73
+ sa.add_argument("--json", action="store_true")
74
+ sv = sub.add_parser("supervision", help="the supervision journal and the cost of supervising runs (SCO-B16)")
75
+ svs = sv.add_subparsers(dest="action")
76
+ hk = svs.add_parser("hook", help="one host hook event read from standard input; always exit 0 (SHL-B14, SHL-B15)")
77
+ hk.add_argument("event")
78
+ lo = svs.add_parser("log", help="journal entries read as JSON lines from standard input")
79
+ lo.add_argument("--host", required=True)
80
+ lo.add_argument("--session", required=True)
81
+ lo.add_argument("--caller-app")
82
+ cl = svs.add_parser("close", help="close the threads whose supervising sessions have ended (SCO-B15)")
83
+ cl.add_argument("--session")
84
+ sh = svs.add_parser("show", help="a thread's or a session's supervision (read-only)")
85
+ sh.add_argument("selector", nargs="?")
86
+ sh.add_argument("--session")
87
+ sh.add_argument("--json", action="store_true")
88
+ at = sub.add_parser("attention", help="everything waiting on a person, oldest first (CLI-B6)")
89
+ at.add_argument("--all-roots", action="store_true")
90
+ at.add_argument("--json", action="store_true")
91
+
92
+
93
+ def cmd_logs(env: Any, a: argparse.Namespace) -> int:
94
+ from tempergraph.cli.main import UsageError, _emit, _one, _root
95
+ from tempergraph.store import logs
96
+
97
+ root = _root(env)
98
+ _spec, tid = _one(env, a.selector)
99
+ t = logs.find(root, tid)
100
+ if not a.kind:
101
+ files = logs.run_files(t)
102
+ if a.json:
103
+ _emit(env, {"schema_version": 1, "thread_id": tid, "files": files})
104
+ else:
105
+ for f in files:
106
+ env.out.write(f"{f['bytes']:>10} {f['kind']:<9} {f['path']}\n")
107
+ return 0
108
+ try:
109
+ paths = logs.log_path(root, t, a.kind, a.session)
110
+ except LookupError as exc:
111
+ raise UsageError(str(exc)) from exc
112
+ if not paths or not any(p.exists() for p in paths):
113
+ raise UsageError(f"{tid} has no {a.kind} log{f' for {a.session}' if a.session else ''}"
114
+ " (pruned, never written, or capture lowered)")
115
+ if a.follow:
116
+ if len(paths) != 1:
117
+ raise UsageError("--follow takes one file: name it with --session")
118
+ from tempergraph.durability.lock import is_held
119
+ from tempergraph.store.layout import lock_path
120
+
121
+ lock = lock_path(root, t.workflow, t.task_id)
122
+ for line in logs.follow(paths[0], lambda: is_held(lock), timeout_s=a.timeout):
123
+ env.out.write(line + "\n")
124
+ env.out.flush()
125
+ return 0
126
+ for line in logs.read_lines(paths, a.kind, tid):
127
+ env.out.write(line + "\n")
128
+ return 0
129
+
130
+
131
+ def cmd_store(env: Any, a: argparse.Namespace) -> int:
132
+ from tempergraph.cli.main import UsageError, _emit, _one, _root
133
+ from tempergraph.store import logs
134
+
135
+ root = _root(env)
136
+ if a.action == "usage":
137
+ doc = logs.usage(root)
138
+ if a.json:
139
+ _emit(env, doc)
140
+ else:
141
+ env.out.write(f"{doc['total_bytes']:>12} total {doc['state_root']}\n")
142
+ for t in doc["threads"]:
143
+ mark = " past retention" if t["past_retention"] else ""
144
+ env.out.write(f"{t['bytes']:>12} {t['thread_id']}{mark}\n")
145
+ for w in doc["warnings"]:
146
+ env.err.write(f"warning: {w}\n")
147
+ return 0
148
+ if a.action == "prune":
149
+ if a.older_than < 0:
150
+ raise UsageError("--older-than takes a number of days, 0 or more")
151
+ plan = logs.plan_prune(root, time.time(), a.older_than, a.keep_failed)
152
+ failed = [] if a.dry_run else logs.apply(plan)
153
+ pruned: dict[str, Any] = {"schema_version": 1, "dry_run": a.dry_run, "bytes": plan.bytes() if a.dry_run else None,
154
+ "removed" if not a.dry_run else "would_remove":
155
+ [str(p.relative_to(root)) for p in plan.remove],
156
+ "refused": plan.refused, "kept_failed": plan.kept_failed, "failed": failed}
157
+ from tempergraph.observe import supervision_cost as sco
158
+ from tempergraph.store.layout import home_path
159
+
160
+ old = sco.prunable_journals(home_path(), time.time()) # SCO-B17: kept 90 days, like evidence
161
+ gone = [] if a.dry_run else logs.apply(logs.Plan(remove=old))
162
+ pruned["journals_removed" if not a.dry_run else "journals_would_remove"] = [str(p) for p in old]
163
+ pruned["failed"] += gone
164
+ if a.schedules: # TCK-B23: the one thing that shortens the machine-wide ledger
165
+ from tempergraph.cli import schedule_cli
166
+ from tempergraph.schedule import ledger
167
+
168
+ pruned["ledger_fires_removed" if not a.dry_run else "ledger_fires_would_remove"] = ledger.prune(
169
+ a.older_than, schedule_cli.CLOCK(), dry_run=a.dry_run)
170
+ if a.json or a.dry_run:
171
+ _emit(env, pruned)
172
+ else:
173
+ env.err.write(f"store prune: {len(plan.remove)} removed, {len(plan.refused)} running threads left alone"
174
+ f"{f', {len(failed)} could not be removed' if failed else ''}\n")
175
+ return 0
176
+ if a.action == "export":
177
+ _spec, tid = _one(env, a.selector)
178
+ target = (env.cwd / a.path).resolve()
179
+ if not target.name.endswith(".tar.gz"):
180
+ raise UsageError("store export writes a .tar.gz archive")
181
+ if target.is_relative_to(root):
182
+ raise UsageError("the archive must be written outside the state root")
183
+ _emit(env, logs.export(logs.find(root, tid), target))
184
+ return 0
185
+ raise UsageError("store needs usage, prune or export")
186
+
187
+
188
+ def roots(env: Any, all_roots: bool) -> list[Path]:
189
+ """This repository's state root, or every root of the machine index (`--all-roots`, CST-B8)."""
190
+ from tempergraph.cli.main import _root
191
+ from tempergraph.observe.rows import index_roots
192
+
193
+ if not all_roots:
194
+ return [_root(env)]
195
+ found = [Path(r["path"]) for r in index_roots()]
196
+ try:
197
+ here = _root(env)
198
+ if here not in found:
199
+ found.insert(0, here)
200
+ except Exception: # noqa: BLE001 - outside a repository, the index alone
201
+ pass
202
+ return found
203
+
204
+
205
+ def _loop_report(env: Any, a: argparse.Namespace, since: Any) -> int:
206
+ from tempergraph.cli.main import _emit, _root
207
+ from tempergraph.improve import calibration as cal
208
+ from tempergraph.improve import loop_report as lr
209
+ from tempergraph.improve import reliability as rel
210
+
211
+ root = _root(env)
212
+ specs = env.catalog.specs
213
+ names = sorted(set(specs) | {p.name for p in (root / "runs").iterdir() if p.is_dir()}
214
+ if (root / "runs").is_dir() else set(specs))
215
+
216
+ def coverage(w: str) -> list[str]:
217
+ spec = specs.get(w)
218
+ if spec is None:
219
+ return []
220
+ try:
221
+ return [g["grade"] for g in rel.report(root, w, cal.judged_gates(spec),
222
+ lambda gate, binding: cal.passing(spec, gate))]
223
+ except Exception: # noqa: BLE001 - a gate that cannot be graded is left out of coverage
224
+ return []
225
+
226
+ doc = lr.report(root, names, since, coverage)
227
+ if a.json:
228
+ _emit(env, doc)
229
+ else:
230
+ env.out.write(lr.text(doc))
231
+ return 0
232
+
233
+
234
+ def _risk_report(env: Any, a: argparse.Namespace) -> int:
235
+ from tempergraph.cli.main import _emit, _root
236
+ from tempergraph.observe import risk_report as rr
237
+
238
+ doc = rr.report(_root(env), str(a.risk))
239
+ if a.json:
240
+ _emit(env, doc)
241
+ else:
242
+ env.out.write(rr.text(doc))
243
+ return 0
244
+
245
+
246
+ def _switch_report(env: Any, a: argparse.Namespace, since: Any) -> int:
247
+ from tempergraph.cli.main import UsageError, _emit, _root
248
+ from tempergraph.model import flow
249
+ from tempergraph.observe import switch_report as swr
250
+
251
+ workflow, _, switch = str(a.switch).partition("/")
252
+ if not workflow or not switch:
253
+ raise UsageError("report --switch takes <workflow>/<switch>")
254
+ spec = env.catalog.specs.get(workflow)
255
+ units: set[str] | None = None
256
+ size: str | None = None
257
+ if spec is not None:
258
+ u = spec.units.get(switch)
259
+ if u is None or u.switch is None:
260
+ raise UsageError(f"{workflow} has no switch {switch!r}")
261
+ comp = u.switch.complexity
262
+ units = set().union(*[flow.arm_units(spec, e) for e in u.switch.arms.values()])
263
+ if comp is not None:
264
+ units -= flow.arm_units(spec, comp.joins_at)
265
+ size = comp.size
266
+ doc = swr.report(_root(env), workflow, switch, since, units=units, size=size)
267
+ if a.json:
268
+ _emit(env, doc)
269
+ else:
270
+ env.out.write(swr.text(doc))
271
+ return 0
272
+
273
+
274
+ def cmd_report(env: Any, a: argparse.Namespace) -> int:
275
+ from tempergraph.cli.main import UsageError, _emit, _root
276
+ from tempergraph.observe import report as rep
277
+ from tempergraph.observe import rows
278
+
279
+ try:
280
+ since = rep.window(a.window)
281
+ except ValueError as exc:
282
+ raise UsageError(str(exc)) from exc
283
+ if a.loop:
284
+ return _loop_report(env, a, since)
285
+ if a.risk:
286
+ return _risk_report(env, a)
287
+ if a.switch:
288
+ return _switch_report(env, a, since)
289
+ if a.supervision:
290
+ from tempergraph.observe import supervision_report as sup
291
+
292
+ by = a.by or "workflow"
293
+ if by not in sup.BY:
294
+ raise UsageError(f"report --supervision --by takes {', '.join(sup.BY)}")
295
+ sdoc = sup.report(_root(env), since, by)
296
+ if a.json:
297
+ _emit(env, sdoc)
298
+ else:
299
+ env.out.write(sup.text(sdoc))
300
+ return 0
301
+ if a.by == "schedule": # TCK-B24: from the schedules' fire logs, machine-wide, read-only
302
+ sdoc = rows.schedule_report()
303
+ if a.json:
304
+ _emit(env, sdoc)
305
+ else:
306
+ for sid, g in sdoc["groups"].items():
307
+ env.out.write(f"{sid}\tfires {g['fires']}\tended {g['ended']}\toutcomes {g['outcomes']}\t"
308
+ f"${g['estimated_usd']:.2f}{' (lower bound)' if g['incomplete'] else ''}\t"
309
+ f"skipped {g['skipped']}\tmissed {g['missed']}\trefused {g['refused']}\n")
310
+ t = sdoc["totals"]
311
+ env.out.write(f"total\tfires {t['fires']}\tended {t['ended']}\t${t['estimated_usd']:.2f}\tskipped {t['skipped']}"
312
+ f"\tmissed {t['missed']}\trefused {t['refused']}\n")
313
+ return 0
314
+ by = a.by or "unit"
315
+ if by not in ("unit", "executor", "version"):
316
+ raise UsageError("report --by takes unit, executor or version (workflow, host, level with --supervision)")
317
+ doc = rep.report(_root(env), since, by)
318
+ if a.json:
319
+ _emit(env, doc)
320
+ return 0
321
+ env.out.write(report_text(doc))
322
+ return 0
323
+
324
+
325
+ def _money(m: dict[str, Any]) -> str:
326
+ parts = []
327
+ if m.get("reported_usd") is not None:
328
+ partial = "" if m["reported_sessions"] == m["sessions"] else f" ({m['reported_sessions']} of {m['sessions']})"
329
+ parts.append(f"${m['reported_usd']:.2f} rep{partial}")
330
+ if m.get("estimated_usd") is not None:
331
+ parts.append(f"${m['estimated_usd']:.2f} est")
332
+ if not parts:
333
+ return "unmeasured"
334
+ return ("≥ " if m.get("unmeasured") else "") + " · ".join(parts) + f" · {m['completeness']}"
335
+
336
+
337
+ def report_text(doc: dict[str, Any]) -> str:
338
+ out = [f"{doc['threads']} threads since {doc['since'] or 'the start'} · {_money(doc['total'])}",
339
+ f"steps {_money(doc['steps_and_judges']['steps'])} · judges {_money(doc['steps_and_judges']['judges'])}"]
340
+ if doc["by"] == "executor":
341
+ out += [f" {k}: {_money(v)}" for k, v in doc["by_executor"].items()]
342
+ elif doc["by"] == "version":
343
+ out += [f" {k}: {_money(v)}" for k, v in doc["by_version"].items()]
344
+ else:
345
+ for u in doc["units"]:
346
+ out.append(f" {u['workflow']}.{u['unit']}: first {_money(u['first_visit'])}")
347
+ out += [f" repeat {cause}: {_money(m)}" for cause, m in u["repeats"].items()]
348
+ for c in doc["criteria"]:
349
+ esc = f" · {c['escapes']} escapes" if c["escapes"] else ""
350
+ out.append(f" criterion {c['workflow']}.{c['criterion']}: "
351
+ + ", ".join(f"{k} {v}" for k, v in sorted(c["statuses"].items())) + esc)
352
+ out += [f" {t['class']}: {t['thread_id']} {t['unit']} attempt {t['attempt']}" for t in doc["timeouts"]]
353
+ out += [f" loop: {lp['thread_id']} {lp['session_key']} {lp['tool']} ×{lp['repeats']}" for lp in doc["loops"]]
354
+ return "\n".join(out) + "\n"
355
+
356
+
357
+ def cmd_stats(env: Any, a: argparse.Namespace) -> int:
358
+ from tempergraph.cli.main import UsageError, _emit
359
+ from tempergraph.observe import rows, sinks
360
+ from tempergraph.store.layout import ensure_home, home_path
361
+
362
+ home = home_path()
363
+ if a.action == "forget":
364
+ from tempergraph.observe import forget
365
+
366
+ if a.month:
367
+ raise UsageError("stats forget takes no month; it works on the month in which it runs")
368
+ try:
369
+ _emit(env, forget.forget(home, a.check))
370
+ except forget.IndexInUse as exc:
371
+ raise UsageError("the machine index is in use; try again") from exc
372
+ return 0
373
+ root = _here(env)
374
+ try:
375
+ if a.action == "flush":
376
+ from tempergraph.observe import supervision_cost
377
+
378
+ closed = supervision_cost.close(ensure_home())["closed"]
379
+ _emit(env, {**sinks.flush(home, root), "supervision_closed": closed})
380
+ return 0
381
+ if a.action == "sync" or a.sync:
382
+ synced = sinks.sync(home, root)
383
+ if a.action == "sync":
384
+ _emit(env, synced)
385
+ return 0
386
+ if a.live:
387
+ _emit(env, sinks.live(home, a.source, root))
388
+ return 0
389
+ if a.month and (len(a.month) != 7 or a.month[4] != "-"):
390
+ raise UsageError("--month takes YYYY-MM")
391
+ if a.source and a.local:
392
+ raise UsageError("--source and --local exclude each other")
393
+ conflicts: list[str] = []
394
+ found, unknown, synced_at = sinks.rows_for(home, a.source, a.local, a.month, a.since, root, conflicts)
395
+ except sinks.SinkConfigError as exc:
396
+ raise UsageError(str(exc)) from exc
397
+ doc: dict[str, Any] = {"schema_version": 1, "source": a.source or ("local" if a.local else "home"),
398
+ "month": a.month, "since": a.since, "totals": rows.totals(found), "unknown_schema": unknown,
399
+ "synced": synced_at, "duplicate_row_ids": conflicts}
400
+ if conflicts:
401
+ env.err.write(f"tempergraph: {len(conflicts)} row ids appear twice with different content; both are shown "
402
+ "(a copied machine.json or stats file?)\n")
403
+ if a.by:
404
+ groups: dict[str, list[dict[str, Any]]] = {}
405
+ for r in found:
406
+ groups.setdefault(rows._key(r, a.by), []).append(r)
407
+ doc["by"] = {"key": a.by, "groups": {k: rows.totals(v) for k, v in sorted(groups.items())}}
408
+ if a.projection:
409
+ doc["projection"] = rows.projection(found, by_version=a.by == "version")
410
+ _emit(env, doc)
411
+ return 0
412
+
413
+
414
+ def _here(env: Any) -> Path | None:
415
+ """This folder's state root when there is one; `stats` reads its `config/sinks.json` too."""
416
+ from tempergraph.store.layout import state_root_path
417
+
418
+ try:
419
+ root = state_root_path(env.cwd)
420
+ except Exception: # noqa: BLE001 - outside a repository `stats` reads the home folder only
421
+ return None
422
+ return root if root.is_dir() else None
423
+
424
+
425
+ def cmd_label(env: Any, a: argparse.Namespace) -> int:
426
+ """The one writing verb of this module: one metadata-only `label` row in the ledger (FBK-B8)."""
427
+ from tempergraph.cli.main import UsageError, _emit, _one, _root
428
+ from tempergraph.docs import append_jsonl
429
+ from tempergraph.observe.labels import LabelRefused, label
430
+
431
+ root = _root(env)
432
+ _, tid = _one(env, a.selector)
433
+ caller = env.caller(a)
434
+ try:
435
+ row = label(root, tid, a.gate, a.value, caller, criterion=a.criterion, attempt=a.attempt,
436
+ relayed=bool(a.relayed))
437
+ except LabelRefused as exc:
438
+ raise UsageError(str(exc)) from exc
439
+ append_jsonl(root / "ledger.jsonl", row)
440
+ if a.json:
441
+ _emit(env, row)
442
+ else:
443
+ env.out.write(f"label {row['value']} on {tid} {a.gate} (attempt {row['attempt']}, "
444
+ f"{row['gate_verdict']}) recorded, source {row['source']}\n")
445
+ return 0
446
+
447
+
448
+ def cmd_attention(env: Any, a: argparse.Namespace) -> int:
449
+ from tempergraph.cli import schedule_cli
450
+ from tempergraph.cli.main import _emit
451
+ from tempergraph.observe.attention import attention, line, loop_line, stale_line
452
+
453
+ where = roots(env, a.all_roots)
454
+ try: # SIL-B29, SIL-B32: a lost runner is handed to the loop first; a failure there changes nothing below
455
+ from tempergraph.improve import lost
456
+
457
+ for r in where:
458
+ lost.settle(r, env.catalog.specs, None, env.registry)
459
+ except Exception: # noqa: BLE001
460
+ pass
461
+ doc = attention(where, env.catalog.specs, schedule_cli.CLOCK().timestamp())
462
+ if a.json:
463
+ _emit(env, doc)
464
+ return 0
465
+ if not doc["items"] and not doc["loop"] and "trigger_stale" not in doc:
466
+ env.out.write("Nothing is waiting on a person.\n")
467
+ for i in doc["items"]:
468
+ env.out.write(line(i) + "\n")
469
+ if "trigger_stale" in doc: # TCK-B7
470
+ env.out.write(stale_line(doc["trigger_stale"]) + "\n")
471
+ for s in doc["loop"]: # CLI-B20: the loop's summaries after the items, never among them
472
+ env.out.write(loop_line(s) + "\n")
473
+ return 0
474
+
475
+
476
+ def _signals_env(env: Any) -> Any:
477
+ import os
478
+
479
+ return env.signals[0] if env.signals else os.environ
480
+
481
+
482
+ def cmd_supervision(env: Any, a: argparse.Namespace) -> int:
483
+ import json
484
+ import sys
485
+
486
+ from tempergraph.cli.main import UsageError, _emit, _one
487
+ from tempergraph.observe import supervision_cost as sco
488
+ from tempergraph.store.layout import ensure_home, home_path
489
+
490
+ if a.action == "hook": # never changes, delays or refuses the host call (OVR-B4): exit 0 whatever happens
491
+ try:
492
+ raw = sys.stdin.read(4 * 1024 * 1024)
493
+ payload = json.loads(raw) if raw.strip() else {}
494
+ if isinstance(payload, dict):
495
+ sco.hook(a.event, payload, _signals_env(env))
496
+ except Exception: # noqa: BLE001
497
+ pass
498
+ return 0
499
+ if a.action == "log":
500
+ if sco.disabled(_signals_env(env)):
501
+ return 0
502
+ if a.caller_app is not None and not sco.ID.match(a.caller_app):
503
+ raise UsageError("--caller-app must be an id")
504
+ entries = []
505
+ for n, ln in enumerate(sys.stdin.read().splitlines(), 1):
506
+ if not ln.strip():
507
+ continue
508
+ try:
509
+ e = json.loads(ln)
510
+ except ValueError as exc:
511
+ raise UsageError(f"line {n}: not JSON") from exc
512
+ if not isinstance(e, dict):
513
+ raise UsageError(f"line {n}: not an object")
514
+ if e.get("entry") == "session" and a.caller_app and "caller_app" not in e:
515
+ e["caller_app"] = a.caller_app
516
+ entries.append(e)
517
+ try:
518
+ count = sco.append(ensure_home(), a.host, a.session, entries)
519
+ except sco.EntryRefused as exc:
520
+ raise UsageError(f"nothing appended: {exc}") from exc
521
+ _emit(env, {"schema_version": 1, "appended": count})
522
+ return 0
523
+ if a.action == "close":
524
+ _emit(env, sco.close(ensure_home(), session=a.session))
525
+ return 0
526
+ if a.action == "show":
527
+ if bool(a.selector) == bool(a.session):
528
+ raise UsageError("supervision show takes a selector or --session")
529
+ if a.selector:
530
+ tid = a.selector if "/" in a.selector else _one(env, a.selector)[1]
531
+ doc = sco.show(home_path(), thread=tid)
532
+ else:
533
+ doc = sco.show(home_path(), session=a.session)
534
+ if a.json:
535
+ _emit(env, doc)
536
+ else:
537
+ env.out.write(sco.text(doc))
538
+ return 0
539
+ raise UsageError("supervision takes hook, log, close or show")
540
+
541
+
542
+ COMMANDS = {"supervision": cmd_supervision, "logs": cmd_logs, "store": cmd_store, "report": cmd_report, "stats": cmd_stats, "label": cmd_label,
543
+ "attention": cmd_attention}
544
+
@@ -0,0 +1,77 @@
1
+ """`outcome show` and `outcome candidates` (CLI-B7, CLI-B8, CLI-B14, OUT-B18, OUT-B19, OUT-B20, OUT-B21); read-only, model-free (OVR-B15)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import re
7
+ from datetime import UTC, datetime, timedelta
8
+ from typing import Any
9
+
10
+ WINDOW = re.compile(r"^(\d{1,4})d$")
11
+
12
+
13
+ def add_parser(sub: Any, parser_class: type[argparse.ArgumentParser]) -> None:
14
+ o = sub.add_parser("outcome", help="the good outcome, its measures and revision candidates")
15
+ osub = o.add_subparsers(dest="action", parser_class=parser_class)
16
+ sh = osub.add_parser("show")
17
+ sh.add_argument("workflow")
18
+ sh.add_argument("--runs", nargs="?", const="all", default=None, metavar="WINDOW", help="all, or <days>d")
19
+ sh.add_argument("--json", action="store_true")
20
+ ca = osub.add_parser("candidates")
21
+ ca.add_argument("workflow")
22
+ ca.add_argument("--window", type=int, default=None, metavar="DAYS")
23
+
24
+
25
+ def _since(window: str | int | None) -> str | None:
26
+ if window in (None, "all"):
27
+ return None
28
+ if isinstance(window, int):
29
+ days = window
30
+ else:
31
+ m = WINDOW.match(str(window))
32
+ if not m:
33
+ from tempergraph.cli.main import UsageError
34
+
35
+ raise UsageError(f"--runs {window!r}: expected all or <days>d")
36
+ days = int(m.group(1))
37
+ return (datetime.now(UTC) - timedelta(days=days)).isoformat()
38
+
39
+
40
+ def _definition(spec: Any) -> dict[str, Any]:
41
+ from tempergraph.improve.calibration import accepted_for
42
+ from tempergraph.run.outcome_trust import coverage, profile, trust
43
+
44
+ o = spec.outcome
45
+ root = spec.package_root
46
+ accepted = accepted_for(spec) # JCL-B17
47
+ final = [{"id": c.id, "severity": c.severity, "verified_by": c.verified_by or "none",
48
+ "trust": trust(c, "outcome", root, accepted)} for c in o.final]
49
+ inter = [{"unit": u, "id": c.id, "verified_by": c.verified_by or "none", "serves": list(c.serves),
50
+ "trust": trust(c, u, root, accepted)} for u, io in o.intermediate.items() for c in io.criteria]
51
+ cov = [{"criterion": c.criterion, "trust": c.trust, "covered": c.covered, "serving": c.serving,
52
+ "missing_units": c.missing_units} for c in coverage(o, spec, accepted)]
53
+ return {"revision": o.revision, "statement": o.statement, "deliverables": [dict(d) for d in o.deliverables],
54
+ "final": final, "intermediate": inter, "trust_profile": profile(o, spec, accepted), "coverage": cov}
55
+
56
+
57
+ def cmd_outcome(env: Any, a: argparse.Namespace) -> int:
58
+ from tempergraph.cli.main import UsageError, _emit, _root_or_none, _spec
59
+ from tempergraph.run import outcome_record
60
+
61
+ if a.action not in ("show", "candidates"):
62
+ raise UsageError("outcome needs show or candidates")
63
+ spec = _spec(env, a.workflow)
64
+ if spec.outcome is None:
65
+ raise UsageError(f"{spec.name} has no outcome.json; the authoring skill writes one (AUT)")
66
+ root = _root_or_none(env)
67
+ ledger = root / "ledger.jsonl" if root is not None else None
68
+ if a.action == "candidates":
69
+ doc = outcome_record.candidates(spec, ledger, _since(a.window)) if ledger else \
70
+ {"schema_version": 1, "workflow": spec.name, "candidates": []}
71
+ _emit(env, doc)
72
+ return 0
73
+ doc = {"schema_version": 1, "workflow": spec.name, "outcome": _definition(spec)}
74
+ if a.runs is not None:
75
+ doc["runs"] = outcome_record.measures(spec, ledger, _since(a.runs))["revisions"] if ledger else []
76
+ _emit(env, doc)
77
+ return 0