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,387 @@
1
+ """The `definition` layer (AUD): rules that read the workflow package only (ARC-B8, ARC-B9, ARC-B14, PRA-B7 to PRA-B10).
2
+ Pure over the spec and the package files; no host, no history, no model (OVR-B15)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import re
8
+ from collections.abc import Callable, Iterator, Mapping
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from tempergraph.audit.catalog import PARAMS, rule
13
+ from tempergraph.audit.report import AuditFinding
14
+ from tempergraph.contracts import Capabilities, Criterion, JudgeSpec, TextRef, UnitSpec, WorkflowSpec
15
+ from tempergraph.model import flow
16
+ from tempergraph.model.prompt_lint import TICKED
17
+ from tempergraph.model.text import TextUnreadable, load_text
18
+ from tempergraph.model.validate import identical_slots
19
+
20
+ P = {k: v.default for k, v in PARAMS.items()}
21
+ FACT_CRITERION = re.compile(
22
+ r"\b(file|folder|directory|path)\b[^.]{0,60}\b(exists?|is present|is created)\b|\b(exists?)\b[^.]{0,30}\b(file|"
23
+ r"folder|directory)\b|\b(command|tests?|build|lint|type check)\b[^.]{0,40}\b(pass(es)?|succeeds?|exits? (0|zero)|"
24
+ r"returns? 0)\b|\b(git|commit|branch|tag|pushed|merged)\b[^.]{0,40}\b(exists?|is clean|has|contains|points)\b",
25
+ re.I)
26
+ FORBIDS = { # PRA prompt-tool-conflict: text that forbids a declared capability
27
+ "shell": re.compile(r"\b(do not|don't|never|must not)\s+(run|use|execute)\s+(any\s+)?(commands?|the shell|bash|"
28
+ r"a terminal|the terminal|scripts?)\b", re.I),
29
+ "edit": re.compile(r"\b(do not|don't|never|must not)\s+(edit|modify|change)\s+(any\s+)?(files?|the code)\b", re.I),
30
+ "write": re.compile(r"\b(do not|don't|never|must not)\s+(write|create)\s+(any\s+)?(new\s+)?files?\b", re.I),
31
+ "web_fetch": re.compile(r"\b(do not|don't|never|must not)\s+(fetch|browse|open)\s+(any\s+)?(web ?pages?|urls?|"
32
+ r"the web)\b", re.I),
33
+ "web_search": re.compile(r"\b(do not|don't|never|must not)\s+search\s+the web\b", re.I),
34
+ }
35
+ WHOLE = re.compile(r"\b(write|produce|draft|generate)\s+(the\s+)?(whole|entire|complete|full)\b|\bcomplete (plan|"
36
+ r"document|spec|report)\b|\bin (one|a single) (answer|response|go)\b", re.I)
37
+ IN_PARTS = re.compile(r"\b(in parts|part by part|section by section|one (part|section) at a time|skeleton|"
38
+ r"outline first|one edit per)\b", re.I)
39
+ STANDARD_FRONTMATTER = frozenset({"name", "description", "license", "compatibility", "metadata", "allowed-tools"})
40
+ SIZING_MIN_WORDS = 4
41
+ SMALL = {"small", "haiku"}
42
+ LARGE = {"large", "opus"}
43
+
44
+ Add = Callable[..., None]
45
+
46
+
47
+ class Definition:
48
+ def __init__(self, spec: WorkflowSpec, decl_file: str, surfaces: dict[str, Any],
49
+ caps: Mapping[str, Capabilities] | None = None) -> None:
50
+ self.spec = spec
51
+ self.decl = decl_file # the package file that declares the units, for locations
52
+ self.surfaces = surfaces
53
+ self.caps = caps or {} # the executors' capability sets, for the family of a member's alias
54
+ self.found: list[AuditFinding] = []
55
+
56
+ def add(self, rule_id: str, unit: str | None, statement: str, *, item: str | None = None,
57
+ session: str | None = None, evidence: dict[str, Any] | None = None, field: str | None = None,
58
+ file: str | None = None, line: int | None = None) -> None:
59
+ r = rule(rule_id)
60
+ loc: dict[str, Any] = {"file": file or self.decl}
61
+ if field:
62
+ loc["field"] = field
63
+ if line:
64
+ loc["line"] = line
65
+ self.found.append(AuditFinding(rule=r.id, layer=r.layer, severity=r.severity, confidence=r.confidence,
66
+ cause=r.cause, unit=unit, item=item, session=session, statement=statement,
67
+ evidence=evidence or {}, remedy=r.remedy, location=loc))
68
+
69
+ # -- helpers ------------------------------------------------------------------------------------
70
+ def units(self) -> Iterator[tuple[str, UnitSpec]]:
71
+ for name in self.spec.order:
72
+ u = self.spec.units.get(name)
73
+ if u is not None:
74
+ yield name, u
75
+
76
+ def template(self, u: UnitSpec) -> tuple[str, str] | None:
77
+ st = u.step
78
+ if st is None or st.prompt == "default":
79
+ return None
80
+ where = st.prompt.path if isinstance(st.prompt, TextRef) else ""
81
+ try:
82
+ return where, load_text(self.spec, st.prompt)
83
+ except TextUnreadable:
84
+ return None
85
+
86
+ @staticmethod
87
+ def gated(u: UnitSpec) -> bool:
88
+ return u.gate.check is not None or u.gate.judge is not None
89
+
90
+ @staticmethod
91
+ def cid(c: Criterion) -> str:
92
+ return c.id or c.text[:40]
93
+
94
+ # -- C1 ---------------------------------------------------------------------------------------------
95
+ def c1(self) -> None:
96
+ for name, u in self.units():
97
+ crit = u.gate.criteria
98
+ blockers = [c for c in crit if c.severity == "blocker"]
99
+ files = [k for k, v in (u.step.produces if u.step else {}).items() if v == "file"]
100
+ tpl = self.template(u)
101
+ size = len(tpl[1]) if tpl else 0
102
+ why = []
103
+ if len(blockers) > P["oversized_blockers"]:
104
+ why.append(f"{len(blockers)} blocker criteria (over {int(P['oversized_blockers'])})")
105
+ if len(files) > P["oversized_file_artifacts"]:
106
+ why.append(f"{len(files)} file artifacts (over {int(P['oversized_file_artifacts'])})")
107
+ if size > P["oversized_template_chars"]:
108
+ why.append(f"a {size}-character template (over {int(P['oversized_template_chars'])})")
109
+ if why:
110
+ self.add("oversized-step", name, f"{name} does too much for one gate: " + "; ".join(why),
111
+ evidence={"blockers": len(blockers), "file_artifacts": len(files), "template_chars": size})
112
+ for c in blockers:
113
+ if c.no_change_policy == "retry":
114
+ self.add("no-change-blocker-retries", name, f"blocker {self.cid(c)!r} retries on no change",
115
+ item=self.cid(c), field=f"units.{name}.gate.criteria[{self.cid(c)}].no_change_policy")
116
+ if c.unverified_system:
117
+ self.add("unverified-blocker", name, f"blocker {self.cid(c)!r} names unverified system "
118
+ f"{c.unverified_system!r}, so it is always UNVERIFIABLE", item=self.cid(c),
119
+ evidence={"system": c.unverified_system})
120
+ if u.gate.check is None:
121
+ for c in crit:
122
+ if not c.mechanical and c.verified_by in (None, "judge") and FACT_CRITERION.search(c.text):
123
+ self.add("single-criterion-gate-judge-only", name, f"criterion {self.cid(c)!r} names a "
124
+ "fact a check could compute, and the gate has no check", item=self.cid(c))
125
+
126
+ # -- C3 ---------------------------------------------------------------------------------------------
127
+ def c3(self) -> None:
128
+ total_s = 0.0
129
+ tries = P["infra_tries"]
130
+ for name, u in self.units():
131
+ t: float | None = None
132
+ if u.step is not None and u.kind == "step":
133
+ st = u.step
134
+ t = float(st.timeout_s or P["engine_step_timeout_s"])
135
+ if st.timeout_s is None:
136
+ self.add("default-step-timeout", name, f"{name} sets no timeout_s, so the engine's "
137
+ f"{int(P['engine_step_timeout_s'])} s applies", session="step",
138
+ field=f"units.{name}.step.timeout_s")
139
+ if st.idle_s is not None and st.idle_s >= t:
140
+ self.add("idle-limit-inert", name, f"idle_s {st.idle_s} is not below the wall limit {int(t)} s",
141
+ session="step", evidence={"idle_s": st.idle_s, "timeout_s": int(t)},
142
+ field=f"units.{name}.step.idle_s")
143
+ if t > P["no_idle_above_s"] and st.idle_s is None:
144
+ self.add("no-idle-limit", name, f"a {int(t)} s limit with no idle limit", session="step",
145
+ field=f"units.{name}.step.idle_s")
146
+ elif u.script is not None:
147
+ t = float(u.script.timeout_s)
148
+ j = u.gate.judge
149
+ if j is not None and j.timeout_s is None:
150
+ self.add("default-judge-timeout", name, f"the judge of {name} sets no timeout_s", session="judge",
151
+ field=f"units.{name}.gate.judge.timeout_s")
152
+ if t is None:
153
+ continue
154
+ attempts = u.gate.retry_budget + 1 if self.gated(u) else 1
155
+ hold = t * attempts + t * tries
156
+ total_s += hold
157
+ if hold > P["unit_hold_h"] * 3600:
158
+ self.add("hold-time-exposure", name, f"{name} can hold the run for {hold / 3600:g} h "
159
+ f"({int(t)} s x {attempts} attempts + {int(t)} s x {int(tries)} infra tries)",
160
+ evidence={"timeout_s": int(t), "retry_budget": u.gate.retry_budget,
161
+ "infra_tries": int(tries), "hold_h": round(hold / 3600, 2)})
162
+ if total_s > P["workflow_hold_h"] * 3600:
163
+ self.add("hold-time-exposure", None, f"the units in order can hold a run for {total_s / 3600:g} h "
164
+ f"(over {int(P['workflow_hold_h'])} h)", item="order",
165
+ evidence={"hold_h": round(total_s / 3600, 2)})
166
+
167
+ # -- C5 ---------------------------------------------------------------------------------------------
168
+ def c5(self) -> None:
169
+ gates = [(n, u) for n, u in self.units() if self.gated(u) or u.gate.approval]
170
+ for name, u in gates:
171
+ if self.gated(u) and u.gate.retry_budget == 0 and u.gate.on_budget_spent == "ask":
172
+ self.add("every-retry-asks", name, f"{name} has retry_budget 0 and on_budget_spent ask, so every "
173
+ "RETRY pauses for a person", field=f"units.{name}.gate.retry_budget")
174
+ approvals = [n for n, u in gates if u.gate.approval]
175
+ if gates and len(approvals) > P["approval_share"] * len(gates):
176
+ self.add("approval-on-most-gates", None, f"approval is set on {len(approvals)} of {len(gates)} gates",
177
+ evidence={"approvals": len(approvals), "gates": len(gates), "units": approvals})
178
+
179
+ # -- ARC-B15 council definition rules ------------------------------------------------------------------
180
+ def families(self, u: UnitSpec) -> list[str | None]:
181
+ """The model family of each member of a council: its alias on its own executor, `inherit` when it names none."""
182
+ out: list[str | None] = []
183
+ for m in u.council.members if u.council else ():
184
+ caps = self.caps.get(m.executor or self.spec.default_executor)
185
+ out.append(caps.families.get(m.model or "inherit") if caps is not None else None)
186
+ return out
187
+
188
+ def councils(self) -> None:
189
+ for name, u in self.units():
190
+ c = u.council
191
+ if c is None:
192
+ continue
193
+ fams = self.families(u)
194
+ if len(fams) >= 2 and None not in fams and len(set(fams)) == 1:
195
+ self.add("council-one-family", name, f"every member of {name} runs on the {fams[0]!r} model family",
196
+ evidence={"family": fams[0], "members": len(fams)}, field=f"units.{name}.council.members")
197
+ if c.mode == "vote" and (c.rule or "majority") == "majority" and len(c.members) % 2 == 0:
198
+ self.add("council-even-majority", name, f"{name} votes by majority with {len(c.members)} members, so a "
199
+ "tie is possible", evidence={"members": len(c.members)}, field=f"units.{name}.council.members")
200
+
201
+ # -- C6 ---------------------------------------------------------------------------------------------
202
+ @staticmethod
203
+ def _tier(model: object) -> str:
204
+ if model is None:
205
+ return ""
206
+ first = model if isinstance(model, str) else (list(model)[0] if model else "") # type: ignore[call-overload]
207
+ return str(first).rsplit(":", 1)[-1].lower()
208
+
209
+ def _sizing(self, name: str, who: str, model: object, options: object, ladder: tuple[str, ...], why: str,
210
+ field: str) -> None:
211
+ """SCF-B10: a session whose model, effort or reason nobody stated runs on defaults nobody chose."""
212
+ missing = [w for w, absent in (
213
+ ("model", not model or model == "inherit"),
214
+ ("effort", not ladder and getattr(options, "effort", None) is None),
215
+ ("sizing", len(why.split()) < SIZING_MIN_WORDS)) if absent]
216
+ if missing:
217
+ self.add("sizing-unassessed", name, f"the {who} of {name} states no {', '.join(missing)}",
218
+ session=who, evidence={"missing": missing}, field=field)
219
+
220
+ def c6(self) -> None:
221
+ tiers: list[str] = []
222
+ for name, u in self.units():
223
+ if identical_slots(self.spec, name): # ARC-B15, CTS-B10: the one condition validation warns on as well
224
+ self.add("contest-identical-slots", name, f"every slot of {name} shares executor, model and prompt, so "
225
+ "the contest buys only sampling variance", evidence={"slots": len(flow.slot_names(self.spec, name))},
226
+ field=f"units.{name}.contest.slots")
227
+ j: JudgeSpec | None = u.gate.judge
228
+ if u.step is not None:
229
+ self._sizing(name, "step", u.step.model or self.spec.model_profile.get(name), u.step.session_options,
230
+ tuple(u.step.effort_ladder), u.step.sizing, f"units.{name}.sizing")
231
+ if j is not None and u.step is not None:
232
+ self._sizing(name, "judge", j.model, j.session_options, (), j.sizing,
233
+ f"units.{name}.gate.judge.sizing")
234
+ if u.step is not None:
235
+ tiers.append(self._tier(u.step.model or self.spec.model_profile.get(name)))
236
+ if j is not None:
237
+ tiers.append(self._tier(j.model))
238
+ spans = len(j.references) + len(j.subject)
239
+ if self._tier(j.model) in SMALL and spans > 1:
240
+ self.add("small-judge-cross-file", name, f"the judge of {name} is on a small model and reads "
241
+ f"{spans} artifacts", session="judge", evidence={"artifacts": spans, "model": j.model},
242
+ field=f"units.{name}.gate.judge.model")
243
+ if tiers and all(t in LARGE for t in tiers):
244
+ self.add("large-everywhere", None, "every step and judge resolves to the large tier",
245
+ evidence={"sessions": len(tiers)})
246
+ if self.spec.run_cost_cap_usd is None and self.spec.improvement_mode == "stable":
247
+ self.add("no-run-cost-cap", None, "a stable workflow with no run_cost_cap_usd", field="run_cost_cap_usd")
248
+
249
+ # -- PRA definition rules --------------------------------------------------------------------------
250
+ def prompts(self) -> None:
251
+ root = self.spec.package_root
252
+ produced_by: dict[str, str] = {}
253
+ for name, u in self.units():
254
+ for key in (u.step.produces if u.step else {}):
255
+ produced_by.setdefault(key, name)
256
+ for name, u in self.units():
257
+ st = u.step
258
+ tpl = self.template(u)
259
+ if st is not None and tpl is not None:
260
+ where, text = tpl
261
+ file = where or self.decl
262
+ for cap, pat in FORBIDS.items():
263
+ if cap in st.tools and (m := pat.search(text)):
264
+ self.add("prompt-tool-conflict", name, f"the template says {m.group(0)!r} but the step "
265
+ f"declares {cap!r}", session="step", item=cap, file=file,
266
+ line=text.count("\n", 0, m.start()) + 1)
267
+ for key in st.produces:
268
+ if key not in text:
269
+ self.add("artifact-not-asked", name, f"produced artifact {key!r} is never named in the "
270
+ "template", session="step", item=key, file=file)
271
+ files = [k for k, v in st.produces.items() if v == "file"]
272
+ if len(files) == 1 and (m := WHOLE.search(text)) and not IN_PARTS.search(text):
273
+ self.add("one-shot-long-output", name, f"the template asks for {m.group(0)!r} in one answer",
274
+ session="step", file=file, line=text.count("\n", 0, m.start()) + 1)
275
+ j = u.gate.judge
276
+ if j is not None:
277
+ reach = set(j.references) | set(j.subject) | set(st.produces if st else ())
278
+ for c in u.gate.criteria:
279
+ for tok in dict.fromkeys(TICKED.findall(c.text)):
280
+ if tok in produced_by and tok not in reach:
281
+ self.add("criterion-not-in-reach", name, f"criterion {self.cid(c)!r} names artifact "
282
+ f"{tok!r} (made by {produced_by[tok]}), which the judge does not read",
283
+ session="judge", item=f"{self.cid(c)}:{tok}")
284
+ self._frontmatter(root)
285
+ self._step_files(root)
286
+ self._structure()
287
+
288
+ def _structure(self) -> None:
289
+ """PRA-B13: how each model-facing file is built, against the audit's parameters; advisory only."""
290
+ from tempergraph.audit.text_health import measure, model_facing, repeated
291
+
292
+ files = model_facing(self.spec)
293
+ limit = P["prompt_prohibitions_per_reason"]
294
+ for file, tf in files.items():
295
+ m = measure(tf.text)
296
+ if m.prohibitions and m.prohibitions_per_reason >= limit:
297
+ unit = next((u.split(":")[0] for u in tf.used_by), None)
298
+ self.add("prompt-constraint-heavy", unit, f"{file} holds {m.prohibitions} prohibitions and "
299
+ f"{m.reasons} reasons ({m.prohibitions_per_reason} per reason, at or above {limit:g})",
300
+ file=None if file.startswith("inline:") else file, evidence=m.as_json())
301
+ for sentence, where in repeated(files, int(P["prompt_repeat_files"])):
302
+ self.add("prompt-repeated-text", None, f"a sentence is repeated in {len(where)} files: "
303
+ f"{sentence[:80]!r}", item=sentence[:80], file=where[0],
304
+ evidence={"files": where, "chars": len(sentence)})
305
+
306
+ def _step_files(self, root: Path | None) -> None:
307
+ """PRA-B7: every `step_files` pattern of the package's manifest matches a file of the package."""
308
+ from tempergraph.package.manifest import declared_step_files
309
+
310
+ if root is None:
311
+ return
312
+ for pattern in declared_step_files(root):
313
+ if not any(p.is_file() for p in root.glob(pattern)):
314
+ self.add("step-file-missing", None, f"`step_files` pattern {pattern!r} matches no file of the package",
315
+ item=pattern, file="tempergraph.json", evidence={"pattern": pattern})
316
+
317
+ def _frontmatter(self, root: Path | None) -> None:
318
+ if root is None:
319
+ return
320
+ executors = {(u.step.executor if u.step else None) or self.spec.default_executor
321
+ for _, u in self.units()}
322
+ portable = bool(self.surfaces) or any(e not in ("claude", "agent-sdk") for e in executors)
323
+ if not portable:
324
+ return
325
+ for p in sorted((root / "skills").glob("*/SKILL.md")):
326
+ keys = frontmatter_keys(p.read_text(encoding="utf-8"))
327
+ extra = sorted(keys - STANDARD_FRONTMATTER)
328
+ if extra:
329
+ self.add("skill-frontmatter-nonstandard", None, f"{p.parent.name} uses frontmatter beyond the "
330
+ f"Agent Skills standard: {', '.join(extra)}", item=p.parent.name,
331
+ file=p.relative_to(root).as_posix(), evidence={"fields": extra})
332
+
333
+ # -- outcome (ARC-B14) --------------------------------------------------------------------------------
334
+ def outcome(self) -> None:
335
+ from tempergraph.run.outcome_trust import coverage, trust
336
+
337
+ o = self.spec.outcome
338
+ if o is None:
339
+ return
340
+ rows = [("outcome", c) for c in o.final] + [(u, c) for u, io in o.intermediate.items() for c in io.criteria]
341
+ from tempergraph.improve.calibration import accepted_for
342
+
343
+ accepted = accepted_for(self.spec)
344
+ for unit, c in rows:
345
+ t = trust(c, unit, self.spec.package_root, accepted)
346
+ if c.severity == "blocker" and t in ("unverified", "uncalibrated"):
347
+ self.add("outcome-unverified-blocker", unit, f"blocker {self.cid(c)!r} is at {t} trust",
348
+ item=self.cid(c), file="outcome.json", evidence={"trust": t, "verified_by": c.verified_by})
349
+ for cov in coverage(o, self.spec):
350
+ if not cov.covered:
351
+ self.add("outcome-uncovered", "outcome", f"final criterion {cov.criterion!r} is not covered: "
352
+ f"{cov.trust} at the outcome gate, no trusted serving criterion on "
353
+ f"{', '.join(cov.missing_units) or 'any unit'}", item=cov.criterion, file="outcome.json",
354
+ evidence={"trust": cov.trust, "missing_units": cov.missing_units})
355
+
356
+ # -- change notes (ARC-B17) ---------------------------------------------------------------------------
357
+ def change_notes(self) -> None:
358
+ root = self.spec.package_root
359
+ if root is None or not self.spec.version:
360
+ return
361
+ rel = f"changes/{self.spec.version}.json"
362
+ path = Path(root) / rel
363
+ if not path.is_file():
364
+ self.add("change-notes-incomplete", None, f"the package has no {rel} for its version {self.spec.version}",
365
+ file=".claude-plugin/plugin.json")
366
+ return
367
+ try:
368
+ doc = json.loads(path.read_text(encoding="utf-8"))
369
+ except (OSError, ValueError):
370
+ return
371
+ if isinstance(doc, dict) and doc.get("draft") is True:
372
+ self.add("change-notes-incomplete", None, f"{rel} is still marked draft", file=rel)
373
+
374
+ def run(self) -> list[AuditFinding]:
375
+ for part in (self.c1, self.c3, self.c5, self.councils, self.c6, self.prompts, self.change_notes,
376
+ self.outcome):
377
+ part()
378
+ return self.found
379
+
380
+
381
+ def frontmatter_keys(text: str) -> set[str]:
382
+ if not text.startswith("---"):
383
+ return set()
384
+ end = text.find("\n---", 3)
385
+ if end < 0:
386
+ return set()
387
+ return {m.group(1) for m in re.finditer(r"^([A-Za-z0-9_-]+)\s*:", text[3:end], re.M)}