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,244 @@
1
+ """The history rules of C5 to C8 (ARC-B12 to ARC-B15, PRA-B10): pauses and supervision, cost, the escape rate, the
2
+ cut prompt, and the council and contest rules (ARC-B15) that read only run records.
3
+
4
+ Every function reads `HistoryFacts` only. The council and contest rules count records of their own shape and report
5
+ their own `n` (`SAMPLE_N`): the council's `rounds` with each member's `choices` and `changed` flag (CNL-B10, CNL-B2,
6
+ CNL-B12) and a contest's `slots` and `winner` (CTS-B7). A workflow with none of them is skipped, never passed.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import statistics
12
+ from collections import Counter
13
+ from collections.abc import Callable, Iterator
14
+ from typing import Any
15
+
16
+ from tempergraph.audit.history import STEP_KINDS, HistoryFacts
17
+ from tempergraph.audit.history_rules import P, Rule, finding
18
+ from tempergraph.audit.report import AuditFinding
19
+ from tempergraph.contracts import WorkflowSpec
20
+
21
+ TOUCH_CLASSES = ("designed", "rescue", "steer", "engine")
22
+
23
+
24
+ def _touches(rec: dict[str, Any]) -> Iterator[tuple[str, str, int]]:
25
+ for cls, by in (rec.get("touches") or {}).items():
26
+ if cls in TOUCH_CLASSES and isinstance(by, dict):
27
+ for decider, n in by.items():
28
+ yield cls, str(decider), int(n or 0)
29
+
30
+
31
+ # -- C5 ---------------------------------------------------------------------------------------------------------
32
+
33
+
34
+ def empty_pauses(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
35
+ out = []
36
+ for unit in dict.fromkeys(p.unit for p in facts.pauses):
37
+ ended = [p for p in facts.pauses if p.unit == unit and p.decision is not None]
38
+ empty = [p for p in ended if p.decision == "proceed" and not p.feedback and not p.changed]
39
+ if len(ended) >= P["min_pauses"] and len(empty) / len(ended) >= P["empty_pause_share"]:
40
+ out.append(finding("empty-pauses", facts, unit, f"{len(empty)} of {len(ended)} pauses at {unit} ended in "
41
+ "`proceed` with no feedback and no workspace change",
42
+ evidence={"pauses": len(ended), "empty": len(empty)}))
43
+ return out
44
+
45
+
46
+ def interventions_per_run(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
47
+ total = sum(int(r.get("undesigned") or 0) for r in facts.supervision)
48
+ if not facts.runs or total / facts.runs <= P["interventions_per_run"]:
49
+ return []
50
+ by_class: Counter[str] = Counter()
51
+ by_decider: Counter[str] = Counter()
52
+ for r in facts.supervision:
53
+ for cls, decider, n in _touches(r):
54
+ if cls in ("rescue", "steer") and n:
55
+ by_class[cls] += n
56
+ by_decider[decider] += n
57
+ by_kind: Counter[str] = Counter()
58
+ for r in facts.supervision:
59
+ for kind, n in ((r.get("touches") or {}).get("rescue_by_pause") or {}).items():
60
+ by_kind[str(kind)] += int(n or 0)
61
+ return [finding("interventions-per-run", facts, None, f"{total / facts.runs:.1f} undesigned touches per run "
62
+ f"over {facts.runs} runs", evidence={"per_run": round(total / facts.runs, 2),
63
+ "by_class": dict(by_class), "by_decider": dict(by_decider),
64
+ "by_pause_kind": dict(by_kind)})]
65
+
66
+
67
+ def agent_rescues_alone(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
68
+ rescues = sum(n for r in facts.supervision for cls, _, n in _touches(r) if cls == "rescue")
69
+ alone = sum(int(r.get("agent_own_rescues") or 0) for r in facts.supervision)
70
+ if rescues < P["min_rescues"] or alone / rescues < P["agent_rescue_share"]:
71
+ return []
72
+ return [finding("agent-rescues-alone", facts, None, f"agents made {alone} of {rescues} rescue decisions on "
73
+ "their own", evidence={"rescues": rescues, "agent_alone": alone,
74
+ "share": round(alone / rescues, 3)})]
75
+
76
+
77
+ def supervision_cost_share(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
78
+ shares = [float(r["supervision_share"]) for r in facts.supervision if r.get("supervision_share") is not None]
79
+ if len(shares) < P["min_measured_runs"] or statistics.median(shares) <= P["supervision_share"]:
80
+ return []
81
+ return [finding("supervision-cost-share", facts, None, f"supervision is a median {statistics.median(shares):.0%} "
82
+ f"of run cost over {len(shares)} measured runs",
83
+ evidence={"median_share": round(statistics.median(shares), 3), "measured_runs": len(shares)})]
84
+
85
+
86
+ def polling_supervisor(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
87
+ obs = [float(r["observations"]) for r in facts.supervision if r.get("observations") is not None]
88
+ rewake = [float(r["rewake_share"]) for r in facts.supervision if r.get("rewake_share") is not None]
89
+ polling = len(obs) >= P["min_measured_runs"] and statistics.mean(obs) > P["polling_observations"]
90
+ waking = len(rewake) >= P["min_measured_runs"] and statistics.median(rewake) > P["rewake_share"]
91
+ if not (polling or waking):
92
+ return []
93
+ return [finding("polling-supervisor", facts, None, "the supervisor polls the run instead of waiting on its exit",
94
+ evidence={"observations_per_run": round(statistics.mean(obs), 1) if obs else None,
95
+ "rewake_share": round(statistics.median(rewake), 3) if rewake else None})]
96
+
97
+
98
+ def callers_unknown(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
99
+ total = unknown = 0
100
+ for r in facts.supervision:
101
+ for _, decider, n in _touches(r):
102
+ total += n
103
+ unknown += n if decider == "unknown" else 0
104
+ if total < P["min_touches"] or unknown / total <= P["unknown_caller_share"]:
105
+ return []
106
+ return [finding("callers-unknown", facts, None, f"{unknown} of {total} touches had caller `unknown`",
107
+ evidence={"touches": total, "unknown": unknown, "share": round(unknown / total, 3)})]
108
+
109
+
110
+ # -- C6 and C7 --------------------------------------------------------------------------------------------------
111
+
112
+
113
+ def context_heavy_step(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
114
+ out = []
115
+ for unit in dict.fromkeys(a.unit for a in facts.attempts):
116
+ peaks = [a.peak_context for a in facts.attempts if a.unit == unit and a.kind in STEP_KINDS and a.peak_context]
117
+ if len(peaks) >= P["min_attempts"] and statistics.median(peaks) > P["context_peak_tokens"]:
118
+ out.append(finding("context-heavy-step", facts, unit, f"the median peak context of {unit} is "
119
+ f"{int(statistics.median(peaks))} tokens", evidence={
120
+ "attempts": len(peaks), "median_peak_tokens": int(statistics.median(peaks))}))
121
+ return out
122
+
123
+
124
+ def outcome_escapes(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
125
+ graded = [(run, verdict) for run, verdict in facts.outcomes if verdict and verdict != "not_reached"]
126
+ from tempergraph.run import outcome_record
127
+
128
+ wf = facts.workflow
129
+ latest = {f"{wf}/{run}": {"outcome": {"verdict": verdict}} for run, verdict in graded}
130
+ rows = outcome_record._jsonl(facts.root / "ledger.jsonl") if facts.root else []
131
+ found = outcome_record.escape_threads(latest, rows, {f"{wf}/{src}" for src in facts.rerun_sources})
132
+ escapes = [run for run, _ in graded if f"{wf}/{run}" in found]
133
+ if len(graded) < P["min_graded_runs"] or len(escapes) / len(graded) < P["escape_rate"]:
134
+ return []
135
+ return [finding("outcome-escapes", facts, None, f"{len(escapes)} of {len(graded)} graded runs met the outcome "
136
+ "and were rerun", evidence={"graded": len(graded), "escapes": len(escapes),
137
+ "rate": round(len(escapes) / len(graded), 3)})]
138
+
139
+
140
+ def rendered_near_cut(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
141
+ out = []
142
+ for unit in dict.fromkeys(u for _, u in facts.cut_prompts):
143
+ runs = {r for r, u in facts.cut_prompts if u == unit}
144
+ out.append(finding("rendered-near-cut", facts, unit, f"the renderer cut the prompt of {unit} in "
145
+ f"{len(runs)} runs", evidence={"runs": len(runs)}))
146
+ return out
147
+
148
+
149
+ # -- ARC-B15 council and contest -------------------------------------------------------------------------------
150
+
151
+
152
+ def leader(choices: dict[str, Any]) -> Any:
153
+ """The round's majority choice; None on an empty round or a tie."""
154
+ top = Counter(choices.values()).most_common(2)
155
+ if not top or (len(top) > 1 and top[0][1] == top[1][1]):
156
+ return None
157
+ return top[0][0]
158
+
159
+
160
+ def _later(c: dict[str, Any]) -> list[dict[str, Any]]:
161
+ return [r for r in c.get("rounds") or [] if int(r.get("round") or 0) > 0]
162
+
163
+
164
+ def _round0(c: dict[str, Any]) -> dict[str, Any]:
165
+ return next((r.get("choices") or {} for r in c.get("rounds") or [] if int(r.get("round") or 0) == 0), {})
166
+
167
+
168
+ def _councils(facts: HistoryFacts) -> dict[str, list[dict[str, Any]]]:
169
+ out: dict[str, list[dict[str, Any]]] = {}
170
+ for c in facts.councils:
171
+ if _later(c):
172
+ out.setdefault(str(c.get("unit")), []).append(c)
173
+ return out
174
+
175
+
176
+ def council_rounds_no_gain(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
177
+ out = []
178
+ for unit, cs in _councils(facts).items():
179
+ moved = sum(1 for c in cs if c.get("outcome") != leader(_round0(c)))
180
+ if len(cs) >= P["min_picks"] and moved / len(cs) < P["council_gain_floor"]:
181
+ out.append(finding("council-rounds-no-gain", facts, unit, f"later rounds of {unit} changed the outcome "
182
+ f"in {moved} of {len(cs)} visits", evidence={"visits": len(cs),
183
+ "changed_outcome": moved}))
184
+ return out
185
+
186
+
187
+ def council_conformity(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
188
+ out = []
189
+ for unit, cs in _councils(facts).items():
190
+ rounds = conforming = 0
191
+ for c in cs:
192
+ majority = leader(_round0(c))
193
+ for r in _later(c):
194
+ rounds += 1
195
+ movers = [m for m, did in (r.get("changed") or {}).items() if did]
196
+ if movers and all((r.get("choices") or {}).get(m) == majority for m in movers):
197
+ conforming += 1
198
+ if rounds >= P["min_picks"] and conforming / rounds >= P["council_conformity_share"]:
199
+ out.append(finding("council-conformity", facts, unit, f"in {conforming} of {rounds} rounds after round 0 "
200
+ "every member who changed moved to the round-0 majority",
201
+ evidence={"rounds": rounds, "conforming": conforming}))
202
+ return out
203
+
204
+
205
+ def _place(value: Any) -> int | None:
206
+ """A place in a `contest` record (EVT-B15): an integer counted from 1, as the engine writes it; None for any other."""
207
+ try:
208
+ return int(value) if value is not None and not isinstance(value, bool) else None
209
+ except (TypeError, ValueError):
210
+ return None
211
+
212
+
213
+ def _picked_among_many(record: Any) -> bool:
214
+ """A `contest` record that picked among slots: two or more (a retry that ran the winner's slot alone is no pick)."""
215
+ return len(record.get("slots") or []) >= 2
216
+
217
+
218
+ def contest_no_gain(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
219
+ out = []
220
+ for unit in dict.fromkeys(str(c.get("unit")) for c in facts.contests):
221
+ picks = [c for c in facts.contests if str(c.get("unit")) == unit and _picked_among_many(c)]
222
+ lowest = sum(1 for c in picks if _place(c.get("winner")) == min(_place(s.get("slot")) or 0 for s in c["slots"]))
223
+ if len(picks) >= P["min_picks"] and lowest / len(picks) >= P["contest_lowest_slot_share"]:
224
+ out.append(finding("contest-no-gain", facts, unit, f"the lowest-numbered slot of {unit} won {lowest} of "
225
+ f"{len(picks)} picks", evidence={"picks": len(picks), "lowest_slot_wins": lowest,
226
+ "slots": len(picks[0]["slots"])}))
227
+ return out
228
+
229
+
230
+ HISTORY_C5_C8: dict[str, Rule] = {
231
+ "empty-pauses": empty_pauses, "interventions-per-run": interventions_per_run,
232
+ "agent-rescues-alone": agent_rescues_alone, "supervision-cost-share": supervision_cost_share,
233
+ "polling-supervisor": polling_supervisor, "callers-unknown": callers_unknown,
234
+ "context-heavy-step": context_heavy_step, "outcome-escapes": outcome_escapes,
235
+ "rendered-near-cut": rendered_near_cut, "council-rounds-no-gain": council_rounds_no_gain,
236
+ "council-conformity": council_conformity, "contest-no-gain": contest_no_gain,
237
+ }
238
+
239
+ # The sample a rule counts when it is not the runs in the window (AUD-B5): records of its own shape.
240
+ SAMPLE_N: dict[str, Callable[[HistoryFacts], int]] = {
241
+ "council-rounds-no-gain": lambda f: sum(len(v) for v in _councils(f).values()),
242
+ "council-conformity": lambda f: sum(len(_later(c)) for v in _councils(f).values() for c in v),
243
+ "contest-no-gain": lambda f: sum(1 for c in f.contests if _picked_among_many(c)),
244
+ }
@@ -0,0 +1,270 @@
1
+ """The `host` layer (AUD): this machine and the target repository (ARC-B10, PRA-B7 to PRA-B10).
2
+
3
+ Read-only. The only child processes are the executor probes of `executors --probe` and the host-speed
4
+ probe, under a total budget of 30 s (AUD-B11, AUD-B6, AUD-B9); both are injectable so tests start none.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import json
11
+ import shutil
12
+ import time
13
+ from collections.abc import Callable, Iterator
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from tempergraph import executor_compat
19
+ from tempergraph.audit.catalog import PARAMS, rule
20
+ from tempergraph.audit.report import AuditFinding
21
+ from tempergraph.contracts import TextRef, WorkflowSpec
22
+ from tempergraph.executors.capabilities import DECLARED
23
+ from tempergraph.executors.launcher import ShellTiming, shell_timing
24
+ from tempergraph.model.prompt_lint import TICKED, names
25
+ from tempergraph.model.text import TextUnreadable, load_text, split_judge_file
26
+ from tempergraph.run.commands import REPO_FILE, REPOSITORY, repository_commands
27
+
28
+ P = {k: v.default for k, v in PARAMS.items()}
29
+
30
+ # Documented command sources of a repository and the programs that cover each (ARC toolchain-not-covered).
31
+ TOOLCHAINS: dict[str, frozenset[str]] = {
32
+ "package.json": frozenset({"npm", "npx", "yarn", "pnpm", "node", "bun"}),
33
+ "Makefile": frozenset({"make"}),
34
+ "pyproject.toml": frozenset({"python", "python3", "pytest", "uv", "ruff", "mypy", "hatch", "tox", "nox",
35
+ "poetry", "pip"}),
36
+ "go.mod": frozenset({"go"}),
37
+ "Cargo.toml": frozenset({"cargo"}),
38
+ }
39
+
40
+
41
+ @dataclass(kw_only=True)
42
+ class HostInputs:
43
+ target: Path
44
+ probe: Callable[[str], str | None] # executor -> probed version, None when the probe failed
45
+ timing: Callable[[float], ShellTiming | None] = shell_timing
46
+ which: Callable[[str], str | None] = shutil.which
47
+ plugin_cache: Path | None = None
48
+ stamp: dict[str, Any] | None = None # the package's last `stamp.json`
49
+ skipped: list[dict[str, Any]] = field(default_factory=list)
50
+
51
+
52
+ class Host:
53
+ def __init__(self, spec: WorkflowSpec, decl_file: str, inputs: HostInputs) -> None:
54
+ self.spec, self.decl, self.i = spec, decl_file, inputs
55
+ self.found: list[AuditFinding] = []
56
+ self.deadline = time.monotonic() + P["probe_budget_s"]
57
+
58
+ def add(self, rule_id: str, unit: str | None, statement: str, *, item: str | None = None,
59
+ evidence: dict[str, Any] | None = None, file: str | None = None, session: str | None = None) -> None:
60
+ r = rule(rule_id)
61
+ self.found.append(AuditFinding(rule=r.id, layer="host", severity=r.severity, confidence=r.confidence,
62
+ cause=r.cause, unit=unit, item=item, session=session, statement=statement,
63
+ evidence=evidence or {}, remedy=r.remedy,
64
+ location={"file": file or self.decl}))
65
+
66
+ def skip(self, rule_id: str, reason: str) -> None:
67
+ self.i.skipped.append({"rule": rule_id, "reason": reason})
68
+
69
+ def left(self) -> float:
70
+ return max(0.0, self.deadline - time.monotonic())
71
+
72
+ # -- programs and toolchains (C2) ---------------------------------------------------------------
73
+ def prefixes(self) -> list[tuple[str | None, str]]:
74
+ out: list[tuple[str | None, str]] = [(None, c) for c in self.spec.allow_commands]
75
+ for name in self.spec.order:
76
+ u = self.spec.units.get(name)
77
+ if u is not None and u.step is not None:
78
+ out += [(name, c) for c in u.step.commands]
79
+ return out
80
+
81
+ def commands(self) -> None:
82
+ if self.spec.command_resolver is not None:
83
+ reason = "command_resolver output is not read in release 1"
84
+ self.skip("check-program-missing", reason)
85
+ self.skip("toolchain-not-covered", reason)
86
+ return
87
+ programs: dict[str, str | None] = {}
88
+ declared: set[str] = set() # programs that only the target's commands file names (AUD-B18)
89
+ entries = self.prefixes()
90
+ for unit, prefix in entries:
91
+ prog = prefix.split()[0] if prefix.split() else ""
92
+ if prefix == REPOSITORY or not prog: # the entry is the target's commands, not a program (AUD-B17)
93
+ continue
94
+ if prog not in programs:
95
+ programs[prog] = unit
96
+ if any(prefix == REPOSITORY for _, prefix in entries):
97
+ for prefix in repository_commands(self.i.target):
98
+ prog = prefix.split()[0]
99
+ if prog not in programs:
100
+ programs[prog] = None
101
+ declared.add(prog)
102
+ for prog, unit in programs.items():
103
+ if self.i.which(prog) is None:
104
+ self.add("check-program-missing", unit, f"{prog!r} is not on PATH, so commands with that prefix run "
105
+ "nothing", item=prog, evidence={"program": prog},
106
+ file=REPO_FILE if prog in declared else None)
107
+ if not self.i.target.is_dir():
108
+ self.skip("toolchain-not-covered", "no target directory")
109
+ return
110
+ documented = documented_commands(self.i.target)
111
+ uses_commands = bool(programs) or any(u.gate.check is not None for u in self.spec.units.values())
112
+ if documented and uses_commands:
113
+ covering = frozenset().union(*(TOOLCHAINS[src] for src in documented))
114
+ if not covering & set(programs):
115
+ cmds = [c for cs in documented.values() for c in cs]
116
+ self.add("toolchain-not-covered", None, "the target documents commands no declared prefix covers: "
117
+ + ", ".join(cmds[:6]), evidence={"documented": cmds, "declared": sorted(programs)})
118
+
119
+ # -- slow host (C2) -----------------------------------------------------------------------------------
120
+ def speed(self) -> None:
121
+ got = self.i.timing(min(self.left(), P["slow_login_shell_s"] + 5))
122
+ if got is None:
123
+ self.skip("slow-host", "probe failed")
124
+ return
125
+ slow = got.login_s > P["slow_login_shell_s"] or (
126
+ got.login_s > P["slow_login_shell_floor_s"] and got.login_s > P["slow_login_shell_ratio"] * got.plain_s)
127
+ if slow:
128
+ self.add("slow-host", None, f"a login shell takes {got.login_s:.1f} s against {got.plain_s:.2f} s for a "
129
+ "plain one", evidence={"login_s": round(got.login_s, 2), "plain_s": round(got.plain_s, 3)})
130
+
131
+ # -- executor versions (owned: LIF executor compatibility) ---------------------------------------------
132
+ def executors(self) -> None:
133
+ used = []
134
+ for name in self.spec.order:
135
+ u = self.spec.units.get(name)
136
+ if u is not None and u.step is not None:
137
+ used.append(u.step.executor or self.spec.default_executor)
138
+ if u is not None and u.gate.judge is not None and u.gate.judge.executor:
139
+ used.append(u.gate.judge.executor)
140
+ for ex in dict.fromkeys(used):
141
+ if self.left() <= 0:
142
+ self.skip("executor-outside-tested-range", "probe failed: the 30 s budget is spent")
143
+ return
144
+ version = self.i.probe(ex)
145
+ if version is None:
146
+ self.skip("executor-outside-tested-range", f"probe failed: {ex}")
147
+ continue
148
+ f = executor_compat.finding(ex, version)
149
+ if f is not None:
150
+ self.found.append(AuditFinding(
151
+ rule=f"executor-compat:{f.code}", layer="host", severity="warning", confidence="high",
152
+ owner="executor-compat", item=ex, statement=f.message, evidence={"executor": ex,
153
+ "version": version},
154
+ remedy="Run the executor's contract probes for this version, or pin a tested version (LIF)",
155
+ location={"file": "tempergraph.json"}))
156
+
157
+ # -- names against the host (PRA) -----------------------------------------------------------------------
158
+ def texts(self) -> Iterator[tuple[str, str, str, str]]:
159
+ """(unit, executor, file, text) for each step template and judge text."""
160
+ for name in self.spec.order:
161
+ u = self.spec.units.get(name)
162
+ if u is None:
163
+ continue
164
+ ex = (u.step.executor if u.step else None) or self.spec.default_executor
165
+ st = u.step
166
+ if st is not None and st.prompt != "default":
167
+ text = None
168
+ with contextlib.suppress(TextUnreadable):
169
+ text = load_text(self.spec, st.prompt)
170
+ if text is not None:
171
+ yield name, ex, (st.prompt.path if isinstance(st.prompt, TextRef) else self.decl), text
172
+ j = u.gate.judge
173
+ if j is not None:
174
+ text = f"{j.stance}\n{j.brief}"
175
+ if j.file and self.spec.package_root is not None:
176
+ try:
177
+ text = "\n".join(split_judge_file(load_text(self.spec, TextRef(path=j.file))))
178
+ except TextUnreadable:
179
+ continue
180
+ yield name, j.executor or ex, j.file or self.decl, text
181
+
182
+ def references(self) -> None:
183
+ root = self.spec.package_root
184
+ installed = installed_skills(self.i.plugin_cache)
185
+ own = {p.parent.name for p in (root / "skills").glob("*/SKILL.md")} if root else set()
186
+ seen: set[str] = set()
187
+ for unit, _ex, file, text in self.texts():
188
+ for skill in names(text).skills:
189
+ plugin, _, bare = skill.rpartition(":")
190
+ if skill in seen or (plugin and plugin in installed.get(bare, ())):
191
+ continue
192
+ seen.add(skill)
193
+ others = sorted(installed.get(bare, ()))
194
+ if (bare not in own and others) or len(others) > 1:
195
+ self.add("ref-resolves-elsewhere", unit, f"skill {bare!r} is "
196
+ + ("not shipped with the workflow and is found in " if bare not in own
197
+ else "also found in ") + ", ".join(others), item=bare, file=file,
198
+ evidence={"plugins": others})
199
+
200
+ def stale_tools(self) -> None:
201
+ stamped = (self.i.stamp or {}).get("tool_set")
202
+ renamed = {ex: dict((executor_compat.table().get(ex) or {}).get("renamed") or {}) for ex in DECLARED}
203
+ if not isinstance(stamped, dict) and not any(renamed.values()):
204
+ self.skip("tool-name-stale", "no stamp and no renamed tools in the compatibility table")
205
+ return
206
+ for unit, ex, file, text in self.texts():
207
+ current = {t for ts in DECLARED.get(ex, DECLARED["claude"]).tool_map.values() for t in ts}
208
+ before = set((stamped or {}).get(ex) or ()) if isinstance(stamped, dict) else set()
209
+ for tok in dict.fromkeys(TICKED.findall(text)):
210
+ new = renamed.get(ex, {}).get(tok)
211
+ if new or (tok in before and tok not in current):
212
+ self.add("tool-name-stale", unit, f"`{tok}` is no longer a {ex} tool name"
213
+ + (f"; it is now `{new}`" if new else " (it was at the last stamp)"),
214
+ item=tok, file=file, evidence={"executor": ex, "name": tok, **({"now": new} if new else {})})
215
+
216
+ def run(self) -> list[AuditFinding]:
217
+ for rid in ("interpreter-cannot-import", "worktree-env-outside-worktree"):
218
+ self.skip(rid, "no declared interpreter in release 1 (WFM declares none)")
219
+ self.skip("tool-name-unknown", "owned by prompt lint `lint-tool-name-foreign`; MCP names need the view "
220
+ "catalog of TSA (release 2)")
221
+ for part in (self.commands, self.executors, self.speed, self.references, self.stale_tools):
222
+ part()
223
+ return self.found
224
+
225
+
226
+ def documented_commands(target: Path) -> dict[str, list[str]]:
227
+ """Source file -> the commands it documents (package.json scripts, Makefile targets, and the presence of
228
+ pyproject.toml, go.mod and Cargo.toml)."""
229
+ out: dict[str, list[str]] = {}
230
+ pkg = target / "package.json"
231
+ if pkg.is_file():
232
+ try:
233
+ scripts = json.loads(pkg.read_text(encoding="utf-8")).get("scripts") or {}
234
+ except (OSError, ValueError, AttributeError):
235
+ scripts = {}
236
+ if isinstance(scripts, dict) and scripts:
237
+ out["package.json"] = [f"package.json scripts.{k}" for k in sorted(scripts)]
238
+ mk = target / "Makefile"
239
+ if mk.is_file():
240
+ try:
241
+ targets = [line.split(":")[0] for line in mk.read_text(encoding="utf-8", errors="replace").splitlines()
242
+ if line and not line[0].isspace() and ":" in line and not line.startswith(("#", "."))
243
+ and "=" not in line.split(":")[0]]
244
+ except OSError:
245
+ targets = []
246
+ if targets:
247
+ out["Makefile"] = [f"make {t.strip()}" for t in targets[:10]]
248
+ for name in ("pyproject.toml", "go.mod", "Cargo.toml"):
249
+ if (target / name).is_file():
250
+ out[name] = [name]
251
+ return out
252
+
253
+
254
+ def installed_skills(cache: Path | None) -> dict[str, set[str]]:
255
+ """Skill name -> installed plugins that ship it (newest non-orphaned version of each plugin)."""
256
+ from tempergraph.package.registry import _version_key, plugin_cache
257
+
258
+ root = cache or plugin_cache()
259
+ out: dict[str, set[str]] = {}
260
+ if not root.is_dir():
261
+ return out
262
+ for market in sorted(p for p in root.iterdir() if p.is_dir()):
263
+ for plugin in sorted(p for p in market.iterdir() if p.is_dir()):
264
+ versions = [v for v in plugin.iterdir() if v.is_dir() and not (v / ".orphaned_at").exists()]
265
+ if not versions:
266
+ continue
267
+ newest = max(versions, key=lambda v: _version_key(v.name))
268
+ for s in newest.glob("skills/*/SKILL.md"):
269
+ out.setdefault(s.parent.name, set()).add(plugin.name)
270
+ return out
@@ -0,0 +1,96 @@
1
+ """Owned history rules, rendered (ARC-B1, ARC-AC4, ADR `audit-joins-existing-checks-and-files-nothing`): `cost-lens-rules`, `engine-fault-open` and
2
+ `prompt-change-moved-gate`.
3
+
4
+ Each calls the owning component and renders what it returns under `<owner>:<code>` with the owner's wording and
5
+ numbers: the cost lens of SIL (`improve.lenses.cost_rules`), the engine-side findings of the runs (`improve.record`,
6
+ `improve.causes`) and the post-release watch of SIL. No logic of those components is copied here. A function returns
7
+ None when its owner is not present (ARC-B7: skipped with `owner not present`, never passed).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import datetime as dt
13
+ import importlib
14
+ from collections.abc import Callable
15
+ from typing import Any
16
+
17
+ from tempergraph.audit.history import HistoryFacts
18
+ from tempergraph.audit.report import AuditFinding
19
+ from tempergraph.contracts import WorkflowSpec
20
+
21
+ OWNER = "SIL"
22
+
23
+
24
+ def _version(spec: WorkflowSpec, facts: HistoryFacts) -> str:
25
+ """The workflow version the owners filter on: `current` and `all` read the audited spec's version."""
26
+ return spec.version if facts.version in ("current", "all") else facts.version
27
+
28
+
29
+ def _now(facts: HistoryFacts) -> dt.datetime:
30
+ return dt.datetime.combine(facts.today or dt.date.today(), dt.time(23, 59, 59), tzinfo=dt.UTC)
31
+
32
+
33
+ def cost_lens_findings(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding] | None:
34
+ """ARC-B1: the cost lens's findings over the same window, carried with its code and numbers."""
35
+ from tempergraph.improve import lenses
36
+
37
+ if facts.root is None:
38
+ return []
39
+ got = lenses.cost_rules(spec, facts.root, _version(spec, facts), _now(facts))
40
+ out = []
41
+ for f in got.get("findings") or []:
42
+ out.append(AuditFinding(
43
+ rule=f"cost-lens:{f['rule']}", layer="history", severity="warning" if f.get("filed") else "info",
44
+ confidence="medium", unit=f.get("unit"), owner=OWNER,
45
+ statement=f"cost lens {f['rule']} on {f.get('unit') or 'the workflow'}",
46
+ evidence={k: v for k, v in f.items() if k not in ("rule", "unit")},
47
+ remedy="See the cost lens (SIL-B10)"))
48
+ return out
49
+
50
+
51
+ def engine_fault_findings(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding] | None:
52
+ """ARC-B14: open engine- or executor-side findings that name this workflow's units, so the author does not
53
+ chase them in the workflow. The side is the finding's own, else its cause's (`improve.causes`)."""
54
+ from tempergraph.improve import causes as causemod
55
+
56
+ seen: dict[tuple[str, str, str], set[str]] = {}
57
+ for f in facts.findings:
58
+ cause, unit = str(f.get("cause") or ""), f.get("unit")
59
+ if not cause or unit not in spec.units:
60
+ continue
61
+ side = str(f.get("side") or causemod.cause_of(cause).side)
62
+ if side == "engine" or side.startswith("executor"):
63
+ seen.setdefault((cause, str(unit), side), set()).add(str(f.get("run")))
64
+ return [AuditFinding(rule=f"{OWNER}:{cause}", layer="history", severity="info", confidence="high", unit=unit,
65
+ owner=OWNER, statement=f"{cause} on {unit} is an open {side} finding, not a workflow defect",
66
+ evidence={"runs": len(runs), "side": side}, remedy="See SIL: the fix is on the engine side")
67
+ for (cause, unit, side), runs in sorted(seen.items())]
68
+
69
+
70
+ def _watch() -> Callable[[WorkflowSpec, Any, str], list[dict[str, Any]]] | None:
71
+ """The post-release watch of SIL and PRP, or None when the engine does not hold it yet."""
72
+ try:
73
+ mod = importlib.import_module("tempergraph.improve.watch")
74
+ except ImportError:
75
+ return None
76
+ return getattr(mod, "prompt_moved_gates", None)
77
+
78
+
79
+ def prompt_change_findings(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding] | None:
80
+ """PRA-B10: a prompt change that moved a gate, from the watch, with its digest and dates."""
81
+ watch = _watch()
82
+ if watch is None:
83
+ return None
84
+ out = []
85
+ for row in watch(spec, facts.root, _version(spec, facts)):
86
+ code = str(row["code"])
87
+ out.append(AuditFinding(
88
+ rule=f"{OWNER}:{code}", layer="history", severity=str(row.get("severity") or "warning"),
89
+ confidence="high", unit=row.get("unit"), owner=OWNER, statement=str(row.get("message") or code),
90
+ evidence={k: v for k, v in row.items() if k not in ("code", "unit", "message", "severity")},
91
+ remedy="See the post-release watch (SIL, PRP)"))
92
+ return out
93
+
94
+
95
+ HISTORY_OWNED = {"cost-lens-rules": cost_lens_findings, "engine-fault-open": engine_fault_findings,
96
+ "prompt-change-moved-gate": prompt_change_findings}