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,183 @@
1
+ """Caller provenance: who made a mutating call, and who decided it (PRV-B11 to PRV-B22; ADR `classify-callers-by-the-strongest-signal`, ADR `a-relayed-decision-counts-as-a-persons-only-with-host-turn-evidence`).
2
+
3
+ Accounting, not a security boundary: every signal can be forged by a process of the same user. A declaration
4
+ only lowers trust, and a refusal built on provenance fails toward the careful side. Read-only verbs never call
5
+ this module (OVR-B15).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ import uuid
13
+ from collections.abc import Callable, Mapping, Sequence
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ CI_SYSTEMS = {"GITHUB_ACTIONS": "github-actions", "GITLAB_CI": "gitlab-ci", "BUILDKITE": "buildkite",
19
+ "CIRCLECI": "circleci", "JENKINS_URL": "jenkins", "TF_BUILD": "azure-pipelines",
20
+ "TEAMCITY_VERSION": "teamcity"}
21
+ DECLARABLE = ("person", "agent", "pipeline")
22
+ RESERVED = ("orchestrator", "scheduler", "engine")
23
+ APP = re.compile(r"^[a-z0-9-]{1,40}$")
24
+
25
+
26
+ class CallerRefused(ValueError):
27
+ def __init__(self, code: str, message: str) -> None:
28
+ super().__init__(message)
29
+ self.code = code
30
+
31
+
32
+ def _set(env: Mapping[str, str], name: str) -> bool:
33
+ return bool(env.get(name))
34
+
35
+
36
+ def _scheduler(env: Mapping[str, str], schedule: str | None,
37
+ entry_for_fire: Callable[[str], Mapping[str, Any] | None] | None) -> dict[str, Any]:
38
+ """TCK-B17: the fire token against the digest of the entry the fire id names, before anything is written."""
39
+ import hashlib
40
+ import hmac
41
+
42
+ token = env.get("TEMPERGRAPH_SCHEDULE_TOKEN") or ""
43
+ if schedule and not token:
44
+ raise CallerRefused("schedule_reserved", "--schedule belongs to the scheduler's fires: it needs the fire token")
45
+ entry = entry_for_fire(schedule) if (schedule and entry_for_fire is not None) else None
46
+ wanted = str((entry or {}).get("token_digest") or "")
47
+ if not (schedule and entry and wanted and hmac.compare_digest(hashlib.sha256(token.encode("utf-8")).hexdigest(), wanted)):
48
+ raise CallerRefused("schedule_token_invalid", "no schedule entry on this machine matches the token")
49
+ sid, _, when = str(schedule).partition("@")
50
+ try:
51
+ slot = datetime.strptime(when.removeprefix("manual-"),
52
+ "%Y%m%dT%H%M%SZ" if when.startswith("manual-") else "%Y%m%dT%H%MZ")
53
+ except ValueError:
54
+ raise CallerRefused("schedule_token_invalid", "the fire id names no slot") from None
55
+ made = (entry.get("created") or {}).get("caller") or {}
56
+ trace = (env.get("TRACEPARENT") or "").split("-")
57
+ return {"kind": "scheduler", "confidence": "attested", "decided_by": None, "relay": None, "host": "schedule",
58
+ "host_session": None, "caller_app": None, "parent": None,
59
+ "schedule": {"schedule_id": sid, "fire_id": schedule, "slot": slot.strftime("%Y-%m-%dT%H:%M:%SZ"),
60
+ "created_by": {"kind": made.get("kind"), "decided_by": made.get("decided_by")}},
61
+ "trace_id": trace[1] if len(trace) >= 3 and len(trace[1]) == 32 else None,
62
+ "evidence": [{"signal": "S7", "value": "token_attested"}], "call_id": uuid.uuid4().hex}
63
+
64
+
65
+ def classify(env: Mapping[str, str], tty: bool, *, declared: str | None = None, caller_app: str | None = None,
66
+ schedule: str | None = None, parent: str | None = None,
67
+ entry_for_fire: Callable[[str], Mapping[str, Any] | None] | None = None) -> dict[str, Any]:
68
+ """PRV-B13: the first matching row decides; `evidence` keeps every signal seen."""
69
+ if env.get("TEMPERGRAPH_SESSION_KEY"):
70
+ raise CallerRefused("engine_session_caller", "a step never drives the engine (PRV-B5, PRV-B18, PRV-B17, PRV-B14, PRV-B13, PRV-B19, PRV-B15)")
71
+ if env.get("TEMPERGRAPH_SUPERVISOR_TOKEN") or parent:
72
+ # release 1 has no orchestrations, so no supervisor digest can match (ORC is release 3)
73
+ raise CallerRefused("supervisor_token_invalid", "no orchestration on this machine issued that token")
74
+ if env.get("TEMPERGRAPH_SCHEDULE_TOKEN") or schedule:
75
+ return _scheduler(env, schedule, entry_for_fire)
76
+ declared = declared or env.get("TEMPERGRAPH_CALLER") or None
77
+ caller_app = caller_app or env.get("TEMPERGRAPH_CALLER_APP") or None
78
+ if declared in RESERVED:
79
+ raise CallerRefused("caller_reserved", f"--caller {declared} cannot be declared")
80
+ if declared is not None and declared not in DECLARABLE:
81
+ raise CallerRefused("caller_invalid", f"--caller must be one of {', '.join(DECLARABLE)}")
82
+ if caller_app is not None and not APP.match(caller_app):
83
+ raise CallerRefused("caller_app_invalid", "--caller-app must match [a-z0-9-]{1,40}")
84
+ s2 = env.get("CLAUDE_CODE_CHILD_SESSION") == "1"
85
+ s3 = env.get("CLAUDECODE") == "1" and not s2
86
+ ci = next((sysname for var, sysname in CI_SYSTEMS.items() if _set(env, var)), None)
87
+ s4 = ci is not None or env.get("CI") == "true"
88
+ evidence = [{"signal": "S2", "value": "set" if s2 else "unset"},
89
+ {"signal": "S3", "value": "set" if s3 else "unset"},
90
+ {"signal": "S4", "value": "set" if s4 else "unset", **({"system": ci} if ci else {})},
91
+ {"signal": "S5", "value": "set" if tty else "unset"},
92
+ {"signal": "S6", "value": declared or "unset"}]
93
+ host, session = "unknown", None
94
+ if s2:
95
+ if declared == "person":
96
+ raise CallerRefused("caller_conflict", "a Claude Code tool call cannot declare itself a person; use "
97
+ "--relayed to carry a person's decision (PRV-B5)")
98
+ kind, confidence, host = "agent", "marked", "claude-code"
99
+ session = env.get("CLAUDE_CODE_SESSION_ID") or None
100
+ elif s4 and not tty:
101
+ kind, confidence, host = "pipeline", "marked", f"ci:{ci or 'unknown'}"
102
+ elif declared in ("agent", "pipeline"):
103
+ kind, confidence = declared, "declared"
104
+ host = "messages-api-app" if declared == "agent" and caller_app else "unknown"
105
+ elif tty:
106
+ kind, confidence, host = "person", "observed", "terminal"
107
+ elif declared == "person":
108
+ kind, confidence = "unknown", "declared"
109
+ else:
110
+ kind, confidence = "unknown", "none"
111
+ trace = (env.get("TRACEPARENT") or "").split("-")
112
+ return {"kind": kind, "confidence": confidence, "decided_by": None, "relay": None, "host": host,
113
+ "host_session": session, "caller_app": caller_app, "parent": None, "schedule": None,
114
+ "trace_id": trace[1] if len(trace) >= 3 and len(trace[1]) == 32 else None, "evidence": evidence,
115
+ "call_id": uuid.uuid4().hex}
116
+
117
+
118
+ def journal_path(home: Path, host: str, session: str) -> Path:
119
+ return home / "supervision" / host / f"{session}.jsonl"
120
+
121
+
122
+ def person_turns(home: Path, host: str, session: str | None) -> list[dict[str, Any]] | None:
123
+ """`person_turn` entries of the host session's supervision journal (SCO-B10, SCO-B11); None when unreadable."""
124
+ if not session or not re.match(r"^[A-Za-z0-9_.-]{1,128}$", session):
125
+ return None
126
+ p = journal_path(home, host, session)
127
+ if not p.exists():
128
+ return []
129
+ try:
130
+ lines = p.read_text(encoding="utf-8").splitlines()
131
+ except OSError:
132
+ return None
133
+ out = []
134
+ for ln in lines:
135
+ try:
136
+ e = json.loads(ln)
137
+ except ValueError:
138
+ continue
139
+ if isinstance(e, dict) and e.get("kind", e.get("entry")) == "person_turn":
140
+ out.append(e)
141
+ return out
142
+
143
+
144
+ def _after(at: Any, since: str | None) -> bool:
145
+ if since is None:
146
+ return True
147
+ try:
148
+ return datetime.fromisoformat(str(at)) > datetime.fromisoformat(since)
149
+ except ValueError:
150
+ return False
151
+
152
+
153
+ def decide(block: Mapping[str, Any], *, relayed: bool, words: Sequence[str] = (), since: str | None = None,
154
+ home: Path | None = None) -> dict[str, Any]:
155
+ """PRV-B14: the decider of a deciding call, from the caller and the host's person turns."""
156
+ out = dict(block)
157
+ kind = str(block.get("kind"))
158
+ if kind == "person":
159
+ out.update(decided_by="person", relay="direct")
160
+ elif kind == "agent" and relayed:
161
+ turns = person_turns(home, str(block.get("host")), block.get("host_session")) if home else None
162
+ if turns is None:
163
+ out.update(decided_by="agent", relay="claimed")
164
+ out["evidence"] = [*block.get("evidence", []), {"signal": "journal", "value": "journal_unreadable"}]
165
+ else:
166
+ later = [t for t in turns if _after(t.get("at"), since)]
167
+ named = [t for t in later if set(words) & set(t.get("names") or [])]
168
+ if named:
169
+ out.update(decided_by="person", relay="turn_named", person_turn_at=named[-1].get("at"))
170
+ elif later:
171
+ out.update(decided_by="person", relay="turn_only", person_turn_at=later[-1].get("at"))
172
+ else:
173
+ out.update(decided_by="agent", relay="claimed")
174
+ elif kind == "unknown":
175
+ out.update(decided_by="unknown", relay="claimed" if relayed else "none")
176
+ else:
177
+ out.update(decided_by=kind, relay="none")
178
+ return out
179
+
180
+
181
+ def may_widen(block: Mapping[str, Any]) -> bool:
182
+ """PRV-B21, PRV-B22: a widening needs a person, at a terminal or through a `turn_named` relay."""
183
+ return block.get("decided_by") == "person" and block.get("relay") in ("direct", "turn_named")
tempergraph/py.typed ADDED
File without changes
tempergraph/release.py ADDED
@@ -0,0 +1,17 @@
1
+ """The engine release record, `release.json` (VER-B8); plain data in the package, stdlib only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from functools import cache
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ RELEASE_JSON = Path(__file__).parent / "data" / "release.json"
11
+
12
+
13
+ @cache
14
+ def release() -> dict[str, Any]:
15
+ data = json.loads(RELEASE_JSON.read_text(encoding="utf-8"))
16
+ assert isinstance(data, dict)
17
+ return data
File without changes
@@ -0,0 +1,72 @@
1
+ """The output contract (PRM-B11) and step values (VAL-B5, VAL-B6).
2
+
3
+ A step ends with `ARTIFACT <key>: <value>` lines, or a `BLOCKED:` line, or an `UPSTREAM <unit>:` line.
4
+ A claim to a target not offered is read as blocked.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field
12
+
13
+ from tempergraph.contracts import ProducesKind, ValueKind
14
+ from tempergraph.security.scrub import scrub
15
+
16
+ _ARTIFACT_RE = re.compile(r"^\s*`?ARTIFACT\s+([A-Za-z0-9_.-]+)\s*:\s*(.*?)`?\s*$")
17
+ _BLOCKED_RE = re.compile(r"^\s*`?BLOCKED:\s*(.*?)`?\s*$")
18
+ _UPSTREAM_RE = re.compile(r"^\s*`?UPSTREAM\s+([A-Za-z0-9_.-]+)\s*:\s*(.*?)`?\s*$")
19
+
20
+
21
+ @dataclass
22
+ class ParsedOutput:
23
+ artifacts: dict[str, str] = field(default_factory=dict)
24
+ values: dict[str, str] = field(default_factory=dict)
25
+ blocked: str | None = None
26
+ upstream: tuple[str, str] | None = None
27
+ issues: list[str] = field(default_factory=list) # value_invalid:<k>, value_missing:<k>, value_clipped:<k>
28
+
29
+
30
+ def parse_output(text: str, produces: Mapping[str, ProducesKind], upstream_allowed: tuple[str, ...] = ()) -> ParsedOutput:
31
+ out = ParsedOutput()
32
+ lines = [ln for ln in (text or "").splitlines() if ln.strip()]
33
+ tail: list[str] = []
34
+ for ln in reversed(lines):
35
+ if _ARTIFACT_RE.match(ln) or _BLOCKED_RE.match(ln) or _UPSTREAM_RE.match(ln):
36
+ tail.append(ln)
37
+ continue
38
+ break
39
+ tail.reverse()
40
+ for ln in tail:
41
+ if m := _BLOCKED_RE.match(ln):
42
+ out.blocked = scrub(m.group(1).strip()) or "blocked"
43
+ elif m := _UPSTREAM_RE.match(ln):
44
+ unit, defect = m.group(1), m.group(2).strip()
45
+ if unit in upstream_allowed:
46
+ out.upstream = (unit, scrub(defect))
47
+ else:
48
+ out.blocked = scrub(f"upstream claim on {unit}: {defect}")
49
+ elif m := _ARTIFACT_RE.match(ln):
50
+ out.artifacts[m.group(1)] = m.group(2).strip()
51
+ for key, kind in produces.items():
52
+ raw = out.artifacts.get(key)
53
+ if isinstance(kind, ValueKind):
54
+ if raw is None:
55
+ if not kind.optional:
56
+ out.issues.append(f"value_missing:{key}")
57
+ continue
58
+ val = scrub(raw.strip())
59
+ if len(val) > kind.max_chars:
60
+ val = val[: kind.max_chars]
61
+ out.issues.append(f"value_clipped:{key}")
62
+ if kind.choices is not None:
63
+ norm = val.strip().lower()
64
+ if norm not in [c.lower() for c in kind.choices]:
65
+ out.issues.append(f"value_invalid:{key}")
66
+ continue
67
+ val = norm
68
+ if kind.pattern is not None and not re.fullmatch(kind.pattern, val):
69
+ out.issues.append(f"value_invalid:{key}")
70
+ continue
71
+ out.values[key] = val
72
+ return out
@@ -0,0 +1,166 @@
1
+ """The one renderer for every step prompt on every executor (PRM-B1, PRM-B6).
2
+
3
+ ``executor`` selects only the tool names written in the tools block; nothing else differs (PRM-AC2).
4
+ The step is shown its criteria texts as the target and never asked to grade itself (PRM-B2). Everything
5
+ after the template is appended verbatim, never format-processed (PRM-B4).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field
12
+
13
+ from tempergraph.contracts import Capabilities, UnitSpec, ValueKind
14
+ from tempergraph.executors.capabilities import tool_names
15
+ from tempergraph.render.template import render
16
+ from tempergraph.security.scrub import head_tail
17
+
18
+ PREVIOUS_REPORT_LIMIT = 3000
19
+ CHANGED_PATHS_LIMIT = 20
20
+
21
+
22
+ @dataclass(frozen=True, kw_only=True)
23
+ class Blocker:
24
+ criterion: str
25
+ place: str = ""
26
+ problem: str = ""
27
+ fix: str = ""
28
+
29
+
30
+ @dataclass(frozen=True, kw_only=True)
31
+ class AttemptContext:
32
+ template: str
33
+ fields: Mapping[str, str | None]
34
+ attempt: int = 1
35
+ retry: bool = False
36
+ blockers: tuple[Blocker, ...] = ()
37
+ check_evidence: str = ""
38
+ previous_report: str = ""
39
+ changed_paths: tuple[str, ...] = ()
40
+ paths_only: bool = False # after a timeout, infra failure or cut-off (PRM-B6)
41
+ notes: tuple[str, ...] = () # unmet warnings of the last pass
42
+ visit_reason: str = ""
43
+ visit_from: str = ""
44
+ feedback: str = ""
45
+ rulings: tuple[str, ...] = ()
46
+ upstream_targets: tuple[str, ...] = ()
47
+ grants: tuple[str, ...] = () # capabilities granted for this run (RST-B28, RST-B29, RST-B30)
48
+ lessons: str = "" # the rendered lessons block (LSN-B8, LSN-B2); the step only, never a judge
49
+ self_check: str = "" # the check preview's command for this attempt (CHK-B17)
50
+
51
+
52
+ @dataclass
53
+ class RenderedPrompt:
54
+ text: str
55
+ missing_fields: list[str]
56
+ sections: list[str] = field(default_factory=list)
57
+
58
+
59
+ def render_step(unit: str, spec: UnitSpec, ctx: AttemptContext, caps: Capabilities) -> RenderedPrompt:
60
+ step = spec.step
61
+ assert step is not None
62
+ body, missing = render(ctx.template, ctx.fields)
63
+ parts = [body.rstrip()]
64
+ sections = ["template"]
65
+
66
+ def add(name: str, text: str) -> None:
67
+ parts.append(text)
68
+ sections.append(name)
69
+
70
+ commands = [*step.commands, *([ctx.self_check] if ctx.self_check else [])]
71
+ if commands:
72
+ add("commands", "## Commands you may run\n" + "\n".join(f"- `{c}`" for c in commands))
73
+ if ctx.self_check: # PRM-B6: a fixed section, only when the step declares `self_check`
74
+ add("self_check", "## Check your work before you end\n"
75
+ f"Run `{ctx.self_check}` to see what the gate's check would find in the workspace as it "
76
+ "is now. It changes nothing and can be run a few times in this attempt. The gate's own "
77
+ "check still runs after you end.")
78
+ tools = list(dict.fromkeys(tuple(step.tools) + ctx.grants))
79
+ if tools:
80
+ add("tools", _tools_block(tools, caps, preview=bool(ctx.self_check)))
81
+ if ctx.lessons:
82
+ add("lessons", ctx.lessons)
83
+ if step.produces:
84
+ add("artifacts", _artifact_block(step.produces))
85
+ if spec.gate.criteria:
86
+ lines = [f"{i}. {c.text}" for i, c in enumerate(spec.gate.criteria, 1)]
87
+ add("criteria", "## How this output will be judged\nAn independent reviewer will check:\n" + "\n".join(lines))
88
+ blocked = ("## If you are blocked\nIf only a person can unblock this work, end with one line:\n"
89
+ "`BLOCKED: <what a person must decide or provide>`")
90
+ if ctx.upstream_targets:
91
+ names = ", ".join(f"`{t}`" for t in ctx.upstream_targets)
92
+ blocked += (f"\nIf an earlier unit's output ({names}) has a defect you cannot work around, end with one line:\n"
93
+ "`UPSTREAM <unit>: <defect>`")
94
+ add("blocked", blocked)
95
+ if ctx.notes:
96
+ add("notes", "## Notes from the previous review\n" + "\n".join(f"- {n}" for n in ctx.notes))
97
+ if ctx.visit_reason:
98
+ who = f" (sent back by `{ctx.visit_from}`)" if ctx.visit_from else ""
99
+ add("visit_reason", f"## Why this unit runs again{who}\nEvery point of this reason must be addressed:\n"
100
+ f"{ctx.visit_reason}")
101
+ if ctx.retry:
102
+ add("retry", _retry_block(ctx))
103
+ if ctx.feedback:
104
+ add("feedback", "## Feedback from a person\n" + ctx.feedback)
105
+ if ctx.rulings:
106
+ add("rulings", "## Rulings from a person (apply on every attempt)\n" + "\n".join(f"- {r}" for r in ctx.rulings))
107
+ return RenderedPrompt(text="\n\n".join(parts) + "\n", missing_fields=missing, sections=sections)
108
+
109
+
110
+ def _tools_block(tools: list[str], caps: Capabilities, preview: bool = False) -> str:
111
+ names: list[str] = []
112
+ for t in tools:
113
+ names.extend(tool_names(caps, t))
114
+ lines = ["## Tools for this step", "Tools: " + ", ".join(f"`{n}`" for n in dict.fromkeys(names)) + ".",
115
+ "Stay in the working directory."]
116
+ file_tools = {"read", "search", "list", "edit", "write"} & set(tools)
117
+ if "shell" in tools:
118
+ if file_tools:
119
+ lines.append("Prefer the file tools over the shell when both can do the job.")
120
+ lines.append("Run git without a leading change of directory.")
121
+ lines.append("Run only the listed commands.")
122
+ elif preview: # CHK-B17: the preview is granted as one exact command; say so, or a model believes the line
123
+ shell = (tool_names(caps, "shell") or ["shell"])[0] # below and never runs it (live check L-29)
124
+ lines.append(f"There is no shell in this step except for the check preview: run that one command with the "
125
+ f"`{shell}` tool, exactly as written above.")
126
+ else:
127
+ lines.append("There is no shell in this step.")
128
+ return "\n".join(lines)
129
+
130
+
131
+ def _artifact_block(produces: Mapping[str, object]) -> str:
132
+ lines = ["## What to end with", "End your answer with one line per output:"]
133
+ for key, kind in produces.items():
134
+ if isinstance(kind, ValueKind):
135
+ desc = "one line"
136
+ if kind.choices:
137
+ desc += " (one of: " + ", ".join(kind.choices) + ")"
138
+ lines.append(f"`ARTIFACT {key}: <{desc}>`")
139
+ else:
140
+ lines.append(f"`ARTIFACT {key}: <{kind}>`")
141
+ return "\n".join(lines)
142
+
143
+
144
+ def _retry_block(ctx: AttemptContext) -> str:
145
+ lines = ["## The previous attempt was not accepted"]
146
+ if not ctx.paths_only:
147
+ for b in ctx.blockers:
148
+ row = f"- {b.criterion}"
149
+ if b.place:
150
+ row += f" — at {b.place}"
151
+ if b.problem:
152
+ row += f": {b.problem}"
153
+ if b.fix:
154
+ row += f" Fix: {b.fix}"
155
+ lines.append(row)
156
+ if ctx.check_evidence:
157
+ lines.append("Check evidence:\n" + head_tail(ctx.check_evidence, 2000))
158
+ if ctx.previous_report:
159
+ lines.append("What the previous attempt reported (a claim, not a fact):\n"
160
+ + head_tail(ctx.previous_report, PREVIOUS_REPORT_LIMIT))
161
+ else:
162
+ lines.append("The previous attempt ended before it finished.")
163
+ if ctx.changed_paths:
164
+ paths = list(ctx.changed_paths)[:CHANGED_PATHS_LIMIT]
165
+ lines.append("Paths changed since it began:\n" + "\n".join(f"- {p}" for p in paths))
166
+ return "\n".join(lines)
@@ -0,0 +1,86 @@
1
+ """The template grammar of CON-B8.
2
+
3
+ Literal text, doubled braces for literal braces, and plain fields ``{name}`` where ``name`` is an engine
4
+ key, a declared input, an earlier artifact key, ``settings.<name>``, or ``<unit>.<key>`` (a sub-workflow
5
+ unit's exposed key, SWF-B12). Nothing else between braces is valid. A field without a value renders as the visible marker ``⟨missing:name⟩``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections.abc import Mapping
12
+ from dataclasses import dataclass
13
+
14
+ from tempergraph.constants import MISSING_MARKER
15
+
16
+ FIELD_RE = re.compile(r"^(?:[A-Za-z_][A-Za-z0-9_]*\.)?[A-Za-z_][A-Za-z0-9_]*$") # `name`, or one dotted pair
17
+
18
+
19
+ class TemplateError(ValueError):
20
+ def __init__(self, message: str, position: int) -> None:
21
+ super().__init__(f"{message} at offset {position}")
22
+ self.position = position
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Part:
27
+ literal: str | None = None
28
+ field: str | None = None
29
+
30
+
31
+ def parse(template: str) -> list[Part]:
32
+ parts: list[Part] = []
33
+ buf: list[str] = []
34
+ i, n = 0, len(template)
35
+ while i < n:
36
+ ch = template[i]
37
+ if ch == "{":
38
+ if i + 1 < n and template[i + 1] == "{":
39
+ buf.append("{")
40
+ i += 2
41
+ continue
42
+ end = template.find("}", i + 1)
43
+ if end < 0:
44
+ raise TemplateError("unbalanced '{'", i)
45
+ name = template[i + 1 : end]
46
+ if not FIELD_RE.match(name):
47
+ raise TemplateError(f"invalid field {{{name}}}", i)
48
+ if buf:
49
+ parts.append(Part(literal="".join(buf)))
50
+ buf = []
51
+ parts.append(Part(field=name))
52
+ i = end + 1
53
+ continue
54
+ if ch == "}":
55
+ if i + 1 < n and template[i + 1] == "}":
56
+ buf.append("}")
57
+ i += 2
58
+ continue
59
+ raise TemplateError("unbalanced '}'", i)
60
+ buf.append(ch)
61
+ i += 1
62
+ if buf:
63
+ parts.append(Part(literal="".join(buf)))
64
+ return parts
65
+
66
+
67
+ def fields(template: str) -> list[str]:
68
+ return [p.field for p in parse(template) if p.field is not None]
69
+
70
+
71
+ def render(template: str, values: Mapping[str, str | None]) -> tuple[str, list[str]]:
72
+ """Render; return the text and the fields rendered as the missing marker (CON-AC2)."""
73
+ out: list[str] = []
74
+ missing: list[str] = []
75
+ for p in parse(template):
76
+ if p.literal is not None:
77
+ out.append(p.literal)
78
+ continue
79
+ assert p.field is not None
80
+ val = values.get(p.field)
81
+ if val is None:
82
+ missing.append(p.field)
83
+ out.append(MISSING_MARKER.format(name=p.field))
84
+ else:
85
+ out.append(str(val))
86
+ return "".join(out), missing
@@ -0,0 +1,2 @@
1
+ """The gate funnel and the run path: run log, checks, judge, guard, gate, human, budgets, scripts,
2
+ finalizer and the runner that drives a compiled workflow (T5)."""