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,263 @@
1
+ """The compatibility changelog and a workflow's compatibility with the running engine (VER-B9, VER-B2, VER-B5).
2
+
3
+ One file per release, `tempergraph/data/changelog/<engine_version>.json`. Range selection reads the files
4
+ after the stamp up to and including the running engine, oldest first (VER-B2). Detect rules run typed kinds
5
+ first; a `text` hit at a location a typed rule already hit is dropped (VER-B3). Read-only, model-free.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import fnmatch
12
+ import json
13
+ import re
14
+ from collections.abc import Iterable, Mapping
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph.constants import ENGINE_VERSION
20
+ from tempergraph.contracts import WorkflowSpec
21
+ from tempergraph.package.inventory import canonical
22
+
23
+ CHANGELOG_DIR = Path(__file__).resolve().parents[1] / "data" / "changelog"
24
+ AUDIENCES = frozenset({"workflow", "operator", "state", "integration"})
25
+ KINDS = frozenset({"added", "deprecated", "renamed", "removed", "changed", "tightened", "behaviour", "executor"})
26
+ SURFACES = frozenset({"spec_field", "declaration", "callable", "template", "capability", "tool_name", "cli",
27
+ "document", "state"})
28
+ DETECT_KINDS = frozenset({"field", "symbol", "template_key", "tool_ref", "finding", "text"})
29
+ MIGRATE = frozenset({"transform", "assisted", "owner", "none"})
30
+ TRANSFORMS = {"rename_field": "spec_field", "set_field": "spec_field", "drop_field": "spec_field",
31
+ "rename_symbol": "declaration", "rename_template_key": "template", "rename_tool": "tool_name",
32
+ "map_capability": "capability", "model_list_to_escalation": "spec_field",
33
+ "rename_produced_key": "spec_field"}
34
+ TYPED = ("field", "symbol", "template_key", "tool_ref", "finding")
35
+ CHILD_SURFACES = frozenset({"spec_field", "declaration"}) # VER-B17: what another workflow can depend on of a child
36
+
37
+
38
+ def semver(v: str) -> tuple[int, int, int]:
39
+ m = re.match(r"^(\d+)\.(\d+)\.(\d+)", v)
40
+ if m is None:
41
+ raise ValueError(f"{v!r} is not a semantic version")
42
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
43
+
44
+
45
+ def entry_problems(e: Mapping[str, Any]) -> list[str]:
46
+ """VER-AC2: an entry against VER-B9, and VER-B4: a `renamed` entry a transform fits carries it."""
47
+ out = []
48
+ if not re.match(r"^E\d+\.\d+\.\d+-\d+$", str(e.get("id") or "")):
49
+ out.append("id must be E<version>-<n>")
50
+ for key, allowed in (("audience", AUDIENCES), ("kind", KINDS), ("surface", SURFACES)):
51
+ if e.get(key) not in allowed:
52
+ out.append(f"{key} {e.get(key)!r} is not one of {sorted(allowed)}")
53
+ if not isinstance(e.get("breaking"), bool):
54
+ out.append("breaking must be true or false")
55
+ if e.get("kind") == "added" and e.get("breaking"):
56
+ out.append("an `added` entry is never breaking")
57
+ for rule in e.get("detect") or []:
58
+ if not isinstance(rule, Mapping) or rule.get("kind") not in DETECT_KINDS:
59
+ out.append(f"detect rule {rule!r} has an unknown kind")
60
+ mig = e.get("migrate") or {}
61
+ if not isinstance(mig, Mapping) or mig.get("action") not in MIGRATE:
62
+ out.append("migrate must be one of transform, assisted, owner, none")
63
+ elif e.get("kind") == "renamed" and mig.get("action") != "transform":
64
+ fits = [t for t, s in TRANSFORMS.items() if s == e.get("surface") and t.startswith("rename")]
65
+ if fits:
66
+ out.append(f"a `renamed` entry on {e.get('surface')} carries a transform: {fits[0]}")
67
+ if e.get("kind") == "deprecated" and not e.get("removal_in"):
68
+ out.append("a `deprecated` entry names `removal_in`")
69
+ return out
70
+
71
+
72
+ def releases(folder: Path | None = None) -> list[tuple[tuple[int, int, int], Path]]:
73
+ d = folder or CHANGELOG_DIR
74
+ out = []
75
+ for p in d.glob("*.json") if d.is_dir() else []:
76
+ try:
77
+ out.append((semver(p.stem), p))
78
+ except ValueError:
79
+ continue
80
+ return sorted(out)
81
+
82
+
83
+ def entries_between(stamp: str | None, engine: str = ENGINE_VERSION,
84
+ folder: Path | None = None) -> list[dict[str, Any]]:
85
+ """VER-B2: files after `stamp` up to and including `engine`, oldest first; all of them when unstamped."""
86
+ lo = semver(stamp) if stamp else None
87
+ hi = semver(engine)
88
+ out: list[dict[str, Any]] = []
89
+ for v, path in releases(folder):
90
+ if (lo is None or v > lo) and v <= hi:
91
+ doc = json.loads(path.read_text(encoding="utf-8"))
92
+ out += [dict(e) for e in doc.get("entries") or [] if isinstance(e, Mapping)]
93
+ return out
94
+
95
+
96
+ def child_notes(root: Path, until: str | None = None, skip: Iterable[str] = ()) -> list[dict[str, Any]]:
97
+ """VER-B17: a workflow's own `changes/<version>.json` in the changelog's shape, read for a parent: the entries up
98
+ to and including version `until`, oldest first, with `audience: workflow` and a surface a parent can depend on
99
+ (`CHILD_SURFACES`). An entry that is not an entry of VER-B9 (`entry_problems`), and an entry id in `skip` (already
100
+ applied by the parent), is left out; an unreadable file reads as no notes."""
101
+ out: list[dict[str, Any]] = []
102
+ hi = semver(until) if until else None
103
+ for v, path in releases(root / "changes"):
104
+ if hi is not None and v > hi:
105
+ continue
106
+ try:
107
+ doc = json.loads(path.read_text(encoding="utf-8"))
108
+ except (OSError, ValueError):
109
+ continue
110
+ for e in doc.get("entries") or [] if isinstance(doc, Mapping) else []:
111
+ if (isinstance(e, Mapping) and not entry_problems(e) and e.get("audience") == "workflow"
112
+ and e.get("surface") in CHILD_SURFACES and str(e["id"]) not in set(skip)):
113
+ out.append(dict(e))
114
+ return out
115
+
116
+
117
+ def _for_unit(value: Any, unit: str) -> Any:
118
+ """A child's note cannot know what a parent calls the unit that runs it: `<unit>` in a rule or a parameter is the name."""
119
+ if isinstance(value, str):
120
+ return value.replace("<unit>", unit)
121
+ if isinstance(value, Mapping):
122
+ return {k: _for_unit(v, unit) for k, v in value.items()}
123
+ if isinstance(value, list):
124
+ return [_for_unit(v, unit) for v in value]
125
+ return value
126
+
127
+
128
+ def children_entries(spec: WorkflowSpec, stamp: Mapping[str, Any] | None = None) -> list[dict[str, Any]]:
129
+ """SWF-B9, VER-B17, WUP-B6: for each sub-workflow unit of `spec`, the change notes of the child it runs (from the
130
+ child's registered package, up to the child's current version) that the parent's stamp has not applied, as
131
+ entries of the parent's plan. An entry's id is `<unit>:<id>`, so two children's notes never meet, and `<unit>` in
132
+ its rules and parameters is the parent's unit name. A child that is not registered has no notes to read here:
133
+ validation speaks of it."""
134
+ from tempergraph.model import subworkflow
135
+
136
+ applied = {str(e.get("id")) for e in (stamp or {}).get("entries_applied") or [] if isinstance(e, Mapping)}
137
+ out: list[dict[str, Any]] = []
138
+ for unit in subworkflow.units_of(spec):
139
+ rec = spec.units[unit].subworkflow
140
+ got = subworkflow.read_child(rec.workflow) if rec is not None else None
141
+ if not isinstance(got, subworkflow.Child) or got.spec.package_root is None:
142
+ continue
143
+ for e in child_notes(Path(got.spec.package_root), got.version,
144
+ skip={i.partition(":")[2] for i in applied if i.startswith(f"{unit}:")}):
145
+ out.append({**_for_unit(e, unit), "id": f"{unit}:{e['id']}", "child": got.name, "unit": unit})
146
+ return out
147
+
148
+
149
+ def breaking_since_level(level: int, folder: Path | None = None) -> list[str]:
150
+ """PKG-B6 row 2: ids of the breaking `workflow` entries a package at interface `level` has not met. The
151
+ level starts at 1 and grows by one with each release holding such an entry (VER-B8), so the entries of
152
+ every release that raised it above `level` are the ones listed, oldest first."""
153
+ at, out = 1, []
154
+ for _, path in releases(folder):
155
+ doc = json.loads(path.read_text(encoding="utf-8"))
156
+ ids = [str(e.get("id")) for e in doc.get("entries") or [] if isinstance(e, Mapping)
157
+ and e.get("audience") == "workflow" and e.get("breaking")]
158
+ if ids:
159
+ at += 1
160
+ if at > level:
161
+ out += ids
162
+ return out
163
+
164
+
165
+ @dataclass(frozen=True)
166
+ class Hit:
167
+ entry: str
168
+ rule: str
169
+ where: str
170
+ confidence: str
171
+
172
+
173
+ def _field_values(obj: Any, parts: list[str], prefix: str = "") -> Iterable[tuple[str, Any]]:
174
+ if not parts:
175
+ yield prefix, obj
176
+ return
177
+ head, rest = parts[0], parts[1:]
178
+ if isinstance(obj, Mapping):
179
+ keys = list(obj) if head == "*" else ([head] if head in obj else [])
180
+ for k in keys:
181
+ yield from _field_values(obj[k], rest, f"{prefix}.{k}" if prefix else str(k))
182
+
183
+
184
+ def detect(entry: Mapping[str, Any], spec: WorkflowSpec, root: Path,
185
+ finding_codes: Iterable[str] = ()) -> list[Hit]:
186
+ eid = str(entry.get("id"))
187
+ hits: list[Hit] = []
188
+ data = canonical(spec)
189
+ codes = set(finding_codes)
190
+ py = [p for p in sorted((root / "workflow").rglob("*.py"))] if (root / "workflow").is_dir() else []
191
+ for i, rule in enumerate(entry.get("detect") or []):
192
+ rid, kind = str(rule.get("id") or f"{eid}/{i}"), rule.get("kind")
193
+ if kind == "field":
194
+ m = re.match(r"^(?P<path>[\w.*]+)(?:\s*==\s*(?P<value>.+))?$", str(rule.get("match") or ""))
195
+ if m:
196
+ want = json.loads(m.group("value")) if m.group("value") else None
197
+ for where, val in _field_values(data, m.group("path").split(".")):
198
+ if m.group("value") is None or val == want:
199
+ hits.append(Hit(eid, rid, where, "high"))
200
+ elif kind == "symbol":
201
+ name = str(rule.get("match") or "")
202
+ for p in py:
203
+ for node in ast.walk(ast.parse(p.read_text(encoding="utf-8"))):
204
+ if isinstance(node, ast.ImportFrom) and node.module == "tempergraph.api" and any(
205
+ a.name == name for a in node.names):
206
+ hits.append(Hit(eid, rid, f"{p.relative_to(root).as_posix()}:{node.lineno}", "high"))
207
+ elif kind == "finding":
208
+ if str(rule.get("match")) in codes:
209
+ hits.append(Hit(eid, rid, f"finding:{rule.get('match')}", "high"))
210
+ elif kind in ("template_key", "tool_ref", "text"):
211
+ pat = re.compile(str(rule.get("match") or "") if kind == "text" else re.escape(
212
+ ("{" + str(rule.get("match")) + "}") if kind == "template_key" else str(rule.get("match"))))
213
+ glob = str(rule.get("files") or "**/*")
214
+ for p in sorted(root.rglob("*")):
215
+ rel = p.relative_to(root).as_posix()
216
+ if not p.is_file() or rel.startswith(("docs/", ".git/")) or not fnmatch.fnmatch(rel, glob):
217
+ continue
218
+ try:
219
+ text = p.read_text(encoding="utf-8")
220
+ except (OSError, UnicodeDecodeError):
221
+ continue
222
+ for m2 in pat.finditer(text):
223
+ line = text.count("\n", 0, m2.start()) + 1
224
+ hits.append(Hit(eid, rid, f"{rel}:{line}", "low" if kind == "text" else "high"))
225
+ typed = {h.where for h in hits if h.confidence == "high"}
226
+ return [h for h in hits if h.confidence == "high" or h.where not in typed]
227
+
228
+
229
+ def compatibility(spec: WorkflowSpec, root: Path, stamp: Mapping[str, Any] | None, *,
230
+ engine: str = ENGINE_VERSION, folder: Path | None = None,
231
+ finding_codes: Iterable[str] = ()) -> dict[str, Any]:
232
+ """VER-B2, VER-B5: `current`, `stamp_behind`, `needs_upgrade`, `out_of_range`, `unstamped`, with the hits."""
233
+ stamped = str(stamp.get("engine_version")) if stamp else None
234
+ entries = [e for e in entries_between(stamped, engine, folder) if e.get("audience") == "workflow"]
235
+ entries += children_entries(spec, stamp) # SWF-B9: the notes of every sub-workflow the workflow runs (VER-B17)
236
+ hits = {str(e["id"]): detect(e, spec, root, finding_codes) for e in entries}
237
+ breaking = [e["id"] for e in entries if e.get("breaking") and hits.get(str(e["id"]))]
238
+ if spec.requires_engine and not _in_range(engine, spec.requires_engine):
239
+ state = "out_of_range"
240
+ elif stamped is None:
241
+ state = "unstamped"
242
+ elif breaking:
243
+ state = "needs_upgrade"
244
+ elif stamped == engine or not any(hits.values()):
245
+ state = "current"
246
+ else:
247
+ state = "stamp_behind"
248
+ return {"state": state, "stamp": stamped, "engine": engine, "entries": [e["id"] for e in entries],
249
+ "hits": {k: [h.__dict__ for h in v] for k, v in hits.items() if v}, "breaking": breaking}
250
+
251
+
252
+ def _in_range(version: str, spec_range: str) -> bool:
253
+ v = semver(version)
254
+ for part in (p.strip() for p in spec_range.split(",") if p.strip()):
255
+ m = re.match(r"^(>=|<=|==|<|>|!=)\s*(\d+(?:\.\d+){0,2})$", part)
256
+ if m is None:
257
+ return False
258
+ parts = [int(x) for x in m.group(2).split(".")] + [0, 0]
259
+ b = (parts[0], parts[1], parts[2])
260
+ ok = {">=": v >= b, "<=": v <= b, "==": v == b, "<": v < b, ">": v > b, "!=": v != b}[m.group(1)]
261
+ if not ok:
262
+ return False
263
+ return True
@@ -0,0 +1,115 @@
1
+ """The docs check of a package's docs half, `docs-drift` (PKG-B21, PKG-B22, PKG-B9, PKG-AC6).
2
+
3
+ Criterion text lives only in `outcome.json`; the docs name each criterion by id as an acceptance criterion
4
+ (`- [ ] <id> <text>`) in the spec of its unit, or the overview for a final criterion. The check compares ids
5
+ and whitespace-normalised text, and resolves every relative link under `docs/`. A miss is a warning; in
6
+ `stable` mode an error. It reads files only.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from collections.abc import Mapping
14
+ from pathlib import Path
15
+ from typing import Literal
16
+
17
+ from tempergraph.contracts import WorkflowSpec
18
+ from tempergraph.model.validate import Finding
19
+
20
+ OVERVIEW = "overview.spec.md"
21
+ SPEC_RE = re.compile(r"^(?:\d{2}-)?(?P<name>.+)\.spec\.md$") # an earlier layout's number prefix is read, never written
22
+ AC_RE = re.compile(r"^\s*-\s*\[[ xX]\]\s+(?P<id>\S+)\s+(?P<text>.+?)\s*$")
23
+ LINK_RE = re.compile(r"\[[^\]]*\]\((?P<target>[^)\s]+)\)")
24
+ AC_HEADING = re.compile(r"^##\s+6\b|^##\s+acceptance criteria\b", re.I)
25
+
26
+
27
+ def _norm(text: str) -> str:
28
+ return " ".join(text.split())
29
+
30
+
31
+ def criteria_of(spec: WorkflowSpec, root: Path) -> tuple[dict[str, str], dict[str, dict[str, str]]]:
32
+ """(final id -> text, unit -> {id -> text}); from the attached outcome, else a tolerant read of the file."""
33
+ if spec.outcome is not None:
34
+ final = {c.id: c.text for c in spec.outcome.final if c.id}
35
+ inter = {u: {c.id: c.text for c in o.criteria if c.id} for u, o in spec.outcome.intermediate.items()}
36
+ return final, inter
37
+ try:
38
+ doc = json.loads((root / "outcome.json").read_text(encoding="utf-8"))
39
+ except (OSError, ValueError):
40
+ return {}, {}
41
+ if not isinstance(doc, dict):
42
+ return {}, {}
43
+
44
+ def ids(rows: object) -> dict[str, str]:
45
+ return {str(r["id"]): str(r.get("text", "")) for r in rows or [] # type: ignore[attr-defined]
46
+ if isinstance(r, dict) and r.get("id")}
47
+
48
+ inter_doc = doc.get("intermediate") or {}
49
+ return ids(doc.get("final")), {str(u): ids((o or {}).get("criteria")) for u, o in inter_doc.items()
50
+ if isinstance(o, dict)}
51
+
52
+
53
+ def _acceptance(text: str) -> dict[str, str]:
54
+ out: dict[str, str] = {}
55
+ inside = False
56
+ for line in text.splitlines():
57
+ if line.startswith("## "):
58
+ inside = bool(AC_HEADING.match(line))
59
+ continue
60
+ m = AC_RE.match(line) if inside else None
61
+ if m:
62
+ out[m.group("id")] = _norm(m.group("text"))
63
+ return out
64
+
65
+
66
+ def docs_check(spec: WorkflowSpec, root: Path, mode: Literal["dev", "stable"] | None = None) -> list[Finding]:
67
+ severity: Literal["error", "warning"] = "error" if (mode or spec.improvement_mode) == "stable" else "warning"
68
+ out: list[Finding] = []
69
+
70
+ def drift(unit: str | None, message: str) -> None:
71
+ out.append(Finding("docs-drift", unit, message, severity))
72
+
73
+ specs_dir = root / "docs" / "specs"
74
+ files: dict[str, Path] = {} # unit (or "" for the overview) -> file
75
+ if specs_dir.is_dir():
76
+ units = {u.replace("_", "-"): u for u in spec.order}
77
+ for p in sorted(specs_dir.glob("*.spec.md")):
78
+ name = m.group("name").replace("_", "-") if (m := SPEC_RE.match(p.name)) is not None else ""
79
+ if name == "overview":
80
+ files[""] = p
81
+ elif name in units:
82
+ files[units[name]] = p
83
+ final, inter = criteria_of(spec, root)
84
+ expected: dict[str, Mapping[str, str]] = {"": final, **{u: inter.get(u, {}) for u in spec.order}}
85
+ known = set(final) | {cid for ids in inter.values() for cid in ids}
86
+ if "" not in files:
87
+ drift(None, f"docs/specs/{OVERVIEW} is missing")
88
+ for unit in spec.order:
89
+ if unit not in files:
90
+ drift(unit, f"unit {unit!r} has no spec under docs/specs/ ({unit.replace('_', '-')}.spec.md)")
91
+ seen: dict[str, list[str]] = {}
92
+ for owner, path in files.items():
93
+ rel = path.relative_to(root).as_posix()
94
+ acs = _acceptance(path.read_text(encoding="utf-8"))
95
+ for cid in acs:
96
+ seen.setdefault(cid, []).append(owner)
97
+ if cid not in known:
98
+ drift(owner or None, f"{rel} names criterion {cid!r}, which outcome.json does not hold")
99
+ for cid, text in expected.get(owner, {}).items():
100
+ if cid not in acs:
101
+ drift(owner or None, f"criterion {cid!r} is not an acceptance criterion of {rel}")
102
+ elif acs[cid] != _norm(text):
103
+ drift(owner or None, f"criterion {cid!r}: the text in {rel} differs from outcome.json")
104
+ for cid, owners in seen.items():
105
+ if cid in known and len(owners) > 1:
106
+ drift(None, f"criterion {cid!r} is an acceptance criterion of more than one spec")
107
+ docs = root / "docs"
108
+ for p in sorted(docs.rglob("*.md")) if docs.is_dir() else []:
109
+ for m in LINK_RE.finditer(p.read_text(encoding="utf-8")):
110
+ target = m.group("target").split("#", 1)[0]
111
+ if not target or re.match(r"^[a-z][a-z0-9+.-]*:", target):
112
+ continue
113
+ if not (p.parent / target).exists():
114
+ drift(None, f"{p.relative_to(root).as_posix()}: link {target!r} does not resolve")
115
+ return out
@@ -0,0 +1,90 @@
1
+ """Private import names for workflow packages (PKG-B15, PKG-B16, PKG-B17 step 3, PKG-B3).
2
+
3
+ A package's entry module, the folder ``workflow/<module>/``, is imported as ``tgwf_<name>`` (the workflow name
4
+ with ``-`` as ``_``), so two packages that both hold a ``checks`` module never collide. The package's own
5
+ modules import each other relatively; their callables are recorded as ``tgwf_<name>.<sub>:<qualname>``.
6
+
7
+ A meta-path finder maps each private name to its folder. The engine process registers a package when it
8
+ loads it; a child process (the check worker) gets the same map in its context document and calls
9
+ :func:`install` before it imports a callable by reference (CHK-B16).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import importlib.abc
15
+ import importlib.machinery
16
+ import importlib.util
17
+ import sys
18
+ from collections.abc import Mapping, Sequence
19
+ from pathlib import Path
20
+ from types import ModuleType
21
+
22
+ PREFIX = "tgwf_"
23
+
24
+
25
+ def private_name(workflow: str) -> str:
26
+ return PREFIX + workflow.replace("-", "_")
27
+
28
+
29
+ class _Finder(importlib.abc.MetaPathFinder):
30
+ def __init__(self) -> None:
31
+ self.roots: dict[str, Path] = {}
32
+
33
+ def find_spec(self, fullname: str, path: Sequence[str] | None = None,
34
+ target: ModuleType | None = None) -> importlib.machinery.ModuleSpec | None:
35
+ top = fullname.partition(".")[0]
36
+ root = self.roots.get(top)
37
+ if root is None or fullname != top:
38
+ return None # submodules are found through the package's __path__
39
+ init = root / "__init__.py"
40
+ if not init.is_file():
41
+ return None
42
+ return importlib.util.spec_from_file_location(fullname, init, submodule_search_locations=[str(root)])
43
+
44
+
45
+ _FINDER = _Finder()
46
+
47
+
48
+ def _ensure_finder() -> None:
49
+ if _FINDER not in sys.meta_path:
50
+ sys.meta_path.insert(0, _FINDER)
51
+
52
+
53
+ def _purge(name: str) -> None:
54
+ for mod in [m for m in sys.modules if m == name or m.startswith(name + ".")]:
55
+ del sys.modules[mod]
56
+
57
+
58
+ def register(name: str, folder: Path) -> None:
59
+ """Map a private name to a package's entry folder; a different folder (a new version) drops the old modules."""
60
+ _ensure_finder()
61
+ folder = folder.resolve()
62
+ if _FINDER.roots.get(name) != folder:
63
+ _purge(name)
64
+ importlib.invalidate_caches()
65
+ _FINDER.roots[name] = folder
66
+
67
+
68
+ def import_entry(workflow: str, folder: Path) -> ModuleType:
69
+ """Import afresh: a load always reads the package's current source (PKG-B15, PKG-B16, PKG-B17). No bytecode is written
70
+ into the package, so loading (and `audit`, AUD-B6) leaves it byte-for-byte unchanged."""
71
+ name = private_name(workflow)
72
+ register(name, folder)
73
+ _purge(name)
74
+ importlib.invalidate_caches()
75
+ was, sys.dont_write_bytecode = sys.dont_write_bytecode, True
76
+ try:
77
+ return importlib.import_module(name)
78
+ finally:
79
+ sys.dont_write_bytecode = was
80
+
81
+
82
+ def mapping() -> dict[str, str]:
83
+ """The registered private names, for a child process's context document."""
84
+ return {k: str(v) for k, v in _FINDER.roots.items()}
85
+
86
+
87
+ def install(roots: Mapping[str, str] | None) -> None:
88
+ for name, folder in (roots or {}).items():
89
+ if name.startswith(PREFIX):
90
+ register(name, Path(folder))
@@ -0,0 +1,111 @@
1
+ """What is where in a package, and the digests over it (PKG-B13, PKG-B15 `package_files`, VER-B14, VER-B15, PKG-AC7).
2
+
3
+ `content_digest` covers what a run runs: the spec's canonical JSON, `outcome.json`, every template, brief,
4
+ lessons file, skill and agent file, every file the package declares in `step_files` (PKG-B13), every Python
5
+ source under `workflow/` and the `dependencies` of its `pyproject.toml`. It never covers `docs/`, `diagram/`, `evals/`, `authoring.json`, `README.md` or `tests/`.
6
+ `docs_digest` covers `docs/` only (PKG-B21, PKG-B22).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ import hashlib
13
+ import json
14
+ from collections.abc import Iterable, Mapping
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph.contracts import CallableRef, WorkflowSpec
20
+ from tempergraph.package.manifest import declared_step_files, step_files
21
+
22
+ # Folders and files whose content is part of what runs (VER-B14, VER-B15).
23
+ CONTENT_DIRS = ("prompts", "judges", "lessons", "skills", "agents")
24
+ CONTENT_FILES = ("outcome.json",)
25
+ SKIP_PARTS = frozenset({"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache"})
26
+
27
+
28
+ @dataclass(frozen=True, kw_only=True)
29
+ class PackageInventory:
30
+ root: Path
31
+ content: tuple[str, ...] = () # package-relative paths inside the content digest
32
+ python: tuple[str, ...] = () # workflow/**/*.py
33
+ docs: tuple[str, ...] = ()
34
+ other: tuple[str, ...] = () # present, outside both digests
35
+ present: frozenset[str] = field(default_factory=frozenset) # top-level names
36
+
37
+ def has(self, rel: str) -> bool:
38
+ return (self.root / rel).exists()
39
+
40
+
41
+ def _walk(root: Path, top: Path) -> Iterable[Path]:
42
+ if top.is_file():
43
+ yield top
44
+ return
45
+ if not top.is_dir():
46
+ return
47
+ for p in sorted(top.rglob("*")):
48
+ rel = p.relative_to(root)
49
+ if p.is_file() and not (SKIP_PARTS & set(rel.parts)) and p.suffix not in (".pyc", ".pyo"):
50
+ yield p
51
+
52
+
53
+ def package_files(package_path: Path) -> PackageInventory:
54
+ root = package_path
55
+ content: list[str] = []
56
+ for name in (*CONTENT_DIRS, *CONTENT_FILES):
57
+ content += [p.relative_to(root).as_posix() for p in _walk(root, root / name)]
58
+ python = [p.relative_to(root).as_posix() for p in _walk(root, root / "workflow") if p.suffix == ".py"]
59
+ # A declared step file is part of what a run runs wherever it lies, except in the Python half, which is covered.
60
+ content += [rel for rel in step_files(root, declared_step_files(root)) if rel not in {*content, *python}]
61
+ docs = [p.relative_to(root).as_posix() for p in _walk(root, root / "docs")]
62
+ docs = [rel for rel in docs if rel not in set(content)]
63
+ known = set(content) | set(python) | set(docs)
64
+ other = [p.relative_to(root).as_posix() for p in _walk(root, root)
65
+ if p.relative_to(root).as_posix() not in known and p.relative_to(root).parts[0] != ".git"]
66
+ present = frozenset(p.name for p in root.iterdir()) if root.is_dir() else frozenset()
67
+ return PackageInventory(root=root, content=tuple(content), python=tuple(python), docs=tuple(docs),
68
+ other=tuple(other), present=present)
69
+
70
+
71
+ def canonical(obj: Any) -> Any:
72
+ """A JSON-ready, order-stable form of a spec: callables by reference, paths and live objects left out."""
73
+ if isinstance(obj, CallableRef):
74
+ return obj.ref
75
+ if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
76
+ return {f.name: canonical(getattr(obj, f.name)) for f in dataclasses.fields(obj)
77
+ if f.name not in ("package_root", "outcome", "func", "verified_engine")}
78
+ if isinstance(obj, Mapping):
79
+ return {str(k): canonical(v) for k, v in sorted(obj.items(), key=lambda kv: str(kv[0]))}
80
+ if isinstance(obj, (list, tuple, set, frozenset)):
81
+ items = [canonical(v) for v in obj]
82
+ return sorted(items, key=json.dumps) if isinstance(obj, (set, frozenset)) else items
83
+ if isinstance(obj, Path):
84
+ return None
85
+ if obj is None or isinstance(obj, (str, int, float, bool)):
86
+ return obj
87
+ return repr(obj)
88
+
89
+
90
+ def _feed(h: Any, label: str, data: bytes) -> None:
91
+ h.update(label.encode() + b"\0" + str(len(data)).encode() + b"\0" + data)
92
+
93
+
94
+ def content_digest(spec: WorkflowSpec, inventory: PackageInventory, dependencies: Iterable[str]) -> str:
95
+ h = hashlib.sha256()
96
+ _feed(h, "spec", json.dumps(canonical(spec), sort_keys=True, separators=(",", ":")).encode())
97
+ for rel in sorted((*inventory.content, *inventory.python)):
98
+ _feed(h, rel, (inventory.root / rel).read_bytes())
99
+ _feed(h, "dependencies", "\n".join(sorted(" ".join(d.split()) for d in dependencies)).encode())
100
+ return h.hexdigest()
101
+
102
+
103
+ def docs_digest(inventory: PackageInventory) -> str:
104
+ h = hashlib.sha256()
105
+ for rel in sorted(inventory.docs):
106
+ _feed(h, rel, (inventory.root / rel).read_bytes())
107
+ return h.hexdigest()
108
+
109
+
110
+ def workflow_version(version: str, digest: str) -> str:
111
+ return f"{version}+{digest[:12]}"