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,178 @@
1
+ """The per-thread result cache of model-free scripts (SCR-B9, SCR-B3, ADR `cache-only-model-free-script-results-per-thread`).
2
+
3
+ A script with `cache: thread` is keyed by a digest of what decides its result; a hit restores the recorded
4
+ `produces` files and result from `<thread folder>/cache/` and runs nothing. Only a run that finished and
5
+ succeeded is recorded. A folder or an entry that cannot be read raises :class:`CacheError`, which the caller
6
+ logs and treats as a miss.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import shutil
16
+ from collections.abc import Collection, Mapping
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ from tempergraph import git as gitmod
21
+ from tempergraph.store import manifest
22
+
23
+ SCHEMA = 1
24
+ ABSENT = "absent"
25
+ REFUSED = "refused"
26
+ WORKSPACE = "workspace"
27
+
28
+
29
+ class CacheError(Exception):
30
+ """The cache folder or an entry in it cannot be read or written: a logged miss (SCR-B9)."""
31
+
32
+
33
+ @dataclass(frozen=True, kw_only=True)
34
+ class Result:
35
+ """What a succeeded script left: its exit code, its artifacts and the kind of each artifact's key."""
36
+
37
+ exit_code: int | None = None
38
+ artifacts: Mapping[str, str] = field(default_factory=dict)
39
+ kinds: Mapping[str, str] = field(default_factory=dict)
40
+
41
+
42
+ def key(*, argv: tuple[str, ...], reference: str | None, workflow: str, arguments: tuple[str, ...],
43
+ inputs: Mapping[str, str]) -> str:
44
+ """The digest of the resolved argv or callable reference, the workflow's content digest, the rendered
45
+ arguments and the content digest of each declared input."""
46
+ doc = {"argv": list(argv), "reference": reference, "workflow": workflow, "arguments": list(arguments),
47
+ "inputs": {k: inputs[k] for k in sorted(inputs)}}
48
+ return hashlib.sha256(json.dumps(doc, sort_keys=True).encode("utf-8")).hexdigest()
49
+
50
+
51
+ def _file_digest(path: Path) -> str:
52
+ return manifest.file_hash(path) or ABSENT
53
+
54
+
55
+ def _under(path: Path, root: Path) -> bool:
56
+ with contextlib.suppress(OSError, ValueError):
57
+ path.resolve().relative_to(root.resolve())
58
+ return True
59
+ return False
60
+
61
+
62
+ def tree_hash(workdir: Path, state_root: Path, exclude: Collection[str] = ()) -> str:
63
+ """The hash of the tracked and untracked files of the workspace outside the state root (and outside
64
+ `exclude`, workspace-relative paths such as the script's own earlier outputs)."""
65
+ if gitmod.toplevel(workdir) is None:
66
+ return "manifest:" + manifest.status(workdir)
67
+ try:
68
+ listed = gitmod.git_bytes(["ls-files", "-z", "--cached", "--others", "--exclude-standard"], workdir)
69
+ except gitmod.GitError:
70
+ return "manifest:" + manifest.status(workdir)
71
+ skip = set(exclude)
72
+ h = hashlib.sha256()
73
+ for rel in sorted(p for p in listed.decode("utf-8", "replace").split("\0") if p):
74
+ path = workdir / rel
75
+ if rel in skip or ".tempergraph/" in rel or _under(path, state_root):
76
+ continue
77
+ h.update(f"{rel}\0{_file_digest(path)}\n".encode())
78
+ return h.hexdigest()
79
+
80
+
81
+ def _dir_hash(root: Path) -> str:
82
+ h = hashlib.sha256()
83
+ for p in sorted(root.rglob("*")):
84
+ if p.is_file():
85
+ h.update(f"{p.relative_to(root).as_posix()}\0{_file_digest(p)}\n".encode())
86
+ return h.hexdigest()
87
+
88
+
89
+ def safe_relative(value: str) -> Path | None:
90
+ """A workspace-relative path with no `..` and no root, or nothing."""
91
+ p = Path(value)
92
+ return None if not value or p.is_absolute() or ".." in p.parts else p
93
+
94
+
95
+ def input_digest(name: str, workdir: Path, state_root: Path, artifacts: Mapping[str, str],
96
+ exclude: Collection[str] = ()) -> str:
97
+ """The content digest of one declared input: `workspace` is the tree hash; an artifact or value key is the
98
+ content of the file it names (else the text); anything else is a path of the workspace."""
99
+ if name == WORKSPACE:
100
+ return "tree:" + tree_hash(workdir, state_root, exclude)
101
+ if name in artifacts:
102
+ value = str(artifacts[name])
103
+ rel = safe_relative(value)
104
+ if rel is not None and (workdir / rel).is_file():
105
+ return "file:" + _file_digest(workdir / rel)
106
+ return "value:" + hashlib.sha256(value.encode("utf-8")).hexdigest()
107
+ rel = safe_relative(name)
108
+ if rel is None:
109
+ return REFUSED
110
+ path = workdir / rel
111
+ if path.is_dir():
112
+ return "dir:" + _dir_hash(path)
113
+ return "file:" + _file_digest(path)
114
+
115
+
116
+ def _entry(folder: Path, key_: str) -> Path:
117
+ return folder / f"{key_}.json"
118
+
119
+
120
+ def _blobs(folder: Path, key_: str) -> Path:
121
+ return folder / f"{key_}.files"
122
+
123
+
124
+ def store(folder: Path, key_: str, result: Result, workdir: Path) -> None:
125
+ """Record a succeeded run: its result and a copy of each `file` artifact it left in the workspace."""
126
+ files: dict[str, dict[str, str]] = {}
127
+ try:
128
+ folder.mkdir(parents=True, exist_ok=True, mode=0o700)
129
+ for name, value in result.artifacts.items():
130
+ rel = safe_relative(str(value))
131
+ if result.kinds.get(name) != "file" or rel is None or not (workdir / rel).is_file():
132
+ continue
133
+ blob = hashlib.sha256(rel.as_posix().encode("utf-8")).hexdigest()[:24]
134
+ dest = _blobs(folder, key_) / blob
135
+ dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
136
+ shutil.copyfile(workdir / rel, dest)
137
+ files[name] = {"path": rel.as_posix(), "blob": blob}
138
+ doc = {"schema": SCHEMA, "exit_code": result.exit_code, "artifacts": dict(result.artifacts),
139
+ "kinds": dict(result.kinds), "files": files}
140
+ tmp = folder / f"{key_}.tmp"
141
+ tmp.write_text(json.dumps(doc, sort_keys=True), encoding="utf-8")
142
+ os.replace(tmp, _entry(folder, key_))
143
+ except OSError as exc:
144
+ raise CacheError(type(exc).__name__) from None
145
+
146
+
147
+ def lookup(folder: Path, key_: str, workdir: Path) -> Result | None:
148
+ """The recorded result of a hit, with its files put back in the workspace; nothing on a miss; a
149
+ :class:`CacheError` when the folder or the entry cannot be read."""
150
+ if folder.exists() and not folder.is_dir():
151
+ raise CacheError("NotADirectoryError")
152
+ try:
153
+ raw = _entry(folder, key_).read_text(encoding="utf-8")
154
+ except FileNotFoundError:
155
+ return None
156
+ except OSError as exc:
157
+ raise CacheError(type(exc).__name__) from None
158
+ try:
159
+ doc = json.loads(raw)
160
+ if not isinstance(doc, dict) or doc.get("schema") != SCHEMA:
161
+ raise ValueError("schema")
162
+ files = {str(k): dict(v) for k, v in dict(doc.get("files") or {}).items()}
163
+ arts = {str(k): str(v) for k, v in dict(doc.get("artifacts") or {}).items()}
164
+ kinds = {str(k): str(v) for k, v in dict(doc.get("kinds") or {}).items()}
165
+ code = doc.get("exit_code")
166
+ restores: list[tuple[Path, Path]] = []
167
+ for info in files.values():
168
+ rel = safe_relative(str(info["path"]))
169
+ blob = _blobs(folder, key_) / str(info["blob"])
170
+ if rel is None or not blob.is_file():
171
+ raise ValueError("entry")
172
+ restores.append((blob, workdir / rel))
173
+ for blob, dest in restores:
174
+ dest.parent.mkdir(parents=True, exist_ok=True)
175
+ shutil.copyfile(blob, dest)
176
+ except (ValueError, KeyError, TypeError, OSError) as exc:
177
+ raise CacheError(type(exc).__name__) from None
178
+ return Result(exit_code=code if isinstance(code, int) else None, artifacts=arts, kinds=kinds)
@@ -0,0 +1,105 @@
1
+ """The check preview a step may run from inside its attempt (CHK-B17).
2
+
3
+ A step that declares `self_check` gets a random ticket for one attempt. The ticket file holds the check
4
+ worker's input document, so the `self-check` verb needs no checkpoint and no catalog: it refreshes the git
5
+ facts, runs the unit's check in the check worker with `preview = true`, prints what the gate's check would
6
+ find and notes the call on the ticket. It writes no verdict, fact, artifact or state and spends no budget;
7
+ the engine writes one `self_check` record a call when the attempt ends, and removes the ticket.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import dataclasses
14
+ import json
15
+ import re
16
+ import secrets
17
+ import time
18
+ from pathlib import Path
19
+ from typing import IO, Any
20
+
21
+ from tempergraph.contracts import GateSpec
22
+ from tempergraph.docs import write_json
23
+ from tempergraph.run import checks as checkmod
24
+ from tempergraph.run.check_worker import context_doc, run_doc
25
+
26
+ TICKET_RE = re.compile(r"^[0-9a-f]{32}$")
27
+ DEFAULT_LIMIT = 3
28
+ EVIDENCE_CHARS = 2_000
29
+ COMMAND = "tempergraph self-check"
30
+
31
+
32
+ def ticket_path(state_root: Path, ticket: str) -> Path:
33
+ return state_root / "tickets" / f"{ticket}.json"
34
+
35
+
36
+ def command(ticket: str) -> str:
37
+ return f"{COMMAND} {ticket}"
38
+
39
+
40
+ def issue(state_root: Path, gate: GateSpec, ctx: checkmod.CheckContext, *, thread: str, limit: int,
41
+ base_branch: str = "") -> str:
42
+ """A ticket for one attempt of one unit; `close` ends it. It holds the run's base branch so that a preview reads
43
+ that branch's head again when it runs (CHK-B22)."""
44
+ ticket = secrets.token_hex(16)
45
+ path = ticket_path(state_root, ticket)
46
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
47
+ write_json(path, {"schema_version": 1, "thread": thread, "unit": ctx.unit, "item": ctx.item,
48
+ "attempt": ctx.attempt, "limit": int(limit), "calls": [], "base_branch": base_branch,
49
+ "doc": context_doc(gate, dataclasses.replace(ctx, preview=True))})
50
+ return ticket
51
+
52
+
53
+ def close(state_root: Path, ticket: str) -> list[dict[str, Any]]:
54
+ """End the ticket and return its calls, for the engine's `self_check` records."""
55
+ path = ticket_path(state_root, ticket)
56
+ try:
57
+ calls = list(json.loads(path.read_text(encoding="utf-8")).get("calls") or [])
58
+ except (OSError, ValueError, AttributeError):
59
+ calls = []
60
+ with contextlib.suppress(OSError):
61
+ path.unlink()
62
+ return calls
63
+
64
+
65
+ def run(state_root: Path, ticket: str, out: IO[str]) -> int:
66
+ """The `self-check <ticket>` verb. Exit 2 for an unknown or expired ticket and at the limit, else 0."""
67
+ path = ticket_path(state_root, ticket) if TICKET_RE.match(ticket) else None
68
+ try:
69
+ t = json.loads(path.read_text(encoding="utf-8")) if path is not None else None
70
+ except (OSError, ValueError):
71
+ t = None
72
+ if not isinstance(t, dict) or not isinstance(t.get("doc"), dict):
73
+ out.write("self-check: unknown or expired ticket; nothing was run\n")
74
+ return 2
75
+ calls = list(t.get("calls") or [])
76
+ if len(calls) >= int(t.get("limit") or DEFAULT_LIMIT):
77
+ out.write(f"self-check: the limit of {t.get('limit')} previews for this attempt is reached; "
78
+ "the gate's own check runs when you end\n")
79
+ return 2
80
+ doc = t["doc"]
81
+ c = doc["context"]
82
+ workdir = Path(c["workdir"])
83
+ g = checkmod.git_facts(workdir, str((c.get("git") or {}).get("base") or ""), str(t.get("base_branch") or ""))
84
+ c["git"] = None if g is None else {
85
+ "branch": g.branch, "base": g.base, "head": g.head, "base_head": g.base_head, "own_base": g.own_base,
86
+ "clean": g.clean, "pushed": g.pushed, "changed_paths": list(g.changed_paths),
87
+ "commits_since_base": list(g.commits_since_base)}
88
+ if g is not None:
89
+ c["changed_paths"] = list(g.changed_paths)
90
+ c["preview"] = True
91
+ t0 = time.monotonic()
92
+ res, _ = run_doc(doc, workdir, int(doc.get("check_timeout_s") or 1800), f"preview-{c['unit']}-{c.get('attempt')}")
93
+ counts = {s: sum(1 for f in res.findings if f.status == s) for s in ("pass", "fail", "maybe")}
94
+ calls.append({"result": res.result, "findings": counts, "duration_s": round(time.monotonic() - t0, 3),
95
+ "environmental": bool(res.environmental)})
96
+ if path is not None and path.exists(): # an attempt that ended meanwhile keeps its ticket closed
97
+ write_json(path, {**t, "calls": calls})
98
+ out.write(f"self-check {len(calls)} of {t.get('limit')}: {res.result}\n")
99
+ for f in res.findings:
100
+ parts = [f.status, f.criterion or "-", f.place or "-", f.message or "-"]
101
+ out.write(" " + " | ".join(parts) + (f" | fix: {f.fix}" if f.fix else "") + "\n")
102
+ if res.evidence:
103
+ out.write(res.evidence[:EVIDENCE_CHARS].rstrip() + "\n")
104
+ out.write("This is a preview. The gate's own check runs after you end.\n")
105
+ return 0
@@ -0,0 +1,72 @@
1
+ """The calls a step session made, read from its activity journal for the attempt's check (CHK-B24, CHK-B25).
2
+
3
+ The record is `None` wherever it cannot be trusted: no journal, a journal with no call, a session whose
4
+ executor reports tool names only (no capability on any call), and a journal that dropped a tool line. A
5
+ check reads `None` as "no session record", never as an empty list.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ def _session_start(rows: list[dict[str, Any]]) -> int:
16
+ """The row where the last session started: the first of the `session_started` rows that end the journal's
17
+ starts with one `session_id` (CHK-B24).
18
+
19
+ A session that ended its turn and is woken reports a start with the id it has, so that row continues the
20
+ session; a new process after an infra try has a new id. A last start with no id is a start of its own.
21
+ """
22
+ starts = [i for i, r in enumerate(rows) if r.get("ev") == "session_started"]
23
+ if not starts:
24
+ return 0
25
+ last = rows[starts[-1]].get("session_id")
26
+ first = starts[-1]
27
+ if isinstance(last, str) and last:
28
+ for i in reversed(starts):
29
+ if rows[i].get("session_id") != last:
30
+ break
31
+ first = i
32
+ return first
33
+
34
+
35
+ def read_session(session_dir: Path) -> list[dict[str, Any]] | None:
36
+ """The calls since the session last started, in call order: `{name, capability, target, ok}` each (CHK-B24).
37
+
38
+ A `session_started` row with the session id of the start before it is the same session woken, not a start.
39
+
40
+ `target` is the journal line's `input_summary` (null with `observe.tool_inputs = off`), `ok` is true only for
41
+ a call that finished with `ok` true. Returns `None` for a missing or unreadable journal, no call, no call
42
+ with a capability, a `truncated` line since that start that names a dropped tool line, and any line that
43
+ cannot be read (CHK-B25).
44
+ """
45
+ try:
46
+ text = (session_dir / "activity.jsonl").read_text(encoding="utf-8")
47
+ rows = [json.loads(line) for line in text.splitlines() if line.strip()]
48
+ if not all(isinstance(r, dict) for r in rows):
49
+ return None
50
+ rows = rows[_session_start(rows):]
51
+ calls: list[dict[str, Any]] = []
52
+ by_id: dict[str, dict[str, Any]] = {}
53
+ for r in rows:
54
+ ev = r.get("ev")
55
+ if ev == "truncated":
56
+ dropped = r.get("dropped") or {}
57
+ if any(k in dropped for k in ("tool_started", "tool_finished")):
58
+ return None
59
+ elif ev == "tool_started":
60
+ call = {"name": r.get("name"), "capability": r.get("capability"),
61
+ "target": r.get("input_summary"), "ok": False}
62
+ calls.append(call)
63
+ by_id[str(r.get("call_id", ""))] = call
64
+ elif ev == "tool_finished":
65
+ started = by_id.get(str(r.get("call_id", "")))
66
+ if started is not None:
67
+ started["ok"] = r.get("ok") is True
68
+ except Exception: # noqa: BLE001 - a record that cannot be read is no record
69
+ return None
70
+ if not calls or not any(c["capability"] for c in calls):
71
+ return None
72
+ return calls
@@ -0,0 +1,278 @@
1
+ """A sub-workflow's child run as one unit of its parent (SWF-B1 to SWF-B5, SWF-B8, SWF-B10; ADR `a-sub-workflow-runs-inside-its-parents-thread-workspace-and-cap`).
2
+
3
+ The unit's step node invokes the child's own graph with the node's config, so the child is a subgraph under the
4
+ parent's checkpointer, thread, workspace, lock and run cost cap. It has its own compiled graph, its own nodes and its own
5
+ run state (`compiler.state`), because every channel is keyed by one workflow's unit names and a child's `work` must not
6
+ meet the parent's `work`. Its context shares the parent's registry, state root, drain check and cost cap and starts from the
7
+ parent's cost, so one cap holds; its log writer adds `child: <unit>` to every record and its session keys read
8
+ `<unit>/<child unit>.<attempt>.<kind>`. The unit hands back only what `produces` exposes, the cost the child added and
9
+ the child's outcome record; the child's finalizer never runs from here and its outcome gate is never skipped.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import dataclasses
15
+ from collections.abc import Mapping
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph import settings as rst
20
+ from tempergraph.compiler.graph import CompiledWorkflow, compile_workflow
21
+ from tempergraph.compiler.state import RunState, child_input, flat
22
+ from tempergraph.contracts import RunOptions, UnitSpec, WorkflowSpec
23
+ from tempergraph.git import fingerprint
24
+ from tempergraph.improve import calibration
25
+ from tempergraph.model import subworkflow
26
+ from tempergraph.run import outcome_record
27
+ from tempergraph.run.log import ChildLog, CostTotals, RunLog, last_record
28
+ from tempergraph.run.nodes import EngineNodes, RunContext
29
+ from tempergraph.run.outcome import with_outcome
30
+
31
+
32
+ class ChildUpstream(Exception):
33
+ """SWF-B5: the child's judge or step named a key the parent mapped into `inputs` as the defect. The child ends
34
+ `upstream`; the parent's gate for the unit decides where the run goes."""
35
+
36
+ def __init__(self, key: str, reason: str, cost: Mapping[str, Any] | None = None) -> None:
37
+ super().__init__(f"upstream defect in {key}: {reason}")
38
+ self.key = key
39
+ self.reason = reason
40
+ self.cost = dict(cost or {})
41
+
42
+
43
+ class ChildNodes(EngineNodes):
44
+ """The node bodies of one child: the parent's, with the three differences a child has."""
45
+
46
+ def __init__(self, ctx: RunContext, unit: str, declared: UnitSpec) -> None:
47
+ super().__init__(ctx)
48
+ self.unit = unit # the sub-workflow unit of the parent
49
+ self.declared = declared
50
+
51
+ def finalizer(self, state: RunState) -> dict[str, Any]:
52
+ """SWF-B10: a child's finalizer never runs from its parent, whose own finalizer can call the same code."""
53
+ return {}
54
+
55
+ def judge(self, unit: str, state: RunState) -> dict[str, Any]:
56
+ w = super().judge(unit, state)
57
+ self._upstream(unit, state, w)
58
+ return w
59
+
60
+ def _upstream(self, unit: str, state: RunState, w: Mapping[str, Any]) -> None:
61
+ """SWF-B5: a defect in a key the parent mapped into `inputs` ends the child `upstream`."""
62
+ cost = (w.get("run") or {}).get("cost") or (state.get("run") or {}).get("cost")
63
+ for b in (((w.get("judgements") or {}).get(unit) or {}).get("blockers")) or []:
64
+ key = b.get("defect_in")
65
+ if key and subworkflow.is_input_name(self.declared, str(key)):
66
+ raise ChildUpstream(str(key), str(b.get("problem") or b.get("evidence") or "an upstream defect"), cost)
67
+ blocked = str(((state.get("attempts") or {}).get(unit) or {}).get("blocked") or "")
68
+ for param, src in ((self.declared.subworkflow.inputs if self.declared.subworkflow else {}).items()):
69
+ for name in (param, src):
70
+ head = f"upstream claim on {name}:"
71
+ if blocked.startswith(head):
72
+ raise ChildUpstream(name, blocked[len(head):].strip(), cost)
73
+
74
+ def gate(self, unit: str, state: RunState) -> dict[str, Any]:
75
+ """SWF-B2: a child's pause carries `unit` as `<unit>/<child unit>`."""
76
+ w = super().gate(unit, state)
77
+ p = (w.get("pause") or {}).get(unit)
78
+ if p:
79
+ w["pause"][unit] = {**p, "unit": f"{self.ctx.child}/{unit}"}
80
+ return w
81
+
82
+
83
+ @dataclasses.dataclass
84
+ class Built:
85
+ """One child ready to run or to read: its spec as this run executes it, its graph and its nodes."""
86
+
87
+ name: str # the child's name in the registry
88
+ path: str # the unit's path: `<unit>`, or `<unit>/<unit>` for a child of a child
89
+ spec: WorkflowSpec # with the outcome gate, the settings applied and the parent's cap
90
+ graph: CompiledWorkflow
91
+ nodes: ChildNodes
92
+ version: str
93
+ options: Mapping[str, Any] # the operator layers as this child reads them
94
+
95
+
96
+ def root_log(log: Any) -> RunLog:
97
+ return log.parent if isinstance(log, ChildLog) else log
98
+
99
+
100
+ def child_options(unit: str, options: Mapping[str, Any]) -> dict[str, Any]:
101
+ """SWF-B8: the operator layers of a run as the child under `unit` reads them: a flag `<unit>/<child unit>.<key>` is
102
+ `<child unit>.<key>` there, and no other key reaches it. The child's own declared defaults stay under every layer."""
103
+ prefix = f"{unit}/"
104
+ return {"settings": {layer: {k[len(prefix):]: cell for k, cell in cells.items() if k.startswith(prefix)}
105
+ for layer, cells in (options.get("settings") or {}).items()},
106
+ "profiles": list(options.get("profiles") or ())}
107
+
108
+
109
+ def applied(parent: WorkflowSpec, child: subworkflow.Child, options: Mapping[str, Any]) -> tuple[WorkflowSpec, Any]:
110
+ """The child's spec as the run executes it: its declared defaults and the layers `options` carries applied, the
111
+ parent's cap, name and workspace (the child's own `run.workspace` is ignored), and its outcome gate."""
112
+ res = rst.resolve(child.spec, RunOptions(settings=options.get("settings") or {},
113
+ profiles=tuple(options.get("profiles") or ())))
114
+ spec = dataclasses.replace(
115
+ rst.effective_spec(child.spec, res), name=parent.name, run_cost_cap_usd=parent.run_cost_cap_usd,
116
+ daily_cap_usd=parent.daily_cap_usd, workspace=parent.workspace, worktree=parent.worktree)
117
+ return with_outcome(spec), res
118
+
119
+
120
+ def locate(spec: WorkflowSpec, path: str, options: Mapping[str, Any]) -> tuple[WorkflowSpec, str] | None:
121
+ """The child spec and unit a pause path `<unit>/<child unit>` (or deeper) names, as the run executes them; None when
122
+ a child on the path is not registered or the path names none."""
123
+ head, _, rest = path.partition("/")
124
+ held = spec.units.get(head)
125
+ if held is None or held.subworkflow is None or not rest:
126
+ return None
127
+ child = subworkflow.read_child(held.subworkflow.workflow)
128
+ if not isinstance(child, subworkflow.Child):
129
+ return None
130
+ mine = child_options(head, options)
131
+ cspec, _ = applied(spec, child, mine)
132
+ return locate(cspec, rest, mine) if "/" in rest else (cspec, rest)
133
+
134
+
135
+ def build(ctx: RunContext, unit: str, declared: UnitSpec, child: subworkflow.Child, options: Mapping[str, Any]
136
+ ) -> Built:
137
+ """SWF-B8: the child's spec with its declared defaults under every layer of the parent's run (a flag reaches a
138
+ child unit as `<unit>/<child unit>.<key>`), the parent's cap, name and workspace; its nodes; its graph."""
139
+ path = f"{ctx.child}/{unit}" if ctx.child else unit
140
+ mine = child_options(unit, options)
141
+ cspec, res = applied(ctx.spec, child, mine)
142
+ # SWF-B9: the child's judges keep the child's own bindings and cases: a judge map of its own, and a judge state
143
+ # read from its own calibration cases and its own gates' judgements, never the parent's (nor the parent's seam)
144
+ cctx = dataclasses.replace(ctx, spec=cspec, log=ChildLog(root_log(ctx.log), path), judges={},
145
+ settings=rst.workflow_settings(res), child=path, parent_thread=ctx.thread,
146
+ judge_state=calibration.state_name_for(cspec, ctx.state_root, child=path))
147
+ nodes = ChildNodes(cctx, unit, declared)
148
+ return Built(name=child.name, path=path, spec=cspec, graph=compile_workflow(cspec, nodes, None), nodes=nodes,
149
+ version=child.version, options=mine)
150
+
151
+
152
+ def _earlier(state: Mapping[str, Any]) -> dict[str, dict[str, Any]]:
153
+ out: dict[str, dict[str, Any]] = {}
154
+ for chan in ("artifacts", "values"):
155
+ for owner, vals in (state.get(chan) or {}).items():
156
+ if isinstance(vals, dict):
157
+ out.setdefault(owner, {}).update(vals)
158
+ return out
159
+
160
+
161
+ def _failing(orec: Mapping[str, Any] | None, stopped: Mapping[str, Any] | None, name: str) -> list[dict[str, str]]:
162
+ """SWF-B5: a child that stopped, or ended `unmet` or `needs_person`, fails the unit's gate with the child's
163
+ failing final criteria as blockers."""
164
+ bad = [c for c in (orec or {}).get("criteria", []) if c.get("severity", "blocker") == "blocker"
165
+ and c["status"] not in outcome_record.PASSED]
166
+ if (orec or {}).get("verdict") in ("unmet", "needs_person") and bad:
167
+ return [{"criterion": str(c["id"]), "problem": f"the child {name!r}: its final criterion {c['id']} is "
168
+ f"{c['status']}"} for c in bad]
169
+ if stopped:
170
+ return [{"criterion": "child", "problem": f"the child {name!r} stopped at {stopped.get('unit')} "
171
+ f"({stopped.get('reason')})"}]
172
+ return []
173
+
174
+
175
+ def run_child(parent: EngineNodes, unit: str, state: Mapping[str, Any], config: Any) -> dict[str, Any]:
176
+ """The step node of a sub-workflow unit (SWF-B1): run the child to its end, or until it pauses, and hand back
177
+ what the unit exposes."""
178
+ ctx = parent.ctx
179
+ declared = ctx.spec.units[unit]
180
+ rec = declared.subworkflow
181
+ assert rec is not None
182
+ prev = (state.get("attempts") or {}).get(unit) or {}
183
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
184
+ attempt = int(prev.get("attempt", 0)) + 1
185
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
186
+ run: dict[str, Any] = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
187
+ found = subworkflow.read_child(rec.workflow)
188
+ record: dict[str, Any] = {"attempt": attempt, "visit": visit, "ok": True, "text": "", "issues": [], "tools": [],
189
+ "session_id": None, "escalate": None, "infra_spent": False, "check": None,
190
+ "subworkflow": True, "upstream_child": None, "child_failed": None, "error_kind": None}
191
+ # (a key set to None is deleted by the attempts reducer, so nothing of an earlier attempt's end lingers)
192
+ if not isinstance(found, subworkflow.Child): # removed while this run was going: a person decides
193
+ record.update(ok=False, escalate="workflow_fault", error_kind="child_unknown")
194
+ ctx.log.write("engine_error", unit=unit, error="child_unknown", detail=f"{rec.workflow}: {found.reason}")
195
+ return {"attempts": {unit: record}, "run": run}
196
+ seen = last_record(root_log(ctx.log).path, "unit_entered", unit=unit, child=ctx.child)
197
+ if not seen or seen.get("visit") != visit:
198
+ fp = fingerprint(Path(((state.get("workspace") or {}).get("path")) or ctx.state_root.parent))
199
+ ctx.log.write("unit_entered", unit=unit, visit=visit, head_commit=fp.head, dirty=fp.dirty,
200
+ entered_from=_entered(state, unit))
201
+ ctx.count_attempt(unit, None, attempt, visit)
202
+ built = build(ctx, unit, declared, found, (state.get("run") or {}).get("options") or {})
203
+ note = subworkflow.workspace_note(found)
204
+ if note and last_record(root_log(ctx.log).path, "note", child=built.path) is None:
205
+ built.nodes.ctx.log.write("note", message=note)
206
+ inputs = subworkflow.child_inputs(declared, state.get("request") or {}, _earlier(state))
207
+ base = dict(((state.get("run") or {}).get("cost") or {}).get("counters") or {})
208
+ try:
209
+ final: Mapping[str, Any] = built.graph.graph.invoke(child_input(state, inputs, built.options),
210
+ _child_config(config, built.path, visit, attempt))
211
+ except ChildUpstream as up:
212
+ record["upstream_child"] = {"key": up.key, "unit": subworkflow.mapped_source(declared, up.key),
213
+ "reason": up.reason}
214
+ ctx.attempts_started = built.nodes.ctx.attempts_started
215
+ if up.cost:
216
+ run["cost"] = {**up.cost, "_base": base}
217
+ run["children"] = {unit: {"workflow": built.name, "version": built.version, "upstream": up.key}}
218
+ return {"attempts": {unit: record}, "artifacts": {unit: None}, "values": {unit: None}, "run": run}
219
+ ctx.attempts_started = built.nodes.ctx.attempts_started
220
+ arts, vals, missing = subworkflow.exposed(declared, found, flat(final.get("artifacts")), flat(final.get("values")))
221
+ orec = outcome_record.build(built.spec, final, root_log(ctx.log).path, child=built.path)
222
+ stopped = (final.get("run") or {}).get("stopped")
223
+ failing = _failing(orec, stopped, built.name)
224
+ record.update(issues=[f"value_missing:{k}" for k in missing], child_failed=failing or None)
225
+ cost = (final.get("run") or {}).get("cost")
226
+ if cost:
227
+ run["cost"] = {**cost, "_base": base}
228
+ run["children"] = {unit: {"workflow": built.name, "version": built.version, "outcome": orec,
229
+ "stopped": dict(stopped) if stopped else None}}
230
+ return {"attempts": {unit: record}, "artifacts": {unit: arts or None}, "values": {unit: vals or None}, "run": run}
231
+
232
+
233
+ def child_states(cw: CompiledWorkflow, thread_id: str) -> dict[str, dict[str, Any]]:
234
+ """The newest checkpointed state of each child namespace of a thread (a child is a subgraph, so its checkpoints sit
235
+ in the parent's thread under a namespace of their own), keyed by the namespace; empty when there is none."""
236
+ saver = getattr(cw.graph, "checkpointer", None)
237
+ out: dict[str, dict[str, Any]] = {}
238
+ if saver is None:
239
+ return out
240
+ try:
241
+ for tup in saver.list(cw.config(thread_id)): # newest first
242
+ ns = str(tup.config["configurable"].get("checkpoint_ns") or "")
243
+ if ns and ns not in out:
244
+ out[ns] = dict(tup.checkpoint.get("channel_values") or {})
245
+ except Exception: # noqa: BLE001 - a store that cannot be read has no child to show
246
+ return {}
247
+ return out
248
+
249
+
250
+ def _child_config(config: Any, path: str, visit: int, attempt: int) -> dict[str, Any]:
251
+ """The config the child's graph runs with: the parent's, so the checkpointer and thread are the parent's, and a
252
+ checkpoint namespace of the unit's own (SWF-B8). The namespace belongs to one run of the unit (its visit and attempt),
253
+ not to the parent's task, whose id changes whenever the parent's state is updated while it is paused; so a child
254
+ resumes from where it paused, and a later visit or attempt starts a child with no state of the one before."""
255
+ conf = dict((config or {}).get("configurable") or {})
256
+ conf["checkpoint_ns"] = f"{path}.{visit}.{attempt}"
257
+ conf.pop("checkpoint_id", None)
258
+ return {**dict(config or {}), "configurable": conf}
259
+
260
+
261
+ def pending_cost(cw: CompiledWorkflow, thread_id: str) -> CostTotals | None:
262
+ """SWF-B4: the run's cost as the child furthest along holds it. A child that paused or was drained has not handed its
263
+ spend back to the parent's state, and that spend counts against the run and the day."""
264
+ best: CostTotals | None = None
265
+ for values in child_states(cw, thread_id).values():
266
+ held = CostTotals.from_json((values.get("run") or {}).get("cost"))
267
+ if best is None or held.sessions >= best.sessions:
268
+ best = held
269
+ return best
270
+
271
+
272
+ def _entered(state: Mapping[str, Any], unit: str) -> str:
273
+ v = (state.get("visits") or {}).get(unit) or {}
274
+ if v.get("entered_from"):
275
+ return str(v["entered_from"])
276
+ if int(v.get("visit", 1)) > 1 and v.get("from"):
277
+ return f"back:{v['from']}"
278
+ return "proceed" if ((state.get("run") or {}).get("path") or {}).get("units") else "start"