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,439 @@
1
+ """Authoring sessions (AUT-B11, AUT-B12, AUT-B23, AUT-B15, AUT-B19, AUT-B24, AUT-B25): `author start|intake|check|show|list|drop|approve`.
2
+
3
+ A session is a folder `<state root>/authoring/<id>/` holding `authoring.json`, the draft `outcome.json` and
4
+ `blueprint.json`, and `sources/`. Every verb here is model-free and writes only inside that folder (AUT-AC4).
5
+ A phase approval records the digest of the part of the drafts that phase owns; an approval whose part changed
6
+ since counts as cleared, with every later one (AUT-B15, AUT-B17, AUT-B24, AUT-B12), so a session resumes from `author show` alone (AUT-AC5).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ import datetime as dt
13
+ import json
14
+ import re
15
+ import secrets
16
+ import shutil
17
+ from collections.abc import Mapping
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from tempergraph.author.blueprint import digest
23
+ from tempergraph.author.criteria_lint import lint, sufficiency
24
+ from tempergraph.author.inventory import KINDS, files, inventory
25
+ from tempergraph.docs import write_json
26
+ from tempergraph.store.layout import now_iso
27
+
28
+ PATHS = ("solution", "sources", "chat")
29
+ PHASES = {1: "intake", 2: "final outcome", 3: "work backwards", 4: "verifications", 5: "steps' work",
30
+ 6: "start and routing", 7: "approval", 8: "scaffold", 9: "verify, register, stamp"}
31
+ APPROVABLE = range(1, 8)
32
+ VERIFIER_KEYS = ("verified_by", "verifier", "source")
33
+ SLUG = re.compile(r"^[a-z][a-z0-9-]{0,62}$")
34
+
35
+
36
+ class AuthorRefused(Exception):
37
+ def __init__(self, code: str, message: str) -> None:
38
+ super().__init__(f"{code}: {message}")
39
+ self.code = code
40
+
41
+
42
+ @dataclass(kw_only=True)
43
+ class Session:
44
+ folder: Path
45
+ record: dict[str, Any]
46
+ outcome: dict[str, Any]
47
+ blueprint: dict[str, Any]
48
+
49
+ @property
50
+ def id(self) -> str:
51
+ return str(self.record.get("id"))
52
+
53
+ def save(self) -> None:
54
+ write_json(self.folder / "authoring.json", self.record, mode=0o644)
55
+
56
+
57
+ def sessions_root(state_root: Path) -> Path:
58
+ return state_root / "authoring"
59
+
60
+
61
+ def _json(path: Path) -> Any:
62
+ return json.loads(path.read_text(encoding="utf-8"))
63
+
64
+
65
+ def open_session(state_root: Path, sid: str) -> Session:
66
+ folder = sessions_root(state_root) / sid
67
+ if not re.match(r"^[a-z0-9-]+$", sid) or not (folder / "authoring.json").is_file():
68
+ raise AuthorRefused("no-session", f"no authoring session {sid!r} on this state root")
69
+ try:
70
+ return Session(folder=folder, record=_json(folder / "authoring.json"), outcome=_json(folder / "outcome.json"),
71
+ blueprint=_json(folder / "blueprint.json"))
72
+ except (OSError, ValueError) as exc:
73
+ raise AuthorRefused("session-unreadable", f"{folder}: {type(exc).__name__}") from exc
74
+
75
+
76
+ def _finished(rec: Mapping[str, Any]) -> bool:
77
+ return bool(rec.get("scaffolded") or rec.get("finished_at"))
78
+
79
+
80
+ def all_sessions(state_root: Path) -> list[Session]:
81
+ root = sessions_root(state_root)
82
+ out = []
83
+ for p in sorted(root.iterdir()) if root.is_dir() else []:
84
+ try:
85
+ out.append(open_session(state_root, p.name))
86
+ except AuthorRefused:
87
+ continue
88
+ return out
89
+
90
+
91
+ def _blank_outcome() -> dict[str, Any]:
92
+ return {"schema_version": 1, "revision": 1, "statement": "", "deliverables": [], "final": [],
93
+ "intermediate": {}, "assumptions": [], "revisions": []}
94
+
95
+
96
+ def start(state_root: Path, name: str, path: str | list[str], *, mode: str = "new",
97
+ today: dt.date | None = None) -> Session:
98
+ """AUT-B11, AUT-B12 `author start`; one open session per name (AUT-B15, AUT-B17, AUT-B24, AUT-B12)."""
99
+ if not SLUG.match(name):
100
+ raise AuthorRefused("name-invalid", f"{name!r} is not a workflow name (a lowercase slug)")
101
+ paths = [path] if isinstance(path, str) else list(path)
102
+ if mode == "new" and (not paths or any(p not in PATHS for p in paths)):
103
+ raise AuthorRefused("path-invalid", f"--from takes {', '.join(PATHS)}")
104
+ for s in all_sessions(state_root):
105
+ if s.record.get("name") == name and not _finished(s.record):
106
+ raise AuthorRefused("session-open", f"session {s.id} for {name!r} is open; finish or drop it first")
107
+ day = (today or dt.date.today()).strftime("%Y%m%d")
108
+ sid = f"{name}-{day}-{secrets.token_hex(2)}"
109
+ folder = sessions_root(state_root) / sid
110
+ (folder / "sources").mkdir(parents=True)
111
+ record = {"schema_version": 1, "id": sid, "name": name, "path": paths[0] if len(paths) == 1 else paths,
112
+ "mode": mode, "started_at": now_iso(), "sources": [], "candidates": [], "phases": [],
113
+ "decisions": [], "blueprint_digest": None, "outcome_revision": None}
114
+ s = Session(folder=folder, record=record, outcome=_blank_outcome(),
115
+ blueprint={"schema_version": 1, "name": name, "units": []})
116
+ write_json(folder / "outcome.json", s.outcome, mode=0o644)
117
+ write_json(folder / "blueprint.json", s.blueprint, mode=0o644)
118
+ s.save()
119
+ return s
120
+
121
+
122
+ def revise(state_root: Path, package: Path) -> Session:
123
+ """AUT-B12, AUT-B15, AUT-B19, AUT-B24, AUT-B25 revise: a `mode: revise` session holding copies of the package's drafts and record."""
124
+ try:
125
+ name = _json(package / "tempergraph.json")["name"]
126
+ outcome, bp = _json(package / "outcome.json"), _json(package / "blueprint.json")
127
+ prior = _json(package / "authoring.json") if (package / "authoring.json").is_file() else {}
128
+ except (OSError, ValueError, KeyError) as exc:
129
+ raise AuthorRefused("package-unreadable", f"{package}: {type(exc).__name__}") from exc
130
+ s = start(state_root, str(name), "revise", mode="revise")
131
+ s.outcome, s.blueprint = outcome, bp
132
+ keep = {k: prior[k] for k in ("sources", "candidates", "decisions", "issue_repository", "routing", "author",
133
+ "phases", "blueprint_digest", "outcome_revision") if k in prior}
134
+ # the package's approvals come along: an unchanged part stays approved, the first changed one and every
135
+ # later one are cleared, so revise asks again only from where the drafts moved (AUT-B25 step 3)
136
+ s.record.update(keep, package=str(package.resolve()), base_revision=outcome.get("revision"))
137
+ write_json(s.folder / "outcome.json", outcome, mode=0o644)
138
+ write_json(s.folder / "blueprint.json", bp, mode=0o644)
139
+ s.save()
140
+ return s
141
+
142
+
143
+ def intake(s: Session, paths: list[Path], workspace: Path | None, *, kind: str | None = None,
144
+ artifact: str | None = None, unit: str | None = None, outside: bool = False) -> list[dict[str, Any]]:
145
+ """AUT-B14, AUT-B15 `author intake`: copy each file into `sources/` and record its inventory."""
146
+ if kind is not None and kind not in KINDS:
147
+ raise AuthorRefused("kind-invalid", f"--kind takes {', '.join(KINDS)}")
148
+ default = "solution" if s.record.get("path") == "solution" else "reference"
149
+ saved_dir = (s.folder / "sources").resolve()
150
+ plan: list[tuple[Path, str, bool]] = []
151
+ for given in paths:
152
+ p = given.resolve()
153
+ if not p.exists():
154
+ raise AuthorRefused("source-missing", f"{given} does not exist")
155
+ saved = p.is_relative_to(saved_dir)
156
+ inside = workspace is not None and p.is_relative_to(workspace.resolve())
157
+ if not (saved or inside or outside):
158
+ raise AuthorRefused("path-outside-workspace", f"{given} is outside the workspace; pass --outside only "
159
+ "for a path the person named")
160
+ base = saved_dir if saved else workspace.resolve() if inside and workspace is not None else None
161
+ for f in files(p):
162
+ plan.append((f, f.relative_to(base).as_posix() if base is not None else str(f), saved))
163
+ added = []
164
+ n_src = len(s.record["sources"])
165
+ n_cand = len(s.record["candidates"])
166
+ for f, rel, saved in plan:
167
+ n_src += 1
168
+ sid = f"s{n_src}"
169
+ src = inventory(f, rel, sid, kind=kind or default, saved=saved, first_candidate=n_cand + 1,
170
+ artifact=artifact, unit=unit)
171
+ n_cand += len(src.candidates)
172
+ doc = src.to_json()
173
+ if saved:
174
+ doc["file"] = rel
175
+ else:
176
+ copy = f"{sid}-{f.name}"
177
+ shutil.copyfile(f, s.folder / "sources" / copy)
178
+ doc["file"] = copy
179
+ s.record["sources"].append(doc)
180
+ s.record["candidates"] += [c.to_json() for c in src.candidates]
181
+ added.append(doc)
182
+ s.save()
183
+ return added
184
+
185
+
186
+ # -- phases --------------------------------------------------------------------------------------------------
187
+
188
+
189
+ def _strip(c: Mapping[str, Any]) -> dict[str, Any]:
190
+ return {k: v for k, v in c.items() if k not in VERIFIER_KEYS}
191
+
192
+
193
+ def part(s: Session, phase: int) -> str:
194
+ """The digest of what `phase` owns (AUT-B12, AUT-B15, AUT-B19, AUT-B24, AUT-B25)."""
195
+ o, bp = s.outcome, s.blueprint
196
+ if phase == 1:
197
+ doc: Any = [[x.get("id"), x.get("digest"), x.get("kind")] for x in s.record.get("sources") or []]
198
+ elif phase == 2:
199
+ doc = {"statement": o.get("statement"), "deliverables": o.get("deliverables"),
200
+ "final": [_strip(c) for c in o.get("final") or []]}
201
+ elif phase == 3:
202
+ doc = {u: {**{k: v for k, v in (io or {}).items() if k != "criteria"},
203
+ "criteria": [_strip(c) for c in (io or {}).get("criteria") or []]}
204
+ for u, io in (o.get("intermediate") or {}).items()}
205
+ elif phase == 4:
206
+ crits = list(o.get("final") or []) + [c for io in (o.get("intermediate") or {}).values()
207
+ for c in (io or {}).get("criteria") or []]
208
+ doc = [[c.get("id"), *[c.get(k) for k in VERIFIER_KEYS]] for c in crits]
209
+ elif phase == 5:
210
+ doc = {k: v for k, v in bp.items() if k != "input"}
211
+ elif phase == 6:
212
+ doc = {"input": bp.get("input"), "routing": s.record.get("routing")}
213
+ else:
214
+ doc = [digest(bp), digest(o)]
215
+ return digest(doc)
216
+
217
+
218
+ def approvals(s: Session) -> tuple[list[dict[str, Any]], list[int]]:
219
+ """(effective approvals in phase order, phases cleared): the walk stops at the first missing or stale one."""
220
+ by_phase = {int(p["phase"]): p for p in s.record.get("phases") or [] if isinstance(p, dict) and "phase" in p}
221
+ good, cleared = [], []
222
+ stale = False
223
+ for ph in APPROVABLE:
224
+ p = by_phase.get(ph)
225
+ if p is None:
226
+ stale = True
227
+ continue
228
+ if stale or p.get("digest") != part(s, ph):
229
+ stale = True
230
+ cleared.append(ph)
231
+ continue
232
+ good.append(p)
233
+ return good, cleared
234
+
235
+
236
+ def next_phase(s: Session) -> int:
237
+ good = {int(p["phase"]) for p in approvals(s)[0]}
238
+ for ph in APPROVABLE:
239
+ if ph not in good:
240
+ return ph
241
+ return 9 if s.record.get("scaffolded") else 8
242
+
243
+
244
+ def _criteria(o: Mapping[str, Any]) -> list[tuple[str | None, Mapping[str, Any]]]:
245
+ out: list[tuple[str | None, Mapping[str, Any]]] = [(None, c) for c in o.get("final") or []]
246
+ out += [(u, c) for u, io in (o.get("intermediate") or {}).items() for c in (io or {}).get("criteria") or []]
247
+ return out
248
+
249
+
250
+ def check(s: Session, caps: Mapping[str, Any]) -> dict[str, Any]:
251
+ """AUT-B11, AUT-B12 `author check`: OUT-B22 on the outcome, SCF-B9, SCF-B11 on the blueprint, the criteria lint and the
252
+ sufficiency check, coverage and trust. Read-only."""
253
+ from tempergraph.author import blueprint as bpm
254
+ from tempergraph.run.outcome import parse_outcome
255
+
256
+ findings: list[dict[str, Any]] = []
257
+ parsed = parse_outcome(s.outcome) if s.outcome.get("final") else None
258
+ if isinstance(parsed, list):
259
+ findings += [{"code": f.code, "unit": f.unit, "message": f.message, "severity": f.severity,
260
+ "where": "outcome"} for f in parsed]
261
+ parsed = None
262
+ linted = lint(s.outcome)
263
+ findings += [{**f.to_json("check"), "where": "criteria"} for f in linted]
264
+ enough = sufficiency(s.outcome, linted)
265
+ bp = None
266
+ if s.blueprint.get("units"):
267
+ got = bpm.parse(s.blueprint)
268
+ if isinstance(got, list):
269
+ findings += [{"code": f.code, "unit": f.unit, "message": f.message, "severity": f.severity,
270
+ "where": "blueprint"} for f in got]
271
+ else:
272
+ bp = got
273
+ findings += [{"code": f.code, "unit": f.unit, "message": f.message, "severity": f.severity,
274
+ "where": "blueprint"} for f in bpm.check(got, caps, parsed, s.outcome)]
275
+ unclassified = [str(c.get("id")) for _, c in _criteria(s.outcome) if not c.get("verified_by")]
276
+ report: dict[str, Any] = {
277
+ "schema_version": 1, "id": s.id, "findings": findings,
278
+ "sufficiency": [f.message for f in enough], "unclassified": unclassified,
279
+ "verification": verification(s, parsed, bp),
280
+ "ok": not any(f.get("severity") == "error" for f in findings) and not enough and not unclassified}
281
+ if s.record.get("mode") == "revise":
282
+ report["changes"] = changes(s)
283
+ base = s.record.get("base_revision")
284
+ if report["changes"] and isinstance(base, int) and int(s.outcome.get("revision") or 0) <= base:
285
+ report["findings"].append({"code": "revision-not-bumped", "unit": None, "severity": "error",
286
+ "where": "outcome", "message": f"the outcome changed; its revision must "
287
+ f"be above {base}"})
288
+ report["ok"] = False
289
+ return report
290
+
291
+
292
+ def verification(s: Session, parsed: Any, bp: Any) -> dict[str, Any]:
293
+ """The verification table with each criterion's trust as it will be once scaffolded (OUT-B13, OUT-B14): a check is
294
+ `deterministic` when the session holds a good example for its unit or artifact, since scaffold writes the
295
+ must-pass and must-fail fixtures from it (SCF-B11, SCF-B13, SCF-B15, SCF-B16, SCF-B17, SCF-B18, SCF-B19, SCF-B20, SCF-B22)."""
296
+ from tempergraph.run.outcome_trust import TRUSTED
297
+
298
+ goods = [x for x in s.record.get("sources") or [] if x.get("kind") == "example_good"]
299
+ producer = {}
300
+ if bp is not None:
301
+ producer = {k: u.name for u in bp.units for k in u.produces}
302
+
303
+ def trust(c: Mapping[str, Any], unit: str | None) -> str:
304
+ by = c.get("verified_by")
305
+ if by == "person":
306
+ return "human"
307
+ if by in (None, "none"):
308
+ return "unverified"
309
+ if by == "check":
310
+ fixtures = any((x.get("unit") or producer.get(str(x.get("artifact")))) in (unit, None) for x in goods)
311
+ return "deterministic" if fixtures else "uncalibrated"
312
+ return "uncalibrated"
313
+
314
+ rows = [{"unit": u or "outcome", "id": c.get("id"), "severity": c.get("severity", "blocker"),
315
+ "verified_by": c.get("verified_by") or None, "source": c.get("source"), "trust": trust(c, u),
316
+ "serves": list(c.get("serves") or [])} for u, c in _criteria(s.outcome)]
317
+ profile: dict[str, int] = {}
318
+ for r in rows:
319
+ profile[r["trust"]] = profile.get(r["trust"], 0) + 1
320
+ units = sorted({r["unit"] for r in rows if r["unit"] != "outcome"})
321
+ coverage = []
322
+ for r in rows:
323
+ if r["unit"] != "outcome":
324
+ continue
325
+ serving = {x["unit"] for x in rows if r["id"] in x["serves"] and x["trust"] in TRUSTED}
326
+ missing = [u for u in units if u not in serving]
327
+ coverage.append({"criterion": r["id"], "trust": r["trust"],
328
+ "covered": r["trust"] in TRUSTED or (bool(units) and not missing), "missing_units": missing})
329
+ return {"rows": rows, "profile": profile, "coverage": coverage}
330
+
331
+
332
+ RANK = {"unverified": 0, "uncalibrated": 1, "deterministic": 2, "calibrated": 2, "human": 2}
333
+
334
+
335
+ def changes(s: Session) -> list[dict[str, Any]]:
336
+ """AUT-B12, AUT-B15, AUT-B19, AUT-B24, AUT-B25 revise: each criterion's change class against the package's outcome."""
337
+ pkg = Path(str(s.record.get("package") or ""))
338
+ try:
339
+ base = _json(pkg / "outcome.json")
340
+ except (OSError, ValueError):
341
+ return []
342
+ was = {str(c.get("id")): (u, c) for u, c in _criteria(base)}
343
+ now = {str(c.get("id")): (u, c) for u, c in _criteria(s.outcome)}
344
+ tmp = dataclasses.replace(s, outcome=base)
345
+ t_was = {str(r["id"]): r["trust"] for r in verification(tmp, None, None)["rows"]}
346
+ t_now = {str(r["id"]): r["trust"] for r in verification(s, None, None)["rows"]}
347
+ out = []
348
+ for cid in sorted(set(was) | set(now)):
349
+ if cid not in now:
350
+ out.append({"criterion": cid, "class": "weakening", "why": "removed"})
351
+ continue
352
+ if cid not in was:
353
+ out.append({"criterion": cid, "class": "strengthening", "why": "added"})
354
+ continue
355
+ a, b = was[cid][1], now[cid][1]
356
+ sev_a, sev_b = a.get("severity", "blocker"), b.get("severity", "blocker")
357
+ if sev_a == "blocker" and sev_b != "blocker":
358
+ out.append({"criterion": cid, "class": "weakening", "why": "a blocker made a warning"})
359
+ elif RANK[t_now[cid]] < RANK[t_was[cid]]:
360
+ out.append({"criterion": cid, "class": "weakening", "why": f"trust {t_was[cid]} to {t_now[cid]}"})
361
+ elif sev_a != "blocker" and sev_b == "blocker":
362
+ out.append({"criterion": cid, "class": "strengthening", "why": "a warning made a blocker"})
363
+ elif RANK[t_now[cid]] > RANK[t_was[cid]]:
364
+ out.append({"criterion": cid, "class": "strengthening", "why": f"trust {t_was[cid]} to {t_now[cid]}"})
365
+ elif _strip(a) != _strip(b) or a.get("verifier") != b.get("verifier"):
366
+ out.append({"criterion": cid, "class": "neutral", "why": "text, scale or verifier changed"})
367
+ return out
368
+
369
+
370
+ def _phase_problems(s: Session, phase: int, caps: Mapping[str, Any]) -> list[str]:
371
+ rep = check(s, caps)
372
+ errors = [f for f in rep["findings"] if f.get("severity") == "error"]
373
+ if phase == 1:
374
+ return [] if s.record.get("sources") or s.record.get("path") == "chat" else ["no source was taken in"]
375
+ if phase == 2:
376
+ mine = [f for f in errors if f.get("where") == "criteria" and f.get("unit") is None]
377
+ return [f"{f['code']}: {f['message']}" for f in mine] + rep["sufficiency"]
378
+ if phase == 3:
379
+ mine = [f for f in errors if f.get("where") in ("criteria", "outcome") and f.get("unit") is not None]
380
+ if not s.outcome.get("intermediate"):
381
+ return ["no intermediate outcome yet"]
382
+ return [f"{f['code']}: {f['message']}" for f in mine]
383
+ if phase == 4:
384
+ return [f"{c} has no verifier class" for c in rep["unclassified"]] + [
385
+ f"{f['code']}: {f['message']}" for f in errors if f.get("where") == "outcome"]
386
+ if phase in (5, 6):
387
+ if not s.blueprint.get("units"):
388
+ return ["the blueprint has no unit yet"]
389
+ return [f"{f['code']}: {f['message']}" for f in errors if f.get("where") == "blueprint"]
390
+ return [f"{f['code']}: {f['message']}" for f in errors] + rep["sufficiency"] + [
391
+ f"{c} has no verifier class" for c in rep["unclassified"]]
392
+
393
+
394
+ def approve(s: Session, phase: int, caller: Mapping[str, Any], caps: Mapping[str, Any]) -> dict[str, Any]:
395
+ """`author approve <id> <phase>`: the person's yes on a phase's drafts (AUT-B12, AUT-B15, AUT-B19, AUT-B24, AUT-B25)."""
396
+ if phase not in APPROVABLE:
397
+ raise AuthorRefused("phase-invalid", "phases 1 to 7 are approved; 8 and 9 are `scaffold` and `author verify`")
398
+ good = {int(p["phase"]) for p in approvals(s)[0]}
399
+ missing = [p for p in range(1, phase) if p not in good]
400
+ if missing:
401
+ raise AuthorRefused("phase-order", f"phase {phase} needs phases {missing} approved first")
402
+ problems = _phase_problems(s, phase, caps)
403
+ if problems:
404
+ raise AuthorRefused("phase-not-ready", "; ".join(problems))
405
+ keep = [p for p in s.record.get("phases") or [] if int(p.get("phase", 0)) < phase]
406
+ entry = {"phase": phase, "approved_at": now_iso(), "by": dict(caller), "digest": part(s, phase)}
407
+ s.record["phases"] = keep + [entry]
408
+ if phase == 7:
409
+ s.record["blueprint_digest"] = digest(s.blueprint)
410
+ s.record["outcome_revision"] = s.outcome.get("revision")
411
+ s.save()
412
+ return entry
413
+
414
+
415
+ def show(s: Session, caps: Mapping[str, Any]) -> dict[str, Any]:
416
+ """AUT-B11, AUT-B12 `author show`: everything a new conversation needs to resume (AUT-AC5)."""
417
+ good, cleared = approvals(s)
418
+ nxt = next_phase(s)
419
+ rep = check(s, caps)
420
+ return {"schema_version": 1, "id": s.id, "name": s.record.get("name"), "mode": s.record.get("mode"),
421
+ "path": s.record.get("path"), "folder": str(s.folder), "next_phase": nxt, "next": PHASES[nxt],
422
+ "approved": [p["phase"] for p in good], "cleared": cleared, "sources": s.record.get("sources"),
423
+ "candidates": s.record.get("candidates"), "outcome": s.outcome, "blueprint": s.blueprint,
424
+ "verification": rep["verification"], "findings": rep["findings"], "sufficiency": rep["sufficiency"],
425
+ "decisions": s.record.get("decisions"), "assumptions": s.outcome.get("assumptions") or [],
426
+ **({"changes": rep["changes"]} if "changes" in rep else {})}
427
+
428
+
429
+ def listing(state_root: Path) -> list[dict[str, Any]]:
430
+ return [{"id": s.id, "name": s.record.get("name"), "mode": s.record.get("mode"), "next_phase": next_phase(s),
431
+ "finished": _finished(s.record), "started_at": s.record.get("started_at")}
432
+ for s in all_sessions(state_root)]
433
+
434
+
435
+ def drop(s: Session) -> None:
436
+ root = s.folder.parent.resolve()
437
+ if s.folder.resolve().parent != root or root.name != "authoring":
438
+ raise AuthorRefused("drop-refused", f"{s.folder} is not a session folder")
439
+ shutil.rmtree(s.folder)