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,89 @@
1
+ """`audit prompts <workflow>`: one row per model-facing file (PRA-B11). The `changed` column reads the recorded prompt
2
+ digests of the unit and role that use the file from the history facts: the number of changes, the version of the last
3
+ one and the gate's first-pass yield before and after it; `not recorded` when no run recorded a digest for it, never
4
+ zero (CON-B14, CON-B1, CON-B15)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ from tempergraph.audit.history import HistoryFacts
11
+ from tempergraph.audit.report import AuditReport
12
+ from tempergraph.audit.text_health import measure, model_facing, named_files, rendered_size, repeated
13
+ from tempergraph.contracts import WorkflowSpec
14
+ from tempergraph.model.prompt_lint import names as read_names
15
+
16
+
17
+ def _yield(facts: HistoryFacts, unit: str, runs: set[str]) -> float | None:
18
+ visits = [v for v in facts.visits if v.unit == unit and v.run in runs and v.tokens]
19
+ return round(sum(1 for v in visits if v.first_pass) / len(visits), 3) if visits else None
20
+
21
+
22
+ def changed_cell(facts: HistoryFacts | None, used_by: list[str]) -> dict[str, Any] | str:
23
+ """PRA-B11: what history says about a file's changes, `not recorded` without a recorded digest."""
24
+ if facts is None:
25
+ return "not recorded"
26
+ count, recorded = 0, False
27
+ last: tuple[str, str, float | None, float | None] | None = None # (when, version, yield before, yield after)
28
+ for key in dict.fromkeys(used_by):
29
+ unit, _, role = key.partition(":")
30
+ first: dict[str, tuple[str, str]] = {} # the digest a run started with
31
+ for ts, run, u, r, digest in sorted(facts.digests):
32
+ if u == unit and r == role:
33
+ first.setdefault(run, (ts, digest))
34
+ seq = sorted((ts, run, digest) for run, (ts, digest) in first.items())
35
+ recorded = recorded or bool(seq)
36
+ for i in range(1, len(seq)):
37
+ if seq[i][2] == seq[i - 1][2]:
38
+ continue
39
+ count += 1
40
+ ts, run, _ = seq[i]
41
+ if last is None or ts >= last[0]:
42
+ version = next((v.version for v in facts.visits if v.run == run), "")
43
+ last = (ts, version, _yield(facts, unit, {s[1] for s in seq[:i]}),
44
+ _yield(facts, unit, {s[1] for s in seq[i:]}))
45
+ if not recorded:
46
+ return "not recorded"
47
+ return {"changes": count, "version": (last[1] or None) if last else None,
48
+ "first_pass_before": last[2] if last else None, "first_pass_after": last[3] if last else None}
49
+
50
+
51
+ def _criteria_chars(spec: WorkflowSpec, unit: str) -> int:
52
+ u = spec.units.get(unit)
53
+ return sum(len(c.text) for c in u.gate.criteria) if u is not None else 0
54
+
55
+
56
+ def prompt_rows(spec: WorkflowSpec, report: AuditReport, facts: HistoryFacts | None = None,
57
+ repeat_files: int = 3) -> list[dict[str, Any]]:
58
+ """PRA-B11, PRA-B12: one row per model-facing file, its names, findings, history and how its text is built."""
59
+ out = []
60
+ files = model_facing(spec)
61
+ shared: dict[str, int] = {}
62
+ for _, where in repeated(files, repeat_files):
63
+ for f in where:
64
+ shared[f] = shared.get(f, 0) + 1
65
+ for file, tf in files.items():
66
+ text, used_by = tf.text, tf.used_by
67
+ row = {"used_by": used_by}
68
+ n = read_names(text)
69
+ found = [f for f in report.findings if f.location.get("file") == file or
70
+ (file.startswith("inline:") and f.location.get("file") is None and f.unit in
71
+ {u.split(":")[0] for u in row["used_by"]})]
72
+ unresolved = sum(1 for f in found if f.rule in ("prompt-lint:lint-ref-missing", "ref-resolves-elsewhere"))
73
+ stale = sum(1 for f in found if f.rule == "tool-name-stale")
74
+ counts = {s: sum(1 for f in found if f.severity == s and f.ignored is None)
75
+ for s in ("error", "warning", "info")}
76
+ size: dict[str, Any] = {"chars": len(text), "rendered": None, "must_read": None}
77
+ step_unit = next((u.split(":")[0] for u in used_by if u.endswith(":step")), None)
78
+ if step_unit is not None:
79
+ size["rendered"] = rendered_size(spec, step_unit, text)
80
+ named = named_files(text, files)
81
+ size["must_read"] = ((size["rendered"] or len(text) + _criteria_chars(spec, step_unit))
82
+ + sum(len(files[f].text) for f in named if f != file))
83
+ size["must_read_files"] = named
84
+ out.append({"file": file, "role": tf.role, "used_by": used_by, "chars": len(text), "size": size,
85
+ "structure": measure(text).as_json() | {"repeated_sentences": shared.get(file, 0)},
86
+ "names": {"found": len(n.skills) + len(n.agents) + len(n.files) + len(n.tools),
87
+ "unresolved": unresolved, "stale": stale},
88
+ "findings": counts, "changed": changed_cell(facts, used_by)})
89
+ return out
@@ -0,0 +1,248 @@
1
+ """`AuditFinding` and `AuditReport` (AUD (moved), AUD-B12, AUD-B13, AUD-B14): ordering, the quiet default view,
2
+ ignores, the summary, `--fail-on`, and the text, JSON and SARIF forms."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import datetime as dt
7
+ import json
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+ from tempergraph.audit.catalog import BY_ID, CONFIDENCE_RANK, SEVERITY_RANK, known
12
+ from tempergraph.constants import SCHEMA
13
+
14
+ SARIF_LEVEL = {"error": "error", "warning": "warning", "info": "note"}
15
+
16
+
17
+ @dataclass(kw_only=True)
18
+ class AuditFinding:
19
+ rule: str # catalog id, or `validate:<code>` and `<owner>:<code>` for owned rules
20
+ layer: str
21
+ severity: str
22
+ confidence: str
23
+ cause: str = ""
24
+ unit: str | None = None
25
+ item: str | None = None
26
+ session: str | None = None # `step` or `judge`
27
+ statement: str = ""
28
+ evidence: dict[str, Any] = field(default_factory=dict)
29
+ remedy: str = ""
30
+ widening: bool = False
31
+ location: dict[str, Any] = field(default_factory=dict) # {file, field?, line?}
32
+ owner: str = "audit"
33
+ ignored: dict[str, Any] | None = None
34
+
35
+ @property
36
+ def key(self) -> tuple[str, str | None, str | None]:
37
+ return self.rule, self.unit, self.item
38
+
39
+ def shown(self) -> bool:
40
+ """The default view (AUD-B7, AUD-B12): error or warning, high or medium confidence, not ignored."""
41
+ return (self.ignored is None and self.severity in ("error", "warning")
42
+ and self.confidence in ("high", "medium"))
43
+
44
+ def to_json(self) -> dict[str, Any]:
45
+ return {"rule": self.rule, "layer": self.layer, "severity": self.severity, "confidence": self.confidence,
46
+ "cause": self.cause, "unit": self.unit, "item": self.item, "session": self.session,
47
+ "statement": self.statement, "evidence": self.evidence, "remedy": self.remedy,
48
+ "widening": self.widening, "location": self.location, "owner": self.owner,
49
+ "ignored": self.ignored}
50
+
51
+
52
+ @dataclass(frozen=True, kw_only=True)
53
+ class Ignore:
54
+ rule: str
55
+ reason: str
56
+ unit: str | None = None
57
+ until: dt.date | None = None
58
+
59
+ def lapsed(self, today: dt.date) -> bool:
60
+ return self.until is not None and today > self.until
61
+
62
+ def matches(self, f: AuditFinding) -> bool:
63
+ return f.rule == self.rule and (self.unit is None or self.unit == f.unit)
64
+
65
+
66
+ def parse_ignores(raw: Any) -> tuple[list[Ignore], list[str]]:
67
+ """`audit.ignore` of `tempergraph.json` (AUD-B14): the ignores, and the problems that validation
68
+ refuses (AUD-AC7: a missing reason; a bad date or shape)."""
69
+ out: list[Ignore] = []
70
+ problems: list[str] = []
71
+ if raw is None:
72
+ return out, problems
73
+ if not isinstance(raw, list):
74
+ return out, ["audit.ignore must be a list of {rule, unit?, reason, until?}"]
75
+ for i, item in enumerate(raw):
76
+ if not isinstance(item, dict) or not isinstance(item.get("rule"), str) or not item["rule"]:
77
+ problems.append(f"audit.ignore[{i}] needs a rule id")
78
+ continue
79
+ reason = item.get("reason")
80
+ if not isinstance(reason, str) or not reason.strip():
81
+ problems.append(f"audit.ignore[{i}] ({item['rule']}) needs a one-sentence reason")
82
+ continue
83
+ until = None
84
+ if item.get("until") is not None:
85
+ try:
86
+ until = dt.date.fromisoformat(str(item["until"]))
87
+ except ValueError:
88
+ problems.append(f"audit.ignore[{i}] until {item['until']!r} is not a date (YYYY-MM-DD)")
89
+ continue
90
+ unit = item.get("unit")
91
+ out.append(Ignore(rule=item["rule"], reason=reason.strip(), unit=str(unit) if unit else None, until=until))
92
+ return out, problems
93
+
94
+
95
+ def apply_ignores(findings: list[AuditFinding], ignores: list[Ignore], today: dt.date) -> list[AuditFinding]:
96
+ """Mark ignored findings; an ignore never hides a validation error; an unknown rule id is itself an
97
+ `info` finding. Returns the extra findings the ignores raise."""
98
+ extra: list[AuditFinding] = []
99
+ for ig in ignores:
100
+ if not known(ig.rule):
101
+ extra.append(AuditFinding(
102
+ rule="ignore-rule-unknown", layer="definition", severity="info", confidence="high",
103
+ statement=f"audit.ignore names rule {ig.rule!r}, which the catalog does not know",
104
+ remedy=BY_ID["ignore-rule-unknown"].remedy, evidence={"rule": ig.rule},
105
+ location={"file": "tempergraph.json", "field": "audit.ignore"}))
106
+ continue
107
+ if ig.lapsed(today):
108
+ continue # AUD-AC7: a lapsed `until` shows the finding again
109
+ for f in findings:
110
+ if f.ignored is None and ig.matches(f) and not (f.rule.startswith("validate:") and f.severity == "error"):
111
+ f.ignored = {"reason": ig.reason, **({"until": ig.until.isoformat()} if ig.until else {})}
112
+ return extra
113
+
114
+
115
+ def order(findings: list[AuditFinding], unit_order: tuple[str, ...]) -> list[AuditFinding]:
116
+ """Validation errors lead (AUD-B2); then severity, confidence, the rule's rank, unit order (AUD-B12, AUD-B13)."""
117
+ pos = {u: i for i, u in enumerate(unit_order)}
118
+
119
+ def key(f: AuditFinding) -> tuple[Any, ...]:
120
+ base = f.rule.partition(":")[2] if ":" in f.rule else f.rule
121
+ rule = BY_ID.get(f.rule) or BY_ID.get(_OWNED_AS.get(f.rule.partition(":")[0], ""), None)
122
+ rank = rule.rank if rule is not None else (9, 999)
123
+ lead = 0 if (f.rule.startswith("validate:") and f.severity == "error") else 1
124
+ return (lead, SEVERITY_RANK.get(f.severity, 3), CONFIDENCE_RANK.get(f.confidence, 3), rank,
125
+ pos.get(f.unit or "", len(pos)), base, f.item or "")
126
+
127
+ return sorted(findings, key=key)
128
+
129
+
130
+ # An owned finding sorts at its catalog row.
131
+ _OWNED_AS = {"prompt-lint": "prompt-lint", "readiness": "judge-not-ready", "validate": "template-grammar",
132
+ "executor-compat": "executor-outside-tested-range", "cost-lens": "cost-lens-rules",
133
+ "SIL": "engine-fault-open"}
134
+
135
+
136
+ @dataclass(kw_only=True)
137
+ class AuditReport:
138
+ workflow: str
139
+ version: str
140
+ engine_version: str
141
+ layers_run: list[str] = field(default_factory=list)
142
+ layers_skipped: list[dict[str, Any]] = field(default_factory=list)
143
+ rules_skipped: list[dict[str, Any]] = field(default_factory=list)
144
+ findings: list[AuditFinding] = field(default_factory=list)
145
+ hot_spots: list[dict[str, Any]] = field(default_factory=list) # history only: one per unit with findings
146
+ owned: list[dict[str, Any]] = field(default_factory=list)
147
+ runs: int = 0
148
+ unreadable_runs: int = 0 # run logs left out as unreadable (AUD-B12, AUD-B15)
149
+ surface: Any = None # the session surface the tool rules read, shared with `audit tools`; never serialized
150
+ window_days: int = 30
151
+ show_all: bool = False
152
+
153
+ def visible(self) -> list[AuditFinding]:
154
+ return list(self.findings) if self.show_all else [f for f in self.findings if f.shown()]
155
+
156
+ def summary(self) -> dict[str, Any]:
157
+ live = [f for f in self.findings if f.ignored is None]
158
+ counts = {s: sum(1 for f in live if f.severity == s) for s in ("error", "warning", "info")}
159
+ shown = [f for f in self.findings if f.shown()]
160
+ return {"shown": len(shown), "by_severity": counts, "info": counts["info"],
161
+ "low_confidence": sum(1 for f in live if f.confidence == "low" and f.severity != "info"),
162
+ "ignored": sum(1 for f in self.findings if f.ignored is not None),
163
+ "rules_skipped": len(self.rules_skipped),
164
+ "highest_weight_cause": (f"{shown[0].rule} on {shown[0].unit or 'the workflow'}: "
165
+ f"{shown[0].statement}") if shown else None}
166
+
167
+ def exit_code(self, fail_on: str) -> int:
168
+ """AUD-AC5: 6 exactly when a non-ignored finding is at or above the level, else 0."""
169
+ if fail_on == "never":
170
+ return 0
171
+ top = SEVERITY_RANK[fail_on]
172
+ return 6 if any(f.ignored is None and SEVERITY_RANK.get(f.severity, 3) <= top for f in self.findings) else 0
173
+
174
+ def to_json(self) -> dict[str, Any]:
175
+ return {"schema_version": SCHEMA["audit_report"], "workflow": self.workflow, "version": self.version,
176
+ "engine_version": self.engine_version, "layers_run": self.layers_run,
177
+ "layers_skipped": self.layers_skipped, "rules_skipped": self.rules_skipped,
178
+ "window_days": self.window_days, "runs": self.runs, "unreadable_runs": self.unreadable_runs,
179
+ "findings": [f.to_json() for f in self.visible()], "hot_spots": self.hot_spots,
180
+ "owned": self.owned, "summary": self.summary()}
181
+
182
+ def to_text(self) -> str:
183
+ s = self.summary()
184
+ lines = [f"audit {self.workflow} {self.version} (engine {self.engine_version})",
185
+ f"layers: {', '.join(self.layers_run) or 'none'}"
186
+ + "".join(f"; {d['layer']} skipped: {d['reason']}" for d in self.layers_skipped),
187
+ f"{self.runs} runs read, {self.unreadable_runs} runs unreadable (last {self.window_days} days)", ""]
188
+ for h in self.hot_spots:
189
+ lines.append(f"hot spot {h['unit']}: {h['findings']} findings, leading {h['leading_rule']}")
190
+ if self.hot_spots:
191
+ lines.append("")
192
+ for f in self.visible():
193
+ mark = " [ignored]" if f.ignored else ""
194
+ lines.append(f"{f.rule} {f.severity}/{f.confidence} {f.unit or '-'}{mark}")
195
+ lines.append(f" {f.statement}")
196
+ if f.evidence:
197
+ lines.append(" evidence: " + ", ".join(f"{k}={v}" for k, v in f.evidence.items()))
198
+ if f.remedy:
199
+ lines.append(f" remedy: {f.remedy}" + (" [widens]" if f.widening else ""))
200
+ if f.location:
201
+ where = f.location.get("file", "")
202
+ if f.location.get("line"):
203
+ where += f":{f.location['line']}"
204
+ if f.location.get("field"):
205
+ where += f" ({f.location['field']})"
206
+ lines.append(f" at: {where}")
207
+ lines.append("")
208
+ for o in self.owned:
209
+ lines.append(f"owned: {o['owner']}: {o['count']} findings")
210
+ lines.append(f"{s['shown']} shown, {s['info']} info, {s['ignored']} ignored, {s['rules_skipped']} rules skipped")
211
+ if s["highest_weight_cause"]:
212
+ lines.append(f"highest-weight cause: {s['highest_weight_cause']}")
213
+ return "\n".join(lines) + "\n"
214
+
215
+ def to_sarif(self) -> dict[str, Any]:
216
+ """SARIF 2.1.0: one result per visible finding, at its package file and line where known (AUD-B9)."""
217
+ ids = sorted({f.rule for f in self.visible()})
218
+ rules = []
219
+ for rid in ids:
220
+ r = BY_ID.get(rid)
221
+ rules.append({"id": rid, "shortDescription": {"text": rid},
222
+ **({"help": {"text": r.remedy}} if r is not None and r.remedy else {})})
223
+ results = []
224
+ for f in self.visible():
225
+ res: dict[str, Any] = {"ruleId": f.rule, "level": SARIF_LEVEL.get(f.severity, "note"),
226
+ "message": {"text": f.statement}}
227
+ if f.widening:
228
+ res["properties"] = {"widening": True}
229
+ if f.location.get("file"):
230
+ phys: dict[str, Any] = {"artifactLocation": {"uri": f.location["file"]}}
231
+ if f.location.get("line"):
232
+ phys["region"] = {"startLine": int(f.location["line"])}
233
+ res["locations"] = [{"physicalLocation": phys}]
234
+ if f.ignored is not None:
235
+ res["suppressions"] = [{"kind": "inSource", "justification": f.ignored["reason"]}]
236
+ results.append(res)
237
+ return {"$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0",
238
+ "runs": [{"tool": {"driver": {"name": "tempergraph-audit", "version": self.engine_version,
239
+ "rules": rules}},
240
+ "results": results}]}
241
+
242
+
243
+ def render(report: AuditReport, fmt: str) -> str:
244
+ if fmt == "json":
245
+ return json.dumps(report.to_json(), indent=2, ensure_ascii=False) + "\n"
246
+ if fmt == "sarif":
247
+ return json.dumps(report.to_sarif(), indent=2, ensure_ascii=False) + "\n"
248
+ return report.to_text()
@@ -0,0 +1,220 @@
1
+ """Decision records whose `Revisit when` trigger has fired (DRV-B1 to DRV-B4): the audit reads the decision records of
2
+ a workflow package's `docs/adr/`, parses the lines that name something the engine records, compares each trigger's
3
+ state with the one the last stamp recorded and reports `decision-revisit-due` (info, advisory). Model-free; an
4
+ issue's state is read through an injected reader, and an unreadable state never fires."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import re
10
+ from collections.abc import Callable, Mapping
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from tempergraph.contracts import WorkflowSpec
16
+
17
+ LIVE_CHECK = re.compile(r"\blive check `?((?:[A-Z][A-Z0-9]{0,7}-)?L-?\d+)`?", re.I)
18
+ ISSUE = re.compile(r"(?<![\w/#])#(\d+)\b")
19
+ MEASURE = re.compile(r"`([A-Za-z0-9_./-]+\.md)`\s+(chars|prohibitions|reasons|prohibitions_per_reason|"
20
+ r"goal_branch_share)\s+(above|below|at or above|at or below)\s+([0-9][0-9_,]*(?:\.[0-9]+)?)", re.I)
21
+ VERSION = re.compile(r"\b(engine|claude|claude code)\s+version\s+(moves|changes|reaches\s+([0-9]+\.[0-9]+\.[0-9]+))",
22
+ re.I)
23
+ SECTION = re.compile(r"^##\s+Revisit when\s*$", re.M)
24
+
25
+ Kind = str # live_check, issue, measure, version
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Trigger:
30
+ record: str # package-relative path of the decision record
31
+ kind: Kind
32
+ key: str # what the stamp keys the state by, such as `issue:12` or `measure:prompts/a.md:chars>12000`
33
+ text: str # the line, as written
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Prose:
38
+ record: str
39
+ text: str
40
+
41
+
42
+ def revisit_lines(text: str) -> list[str]:
43
+ """The non-empty lines of a record's `Revisit when` section, list markers removed."""
44
+ m = SECTION.search(text)
45
+ if m is None:
46
+ return []
47
+ body = text[m.end():]
48
+ nxt = re.search(r"^##\s", body, re.M)
49
+ body = body[:nxt.start()] if nxt else body
50
+ return [ln.strip().lstrip("-* ").strip() for ln in body.splitlines() if ln.strip()]
51
+
52
+
53
+ def parse(record: str, text: str) -> tuple[list[Trigger], list[Prose]]:
54
+ """DRV-B1: each line's machine-readable triggers; a line with none is prose."""
55
+ triggers: list[Trigger] = []
56
+ prose: list[Prose] = []
57
+ for line in revisit_lines(text):
58
+ found: list[Trigger] = []
59
+ for m in LIVE_CHECK.finditer(line):
60
+ found.append(Trigger(record, "live_check", f"live_check:{m.group(1).upper()}", line))
61
+ for m in MEASURE.finditer(line):
62
+ op = {"above": ">", "below": "<", "at or above": ">=", "at or below": "<="}[m.group(3).lower()]
63
+ value = m.group(4).replace(",", "").replace("_", "")
64
+ found.append(Trigger(record, "measure", f"measure:{m.group(1)}:{m.group(2).lower()}{op}{value}", line))
65
+ for m in VERSION.finditer(line):
66
+ who = "engine" if m.group(1).lower() == "engine" else "claude"
67
+ found.append(Trigger(record, "version", f"version:{who}" + (f">={m.group(3)}" if m.group(3) else ""),
68
+ line))
69
+ for m in ISSUE.finditer(line):
70
+ found.append(Trigger(record, "issue", f"issue:{m.group(1)}", line))
71
+ if found:
72
+ triggers += found
73
+ else:
74
+ prose.append(Prose(record, line))
75
+ return triggers, prose
76
+
77
+
78
+ def records(root: Path | None) -> list[tuple[str, str]]:
79
+ if root is None:
80
+ return []
81
+ out = []
82
+ for p in sorted((root / "docs" / "adr").glob("*.md")):
83
+ if p.name.lower() in ("readme.md", "index.md"):
84
+ continue
85
+ try:
86
+ out.append((p.relative_to(root).as_posix(), p.read_text(encoding="utf-8")))
87
+ except (OSError, UnicodeDecodeError):
88
+ continue
89
+ return out
90
+
91
+
92
+ def read_all(root: Path | None) -> tuple[list[Trigger], list[Prose]]:
93
+ triggers: list[Trigger] = []
94
+ prose: list[Prose] = []
95
+ for rel, text in records(root):
96
+ t, p = parse(rel, text)
97
+ triggers += t
98
+ prose += p
99
+ return triggers, prose
100
+
101
+
102
+ @dataclass
103
+ class Readers:
104
+ """Where a trigger's state comes from; a reader that returns None leaves the state unknown."""
105
+ issue: Callable[[int], str | None] = lambda n: None # `open` or `closed`
106
+ claude_version: Callable[[], str | None] = lambda: None
107
+ engine_version: str = ""
108
+
109
+
110
+ def _live_row(root: Path, check: str) -> str | None:
111
+ """The digest of the last row of a package plan whose first cell is the check id, `none` when no row has it."""
112
+ last: str | None = None
113
+ for p in sorted((root / "docs" / "plans").glob("*.md")):
114
+ try:
115
+ lines = p.read_text(encoding="utf-8").splitlines()
116
+ except (OSError, UnicodeDecodeError):
117
+ continue
118
+ for ln in lines:
119
+ cells = [c.strip() for c in ln.strip().strip("|").split("|")]
120
+ if ln.lstrip().startswith("|") and cells and cells[0].upper() == check:
121
+ last = ln.strip()
122
+ return hashlib.sha256(last.encode()).hexdigest()[:16] if last else "none"
123
+
124
+
125
+ def _version_tuple(v: str) -> tuple[int, ...]:
126
+ return tuple(int(x) for x in re.findall(r"\d+", v)[:3])
127
+
128
+
129
+ def state(spec: WorkflowSpec, t: Trigger, readers: Readers) -> str | None:
130
+ """DRV-B2: the trigger's state now, None when it cannot be read."""
131
+ root = spec.package_root
132
+ if root is None:
133
+ return None
134
+ kind, _, rest = t.key.partition(":")
135
+ if kind == "live_check":
136
+ return _live_row(root, rest)
137
+ if kind == "issue":
138
+ return readers.issue(int(rest))
139
+ if kind == "measure":
140
+ from tempergraph.audit.text_health import measure
141
+
142
+ m = re.fullmatch(r"(.+):([a-z_]+)(>=|<=|>|<)([0-9.]+)", rest)
143
+ if m is None:
144
+ return None
145
+ try:
146
+ got = getattr(measure((root / m.group(1)).read_text(encoding="utf-8")), m.group(2))
147
+ except (OSError, UnicodeDecodeError, AttributeError):
148
+ return None
149
+ v, limit = float(got), float(m.group(4))
150
+ crossed = {">": v > limit, "<": v < limit, ">=": v >= limit, "<=": v <= limit}[m.group(3)]
151
+ return "crossed" if crossed else "within"
152
+ if kind == "version":
153
+ who, _, at = rest.partition(">=")
154
+ now = readers.engine_version if who == "engine" else readers.claude_version()
155
+ if not now:
156
+ return None
157
+ if at:
158
+ return "reached" if _version_tuple(now) >= _version_tuple(at) else "below"
159
+ return now
160
+ return None
161
+
162
+
163
+ def states(spec: WorkflowSpec, readers: Readers) -> dict[str, dict[str, str]]:
164
+ """What the stamp records (DRV-B3): per record, each trigger's state that could be read."""
165
+ out: dict[str, dict[str, str]] = {}
166
+ for t in read_all(spec.package_root)[0]:
167
+ s = state(spec, t, readers)
168
+ if s is not None:
169
+ out.setdefault(t.record, {})[t.key] = s
170
+ return out
171
+
172
+
173
+ def fired(t: Trigger, was: str | None, now: str | None) -> bool:
174
+ """DRV-B2: the trigger's state changed since the stamp in the direction its form names."""
175
+ if now is None:
176
+ return False
177
+ kind = t.kind
178
+ if kind == "issue":
179
+ return now == "closed" and was != "closed"
180
+ if kind == "measure":
181
+ return now == "crossed" and was != "crossed"
182
+ if kind == "version" and ">=" in t.key:
183
+ return now == "reached" and was != "reached"
184
+ return was is not None and was != now # a live check's row, a version that moves
185
+
186
+
187
+ def rows(spec: WorkflowSpec, stamp: Mapping[str, Any] | None, readers: Readers) -> list[dict[str, Any]]:
188
+ """`audit decisions`: one row per trigger and per prose line (DRV-B4)."""
189
+ stamped = dict((stamp or {}).get("revisit") or {})
190
+ triggers, prose = read_all(spec.package_root)
191
+ out: list[dict[str, Any]] = []
192
+ for t in triggers:
193
+ was = (stamped.get(t.record) or {}).get(t.key)
194
+ now = state(spec, t, readers)
195
+ out.append({"record": t.record, "kind": t.kind, "trigger": t.key, "line": t.text, "stamped": was,
196
+ "now": now, "due": stamp is not None and fired(t, was, now)})
197
+ out += [{"record": p.record, "kind": "not machine-readable", "line": p.text} for p in prose]
198
+ return out
199
+
200
+
201
+ def findings(spec: WorkflowSpec, stamp: Mapping[str, Any] | None, readers: Readers) -> list[Any]:
202
+ """DRV-B2: one `decision-revisit-due` finding per fired trigger; none without a stamp."""
203
+ from tempergraph.audit.catalog import rule
204
+ from tempergraph.audit.report import AuditFinding
205
+
206
+ if stamp is None:
207
+ return []
208
+ r = rule("decision-revisit-due")
209
+ out = []
210
+ for row in rows(spec, stamp, readers):
211
+ if not row.get("due"):
212
+ continue
213
+ out.append(AuditFinding(rule=r.id, layer=r.layer, severity=r.severity, confidence=r.confidence, cause=r.cause,
214
+ unit=None, item=row["trigger"], session=None,
215
+ statement=f"{row['record']}: its revisit trigger {row['trigger']!r} has fired "
216
+ f"(stamped {row['stamped'] or 'unread'}, now {row['now']})",
217
+ evidence={"trigger": row["trigger"], "line": row["line"], "stamped": row["stamped"],
218
+ "now": row["now"]},
219
+ remedy=r.remedy, location={"file": row["record"]}))
220
+ return out