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,346 @@
1
+ """The blueprint (SCF-B9, SCF-B11): a strict JSON document of the decided shape; `blueprint check` turns it into a
2
+ throwaway spec with stub prompts and gates, validates it, and checks it against the draft outcome.
3
+ Model-free and read-only (OVR-B15)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import json
9
+ from collections.abc import Mapping
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from tempergraph.api import (
15
+ Ask,
16
+ Criterion,
17
+ Gate,
18
+ Judge,
19
+ Map,
20
+ Parallel,
21
+ Question,
22
+ Route,
23
+ Routing,
24
+ Script,
25
+ Step,
26
+ Switch,
27
+ Wait,
28
+ Workflow,
29
+ )
30
+ from tempergraph.contracts import (
31
+ EFFORTS,
32
+ Capabilities,
33
+ InputDeclaration,
34
+ OutcomeSpec,
35
+ Param,
36
+ ProducesKind,
37
+ WorkflowSpec,
38
+ )
39
+ from tempergraph.model.validate import LATER_KINDS, SLUG_RE, Finding, validate
40
+ from tempergraph.package.manifest import name_problem
41
+
42
+ # The authoring blueprint states no sub-workflow, no contest and no council (SCF-B9): it cannot state slots or members,
43
+ # though the engine builds these kinds, so a blueprint keeps its `not_in_release` refusal of them.
44
+ BLUEPRINT_LATER_KINDS: dict[str, int] = {**LATER_KINDS, "subworkflow": 3, "contest": 3, "council": 3}
45
+ BLUEPRINT_FILE = "blueprint.json"
46
+ TOP_KEYS = frozenset({"schema_version", "name", "units", "flow", "outcome_ref", "input"})
47
+ UNIT_KEYS = frozenset({"name", "kind", "summary", "produces", "reads", "gate", "on_fail", "on_budget_spent",
48
+ "approval", "back_targets", "executor", "sizing", "judge_sizing"})
49
+ SIZING_KEYS = frozenset({"model", "effort", "why"})
50
+ SIZING_MIN_WORDS = 4
51
+ TIERS = ("small", "medium", "large")
52
+ GATE_KEYS = frozenset({"check", "judge", "signoff"})
53
+ RELEASE_KINDS = frozenset({"step", "script", "route", "switch", "map", "parallel", "ask", "wait"})
54
+ SESSION_UNIT_KINDS = frozenset({"step", "map"}) # kinds whose units run model sessions and so carry `sizing`
55
+ # A flow shape that belongs to one unit kind (SCF-B9, SCF-B11): the shape states that kind's parameters.
56
+ SHAPE_KIND = {"map": "map", "parallel": "parallel", "wait": "wait"}
57
+ FLOW_KINDS = frozenset({"route", "switch", "parallel", "map", "wait"})
58
+ MAX_UNITS = 20
59
+ SUMMARY_CHARS = 60
60
+ # Validation findings that are a reference problem of the shape; a blueprint check fails on them (SCF-B2).
61
+ REFERENCE_WARNINGS = frozenset({"template-key-not-on-every-path"})
62
+
63
+
64
+ def stub_check(ctx: Any) -> Any: # pragma: no cover - never run; only referenced by the throwaway spec
65
+ raise RuntimeError("blueprint stub")
66
+
67
+
68
+ def stub_select(view: Any) -> str: # pragma: no cover
69
+ raise RuntimeError("blueprint stub")
70
+
71
+
72
+ @dataclass(frozen=True, kw_only=True)
73
+ class BlueprintUnit:
74
+ name: str
75
+ kind: str
76
+ summary: str = ""
77
+ produces: tuple[str, ...] = ()
78
+ reads: tuple[str, ...] = ()
79
+ check: bool = False
80
+ judge: bool = False
81
+ signoff: bool = False
82
+ on_fail: str | None = None
83
+ on_budget_spent: str | None = None
84
+ approval: bool | None = None
85
+ back_targets: tuple[str, ...] = ()
86
+ executor: str | None = None
87
+ sizing: Mapping[str, str] | None = None # the step's model, effort and why (SCF-B9, SCF-B11, SCF-B10)
88
+ judge_sizing: Mapping[str, str] | None = None
89
+
90
+
91
+ @dataclass(frozen=True, kw_only=True)
92
+ class Blueprint:
93
+ name: str
94
+ units: tuple[BlueprintUnit, ...]
95
+ flow: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)
96
+ outcome_ref: Mapping[str, Any] | None = None
97
+ input: Mapping[str, Any] = field(default_factory=dict)
98
+ raw: Mapping[str, Any] = field(default_factory=dict)
99
+
100
+ def unit(self, name: str) -> BlueprintUnit | None:
101
+ return next((u for u in self.units if u.name == name), None)
102
+
103
+
104
+ def digest(doc: Any) -> str:
105
+ return hashlib.sha256(json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
106
+ .encode("utf-8")).hexdigest()
107
+
108
+
109
+ def outcome_digest(doc: Any) -> str:
110
+ """`outcome_ref.digest`: the outcome as canonical JSON without its `revisions` history, which records how
111
+ the outcome changed rather than what it says (scaffold adds the `authored` entry; SCF-B11, SCF-B13, SCF-B15, SCF-B16, SCF-B17, SCF-B18, SCF-B19, SCF-B20, SCF-B22)."""
112
+ if isinstance(doc, dict):
113
+ doc = {k: v for k, v in doc.items() if k != "revisions"}
114
+ return digest(doc)
115
+
116
+
117
+ def _f(code: str, unit: str | None, message: str) -> Finding:
118
+ return Finding(code, unit, message, "error")
119
+
120
+
121
+ def _strs(v: Any) -> bool:
122
+ return isinstance(v, list) and all(isinstance(x, str) and x for x in v)
123
+
124
+
125
+ def _sizing(unit: str, at: str, got: Any, needed: bool) -> list[Finding]:
126
+ """SCF-B9, SCF-B11: every model step and every judge states its model tier, its effort and why (SCF-B10)."""
127
+ if got is None:
128
+ return [_f("sizing-missing", unit, f"{at} is missing: state the model, the effort and why")] if needed else []
129
+ if not needed:
130
+ return [_f("sizing-invalid", unit, f"{at} is set on a unit that runs no such session")]
131
+ if not isinstance(got, dict) or set(got) != SIZING_KEYS or not all(isinstance(v, str) for v in got.values()):
132
+ return [_f("sizing-invalid", unit, f"{at} takes exactly {sorted(SIZING_KEYS)} as text")]
133
+ out = []
134
+ tier = got["model"].rsplit(":", 1)[-1]
135
+ if got["model"] == "inherit" or not tier or (":" not in got["model"] and tier not in TIERS):
136
+ out.append(_f("sizing-invalid", unit, f"{at}.model {got['model']!r} is not a tier of {sorted(TIERS)} or "
137
+ "a qualified alias"))
138
+ if got["effort"] not in EFFORTS:
139
+ out.append(_f("sizing-invalid", unit, f"{at}.effort {got['effort']!r} is not one of {list(EFFORTS)}"))
140
+ if len(got["why"].split()) < SIZING_MIN_WORDS:
141
+ out.append(_f("sizing-invalid", unit, f"{at}.why must say in a sentence why this model and effort fit"))
142
+ return out
143
+
144
+
145
+ def _shape(unit: str, kind: str, body: Any, kinds: Mapping[str, str]) -> list[Finding]:
146
+ """SCF-B9, SCF-B11: `map`, `parallel` and `wait` shapes sit on a unit of that kind and state its parameters."""
147
+ at = f"$.flow.{unit}.{kind}"
148
+ if kind in SHAPE_KIND and kinds.get(unit, SHAPE_KIND[kind]) != SHAPE_KIND[kind]:
149
+ return [_f("blueprint-invalid", unit, f"{at} belongs on a `{SHAPE_KIND[kind]}` unit; {unit} is a "
150
+ f"{kinds[unit]}")]
151
+ if kind == "map" and not (isinstance(body, dict) and set(body) <= {"over"} and isinstance(body.get("over"), str)
152
+ and body["over"].count(".") == 1):
153
+ return [_f("blueprint-invalid", unit, f"{at} takes {{over: \"<unit>.<key>\"}}, the list it runs over")]
154
+ if kind == "parallel" and not (_strs(body) and len(body) >= 2):
155
+ return [_f("blueprint-invalid", unit, f"{at} lists two or more branch units")]
156
+ if kind == "wait" and not (isinstance(body, dict) and set(body) <= {"event"}
157
+ and isinstance(body.get("event", unit), str)):
158
+ return [_f("blueprint-invalid", unit, f"{at} takes {{}} or {{event: <name>}}")]
159
+ return []
160
+
161
+
162
+ def parse(data: Any) -> Blueprint | list[Finding]:
163
+ """SCF-B9, SCF-B11: an unknown key is an error, so a misspelt field is reported, never drawn (SCF-B1)."""
164
+ out: list[Finding] = []
165
+ if not isinstance(data, dict):
166
+ return [_f("blueprint-invalid", None, "the blueprint must be a JSON object")]
167
+ for k in sorted(set(data) - TOP_KEYS):
168
+ out.append(_f("unknown_key", None, f"$.{k} is not a blueprint field"))
169
+ if data.get("schema_version") != 1:
170
+ out.append(_f("blueprint-invalid", None, f"$.schema_version {data.get('schema_version')!r} is unknown"))
171
+ name = data.get("name")
172
+ if not isinstance(name, str) or not SLUG_RE.match(name):
173
+ out.append(_f("blueprint-invalid", None, f"$.name {name!r} is not a slug"))
174
+ elif (problem := name_problem(name)) is not None:
175
+ out.append(_f("blueprint-invalid", None, f"$.name: {problem}"))
176
+ raw_units = data.get("units")
177
+ units: list[BlueprintUnit] = []
178
+ if not isinstance(raw_units, list) or not (1 <= len(raw_units) <= MAX_UNITS):
179
+ out.append(_f("blueprint-invalid", None, f"$.units must list 1 to {MAX_UNITS} units"))
180
+ raw_units = raw_units if isinstance(raw_units, list) else []
181
+ for i, u in enumerate(raw_units):
182
+ at = f"$.units[{i}]"
183
+ if not isinstance(u, dict):
184
+ out.append(_f("blueprint-invalid", None, f"{at} must be an object"))
185
+ continue
186
+ uname = u.get("name") if isinstance(u.get("name"), str) else None
187
+ for k in sorted(set(u) - UNIT_KEYS):
188
+ out.append(_f("unknown_key", uname, f"{at}.{k} is not a unit field"))
189
+ if not uname or not SLUG_RE.match(uname):
190
+ out.append(_f("blueprint-invalid", uname, f"{at}.name {u.get('name')!r} is not a slug"))
191
+ continue
192
+ kind = u.get("kind", "step")
193
+ if kind in BLUEPRINT_LATER_KINDS:
194
+ out.append(_f("not_in_release", uname, f"{at}.kind {kind!r} is built in release {BLUEPRINT_LATER_KINDS[kind]}"))
195
+ elif kind not in RELEASE_KINDS:
196
+ out.append(_f("blueprint-invalid", uname, f"{at}.kind {kind!r} is not a unit kind"))
197
+ if kind == "ask" and list(u.get("produces") or ["answers"]) != ["answers"]:
198
+ out.append(_f("blueprint-invalid", uname, f"{at}.produces: an ask unit produces `answers` only (ASK-B5, ASK-B6)"))
199
+ summary = u.get("summary", "")
200
+ if not isinstance(summary, str) or len(summary) > SUMMARY_CHARS:
201
+ out.append(_f("summary-too-long", uname, f"{at}.summary is over {SUMMARY_CHARS} characters"))
202
+ for key in ("produces", "reads", "back_targets"):
203
+ if key in u and not _strs(u[key]):
204
+ out.append(_f("blueprint-invalid", uname, f"{at}.{key} must be a list of names"))
205
+ gate = u.get("gate", {})
206
+ if not isinstance(gate, dict):
207
+ out.append(_f("blueprint-invalid", uname, f"{at}.gate must be an object"))
208
+ gate = {}
209
+ for k in sorted(set(gate) - GATE_KEYS):
210
+ out.append(_f("unknown_key", uname, f"{at}.gate.{k} is not a gate field"))
211
+ session = kind in SESSION_UNIT_KINDS
212
+ for key, needed in (("sizing", session), ("judge_sizing", session and bool(gate.get("judge")))):
213
+ out.extend(_sizing(uname, f"{at}.{key}", u.get(key), needed))
214
+ units.append(BlueprintUnit(
215
+ sizing=u.get("sizing") if isinstance(u.get("sizing"), dict) else None,
216
+ judge_sizing=u.get("judge_sizing") if isinstance(u.get("judge_sizing"), dict) else None,
217
+ name=uname, kind=str(kind), summary=str(summary or ""),
218
+ produces=(("answers",) if kind == "ask" else
219
+ tuple(u.get("produces") or ()) if _strs(u.get("produces") or []) else ()),
220
+ reads=tuple(u.get("reads") or ()) if _strs(u.get("reads") or []) else (),
221
+ check=bool(gate.get("check")), judge=bool(gate.get("judge")), signoff=bool(gate.get("signoff")),
222
+ on_fail=u.get("on_fail"), on_budget_spent=u.get("on_budget_spent"), approval=u.get("approval"),
223
+ back_targets=tuple(u.get("back_targets") or ()) if _strs(u.get("back_targets") or []) else (),
224
+ executor=u.get("executor")))
225
+ flow = data.get("flow", {})
226
+ if not isinstance(flow, dict):
227
+ out.append(_f("blueprint-invalid", None, "$.flow must map a unit to its shape"))
228
+ flow = {}
229
+ for unit, shape in flow.items():
230
+ if not isinstance(shape, dict) or len(shape) != 1 or next(iter(shape)) not in FLOW_KINDS:
231
+ out.append(_f("blueprint-invalid", unit, f"$.flow.{unit} must be one of {sorted(FLOW_KINDS)}"))
232
+ continue
233
+ kind = next(iter(shape))
234
+ out.extend(_shape(unit, kind, shape[kind], {u.name: u.kind for u in units}))
235
+ for u in units:
236
+ if u.kind in ("map", "parallel") and u.kind not in dict(flow.get(u.name) or {}):
237
+ out.append(_f("blueprint-invalid", u.name, f"$.flow.{u.name} must state the {u.kind}'s shape"))
238
+ for key in ("outcome_ref", "input"):
239
+ if key in data and not isinstance(data[key], dict):
240
+ out.append(_f("blueprint-invalid", None, f"$.{key} must be an object"))
241
+ if out:
242
+ return out
243
+ return Blueprint(name=str(name), units=tuple(units), flow=dict(flow), outcome_ref=data.get("outcome_ref"),
244
+ input=dict(data.get("input") or {}), raw=data)
245
+
246
+
247
+ def read(path: Path) -> Blueprint | list[Finding]:
248
+ try:
249
+ data = json.loads(path.read_text(encoding="utf-8"))
250
+ except (OSError, ValueError) as exc:
251
+ return [_f("blueprint-invalid", None, f"{path.name}: {type(exc).__name__}")]
252
+ return parse(data)
253
+
254
+
255
+ def branch_units(bp: Blueprint) -> set[str]:
256
+ """The units a `parallel` shape names as its branches."""
257
+ return {b for shape in bp.flow.values() if isinstance(shape, dict) for b in (shape.get("parallel") or ())}
258
+
259
+
260
+ def to_spec(bp: Blueprint) -> WorkflowSpec:
261
+ """The throwaway spec: stub prompts that name each read, stub gates, the blueprint's policies."""
262
+ units: dict[str, Any] = {}
263
+ branches = branch_units(bp)
264
+ for u in bp.units:
265
+ shape = dict(bp.flow.get(u.name) or {})
266
+ tools = ["read"] if u.name in branches else ["read", "write"] # FLX-B6: a branch reads only
267
+ gate_kw: dict[str, Any] = {"check": stub_check if u.check else None,
268
+ "judge": Judge(stance="stub", brief="stub", references=list(u.reads))
269
+ if u.judge else None,
270
+ "criteria": [Criterion(id=f"{u.name}-stub", text="stub", check_method="stub")]
271
+ if u.judge else [],
272
+ "approval": bool(u.approval) or u.signoff, "back_targets": list(u.back_targets)}
273
+ if u.on_fail:
274
+ gate_kw["on_fail"] = u.on_fail
275
+ if u.on_budget_spent:
276
+ gate_kw["on_budget_spent"] = u.on_budget_spent
277
+ gate = Gate(**gate_kw)
278
+ prompt = f"Stub for {u.name}." + "".join(f" {{{r}}}" for r in u.reads)
279
+ produces: dict[str, ProducesKind] = {k: "file" for k in u.produces}
280
+ if u.kind == "script":
281
+ units[u.name] = Script(call=stub_check, produces=produces, inputs=list(u.reads), gate=gate)
282
+ elif u.kind == "map":
283
+ src, key = str((shape.get("map") or {}).get("over") or ".").split(".", 1)
284
+ units[u.name] = Map(items_from=(src, key), step=Step(prompt=prompt + " {item}", tools=["read", "write"],
285
+ produces=produces, executor=u.executor,
286
+ summary=u.summary, gate=gate))
287
+ elif u.kind == "parallel":
288
+ units[u.name] = Parallel(branches=list(shape.get("parallel") or ()), gate=gate)
289
+ elif u.kind == "ask":
290
+ units[u.name] = Ask(questions=[Question("answer", u.summary or f"Answer for {u.name}?")],
291
+ context=list(u.reads), gate=gate)
292
+ elif u.kind == "wait":
293
+ units[u.name] = Wait(event=str((shape.get("wait") or {}).get("event") or u.name), check=stub_select,
294
+ gate=gate)
295
+ elif u.kind == "route":
296
+ units[u.name] = Route(select=stub_select, targets=list(shape.get("route") or ()), gate=gate)
297
+ elif u.kind == "switch":
298
+ sw = shape.get("switch") or {}
299
+ units[u.name] = Switch(predicate=stub_select, arms=dict(sw.get("arms") or {}),
300
+ default=str(sw.get("default") or ""), gate=gate)
301
+ else:
302
+ route = list(shape.get("route") or ())
303
+ units[u.name] = Step(prompt=prompt, tools=tools, produces=produces, executor=u.executor,
304
+ summary=u.summary, gate=gate, route=stub_select if route else None,
305
+ route_targets=route)
306
+ inp = bp.input
307
+ spec = Workflow(order=[u.name for u in bp.units], units=units,
308
+ routing=Routing(description=f"Blueprint of {bp.name}"), issue_repository="blueprint/check",
309
+ input=InputDeclaration(kind=inp.get("kind", "text"),
310
+ parameters=tuple(Param(name=str(p)) for p in inp.get("parameters") or ())))
311
+ import dataclasses
312
+
313
+ return dataclasses.replace(spec, name=bp.name, version="0.0.0")
314
+
315
+
316
+ def check(bp: Blueprint, caps: Mapping[str, Capabilities], outcome: OutcomeSpec | None = None,
317
+ outcome_doc: Any = None) -> list[Finding]:
318
+ """`blueprint check` (SCF-B9, SCF-B11): WFM validation of the throwaway spec, then the outcome cross-check."""
319
+ from tempergraph.run.outcome import check_against
320
+
321
+ spec = to_spec(bp)
322
+ found = [f for f in validate(spec, caps) if not f.code.startswith("lint-")]
323
+ out = [f if f.severity == "error" else _f(f.code, f.unit, f.message) for f in found
324
+ if f.severity == "error" or f.code in REFERENCE_WARNINGS]
325
+ if outcome is None:
326
+ return out
327
+ out += [f for f in check_against(outcome, spec) if f.severity == "error"]
328
+ if bp.outcome_ref is not None and outcome_doc is not None:
329
+ ref = bp.outcome_ref
330
+ if ref.get("digest") != outcome_digest(outcome_doc) or ref.get("revision") != outcome.revision:
331
+ out.append(_f("blueprint_outcome_mismatch", None, "outcome_ref does not match the outcome draft "
332
+ f"(revision {outcome.revision}); the approval is cleared"))
333
+ for u in bp.units:
334
+ io = outcome.intermediate.get(u.name)
335
+ crits = io.criteria if io else ()
336
+ has_check = any(c.verified_by == "check" for c in crits)
337
+ if u.check and not has_check:
338
+ out.append(_f("blueprint-check-without-criterion", u.name, f"{u.name}'s gate has a check but no "
339
+ "`check` criterion"))
340
+ if has_check and not u.check:
341
+ out.append(_f("blueprint-criterion-without-check", u.name, f"{u.name} has a `check` criterion but its "
342
+ "gate has no check"))
343
+ if u.signoff != any(c.verified_by == "person" for c in crits):
344
+ out.append(_f("blueprint-signoff-mismatch", u.name, f"{u.name}: the blueprint's sign-off and the "
345
+ "outcome's `person` criteria disagree"))
346
+ return out
@@ -0,0 +1,122 @@
1
+ """`blueprint compare <workflow>` and rung 2 of `author verify` (SCF-B18, SCF-B19, SCF-B20, SCF-B21, SCF-B22): the built spec against the approved
2
+ blueprint. Compared: names, order, artifacts and reads, checks, judges, sign-offs, failure and approval
3
+ policy, back and route targets, switch arms, map lists, parallel branches, wait events, and the outcome digest. Not compared: summaries, models,
4
+ criteria texts and prompts (SCF-AC3). Each difference is said in words, with the two fixes."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ from tempergraph.author.blueprint import Blueprint, outcome_digest
12
+ from tempergraph.contracts import TextRef, UnitSpec, WorkflowSpec
13
+ from tempergraph.model.text import TextUnreadable, load_text
14
+ from tempergraph.render.template import TemplateError, fields
15
+
16
+ FIXES = "fix the workflow to match the blueprint, or change the blueprint with the person's yes (a decision)"
17
+
18
+
19
+ @dataclass(frozen=True, kw_only=True)
20
+ class Difference:
21
+ unit: str | None
22
+ field: str
23
+ blueprint: Any
24
+ built: Any
25
+ statement: str
26
+
27
+ def to_json(self) -> dict[str, Any]:
28
+ return {"unit": self.unit, "field": self.field, "blueprint": self.blueprint, "built": self.built,
29
+ "statement": self.statement, "fixes": FIXES}
30
+
31
+
32
+ def _reads(spec: WorkflowSpec, u: UnitSpec, produced: set[str]) -> list[str]:
33
+ if u.script is not None:
34
+ return sorted(set(u.script.inputs) & produced)
35
+ if u.ask is not None:
36
+ return sorted(set(u.ask.context) & produced) # ASK-B5, ASK-B6: what the person is shown
37
+ if u.step is None or u.step.prompt == "default":
38
+ return []
39
+ try:
40
+ text = load_text(spec, u.step.prompt if isinstance(u.step.prompt, TextRef) else u.step.prompt)
41
+ names = {f.split(".")[0] for f in fields(text)}
42
+ except (TextUnreadable, TemplateError):
43
+ return []
44
+ return sorted(names & produced)
45
+
46
+
47
+ def _produces(u: UnitSpec) -> list[str]:
48
+ if u.step is not None:
49
+ return sorted(u.step.produces)
50
+ if u.script is not None:
51
+ return sorted(u.script.produces)
52
+ if u.ask is not None:
53
+ return ["answers"] # ASK-B5, ASK-B6: the unit's one artifact
54
+ return []
55
+
56
+
57
+ def compare(bp: Blueprint, spec: WorkflowSpec, outcome_doc: Any = None) -> list[Difference]:
58
+ out: list[Difference] = []
59
+
60
+ def diff(unit: str | None, fld: str, a: Any, b: Any, statement: str) -> None:
61
+ if a != b:
62
+ out.append(Difference(unit=unit, field=fld, blueprint=a, built=b, statement=statement))
63
+
64
+ names = [u.name for u in bp.units]
65
+ diff(None, "units", sorted(names), sorted(spec.order),
66
+ f"the units differ: blueprint {sorted(names)}, workflow {sorted(spec.order)}")
67
+ if sorted(names) == sorted(spec.order):
68
+ diff(None, "order", names, list(spec.order), f"the order differs: blueprint {names}, workflow {list(spec.order)}")
69
+ produced = {k for u in spec.units.values() for k in _produces(u)}
70
+ for b in bp.units:
71
+ u = spec.units.get(b.name)
72
+ if u is None:
73
+ continue
74
+ diff(b.name, "kind", b.kind, u.kind, f"{b.name} is a {u.kind}; the blueprint says {b.kind}")
75
+ diff(b.name, "produces", sorted(b.produces), _produces(u),
76
+ f"{b.name} produces {_produces(u)}; the blueprint says {sorted(b.produces)}")
77
+ diff(b.name, "reads", sorted(b.reads), _reads(spec, u, produced),
78
+ f"{b.name} reads {_reads(spec, u, produced)}; the blueprint says {sorted(b.reads)}")
79
+ g = u.gate
80
+ diff(b.name, "gate.check", b.check, g.check is not None,
81
+ f"{b.name} {'has' if g.check else 'has no'} check; the blueprint says {'one' if b.check else 'none'}")
82
+ diff(b.name, "gate.judge", b.judge, g.judge is not None,
83
+ f"{b.name} {'has' if g.judge else 'has no'} judge; the blueprint says {'one' if b.judge else 'none'}")
84
+ approval = bool(b.approval) or b.signoff
85
+ diff(b.name, "approval", approval, g.approval,
86
+ f"{b.name} now pauses for approval after a pass; the blueprint does not" if g.approval else
87
+ f"{b.name} no longer pauses for approval after a pass; the blueprint does")
88
+ diff(b.name, "on_fail", b.on_fail or "retry", g.on_fail,
89
+ f"{b.name} on_fail is {g.on_fail}; the blueprint says {b.on_fail or 'retry'}")
90
+ diff(b.name, "on_budget_spent", b.on_budget_spent or "ask", g.on_budget_spent,
91
+ f"{b.name} on_budget_spent is {g.on_budget_spent}; the blueprint says {b.on_budget_spent or 'ask'}")
92
+ diff(b.name, "back_targets", sorted(b.back_targets), sorted(g.back_targets),
93
+ f"{b.name} goes back to {sorted(g.back_targets)}; the blueprint says {sorted(b.back_targets)}")
94
+ shape = dict(bp.flow.get(b.name) or {})
95
+ if u.kind in ("step", "route") or "route" in shape:
96
+ diff(b.name, "route", sorted(shape.get("route") or ()), sorted(u.route_targets),
97
+ f"{b.name} routes to {sorted(u.route_targets)}; the blueprint says {sorted(shape.get('route') or ())}")
98
+ if u.switch is not None or "switch" in shape:
99
+ sw = shape.get("switch") or {}
100
+ built = {"arms": dict(u.switch.arms), "default": u.switch.default} if u.switch else {}
101
+ diff(b.name, "switch", {"arms": dict(sw.get("arms") or {}), "default": sw.get("default")}, built,
102
+ f"{b.name}'s switch arms or default differ from the blueprint")
103
+ if u.map is not None or "map" in shape:
104
+ built_over = ".".join(u.map.items_from) if u.map else None
105
+ diff(b.name, "map.over", (shape.get("map") or {}).get("over"), built_over,
106
+ f"{b.name} maps over {built_over}; the blueprint says {(shape.get('map') or {}).get('over')}")
107
+ if u.kind == "parallel" or "parallel" in shape:
108
+ diff(b.name, "parallel", sorted(shape.get("parallel") or ()), sorted(u.branches),
109
+ f"{b.name} joins {sorted(u.branches)}; the blueprint says {sorted(shape.get('parallel') or ())}")
110
+ if u.wait is not None or "wait" in shape:
111
+ want = str((shape.get("wait") or {}).get("event") or b.name)
112
+ diff(b.name, "wait.event", want, u.wait.event if u.wait else None,
113
+ f"{b.name} waits for {u.wait.event if u.wait else None}; the blueprint says {want}")
114
+ if spec.outcome is not None:
115
+ io = spec.outcome.intermediate.get(b.name)
116
+ signs = any(c.verified_by == "person" for c in (io.criteria if io else ()))
117
+ diff(b.name, "signoff", b.signoff, signs, f"{b.name} {'has' if signs else 'has no'} sign-off criteria; "
118
+ f"the blueprint says {'it has' if b.signoff else 'none'}")
119
+ if bp.outcome_ref is not None and outcome_doc is not None:
120
+ diff(None, "outcome_ref.digest", bp.outcome_ref.get("digest"), outcome_digest(outcome_doc),
121
+ "outcome.json changed since the blueprint was approved")
122
+ return out