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,351 @@
1
+ """`rerun`: a new thread forked from an earlier one, linked to its source (RRN-B17, RRN-B18; ADR `rewind-on-the-thread-rerun-as-a-linked-fork`).
2
+
3
+ The fork is LangGraph's time travel: the source's checkpoint just before the unit's step node on its last
4
+ visit is copied to the new thread id, and the unit and everything after it are cleared as a trip back. The
5
+ source's history is never written. `--from start` starts the new thread from the source's resolved input.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import dataclasses
11
+ import json
12
+ import uuid
13
+ from collections.abc import Mapping
14
+ from datetime import UTC, datetime
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from tempergraph import git as gitmod
19
+ from tempergraph.compiler import compile_workflow
20
+ from tempergraph.contracts import ThreadState, WorkflowSpec, thread_id
21
+ from tempergraph.docs import write_json
22
+ from tempergraph.durability import engine_file
23
+ from tempergraph.durability.checkpoint import open_readonly
24
+ from tempergraph.durability.lock import LockHeld, RunLock
25
+ from tempergraph.durability.status import classify
26
+ from tempergraph.executors.preflight import preflight
27
+ from tempergraph.executors.registry import Registry
28
+ from tempergraph.git import is_safe_ref
29
+ from tempergraph.model import flow
30
+ from tempergraph.run import gate as gatemod
31
+ from tempergraph.run.log import Ledger, last_record
32
+ from tempergraph.run.outcome import with_outcome
33
+ from tempergraph.run.runner import (
34
+ RunOutcome,
35
+ RunSettings,
36
+ SettingsRefused,
37
+ _drive,
38
+ _Inert,
39
+ _refuse,
40
+ _refuse_settings,
41
+ _reopening,
42
+ _root,
43
+ join_keys,
44
+ settle_resume,
45
+ )
46
+ from tempergraph.store.layout import NotInRepository, ensure_state_root, lock_path, run_dir
47
+ from tempergraph.workspace import (
48
+ LOCK_REASON,
49
+ WorkspaceRecord,
50
+ WorkspaceRefused,
51
+ attach_workspace,
52
+ place,
53
+ prepare_workspace,
54
+ resolve_workspace,
55
+ )
56
+
57
+ EXTERNAL_KINDS = frozenset({"pull_request", "tracker_issue", "wiki_page"})
58
+
59
+
60
+ @dataclasses.dataclass(kw_only=True)
61
+ class Fork:
62
+ values: dict[str, Any]
63
+ config: dict[str, Any] | None # the source checkpoint's config; None for `--from start`
64
+ writer: str | None # the node that wrote that checkpoint
65
+ checkpoint_id: str | None
66
+
67
+
68
+ def external_effects(spec: WorkflowSpec, units: list[str], values: Mapping[str, Any]) -> list[str]:
69
+ """`<unit>: <kind>` for every unit in `units` that produced an external artifact or ran an external script."""
70
+ out: list[str] = []
71
+ arts = values.get("artifacts") or {}
72
+ attempts = values.get("attempts") or {}
73
+ for unit in units:
74
+ u = spec.units.get(unit)
75
+ if u is None or not attempts.get(unit):
76
+ continue
77
+ if u.step is not None:
78
+ for key, kind in u.step.produces.items():
79
+ if isinstance(kind, str) and kind in EXTERNAL_KINDS and key in (arts.get(unit) or {}):
80
+ out.append(f"{unit}: {kind}")
81
+ scripts = [*u.step.before, *u.step.after]
82
+ else:
83
+ scripts = [u.script] if u.script is not None else []
84
+ if any(sc.side_effects == "external" for sc in scripts):
85
+ out.append(f"{unit}: external script")
86
+ return out
87
+
88
+
89
+ def cleared_units(spec: WorkflowSpec, unit: str, values: Mapping[str, Any]) -> list[str]:
90
+ """`unit` and every later unit on the thread's path (RRN-B16, RRN-B17, RRN-B18)."""
91
+ order = flow.effective_order(spec)
92
+ path = list(((values.get("run") or {}).get("path") or {}).get("units") or [])
93
+ later = order[order.index(unit):] if unit in order else [unit]
94
+ return [u for u in later if u in path]
95
+
96
+
97
+ def find_fork(spec: WorkflowSpec, root: Path, source: str, start_at: str) -> Fork | None:
98
+ """The checkpoint just before `start_at`'s step node on its last visit, read-only."""
99
+ with open_readonly(engine_file.checkpoint_of(root, spec.name, source.partition("/")[2])) as saver:
100
+ if saver is None:
101
+ return None
102
+ cw = compile_workflow(with_outcome(spec), _Inert(), saver)
103
+ history = list(cw.graph.get_state_history(cw.config(source)))
104
+ if start_at == "start":
105
+ first = history[-1] if history else None
106
+ return Fork(values=dict(first.values or {}), config=None, writer=None, checkpoint_id=None) \
107
+ if first is not None else None
108
+ node = flow.step_node(start_at)
109
+ for snap in history: # newest first: the first hit is the unit's last visit
110
+ if node in tuple(snap.next or ()):
111
+ writes = (snap.metadata or {}).get("writes") or {}
112
+ writer = next(iter(writes), None) if len(writes) == 1 else None
113
+ return Fork(values=dict(snap.values or {}), config=dict(snap.config), writer=writer,
114
+ checkpoint_id=str((snap.config.get("configurable") or {}).get("checkpoint_id") or ""))
115
+ return None
116
+
117
+
118
+ def next_rerun_id(root: Path, spec: WorkflowSpec, source_task: str) -> tuple[str, int]:
119
+ n = 1
120
+ while classify(root, spec, f"{source_task}~r{n}") is not ThreadState.NONE:
121
+ n += 1
122
+ return f"{source_task}~r{n}", n
123
+
124
+
125
+ def rerun(spec: WorkflowSpec, source_task: str, target: Path, registry: Registry, *, start_at: str,
126
+ feedback: str | None = None, settings: RunSettings | None = None, task_id: str | None = None,
127
+ workspace_from: str = "current", same_branch: bool = False, drop_rulings: bool = False,
128
+ accept_external: bool = False, check: bool = False) -> RunOutcome | dict[str, Any]:
129
+ """RRN-B17, RRN-B18. With `check`, returns the plan document and creates nothing (OVR-B15)."""
130
+ settings = dataclasses.replace(settings or RunSettings(), origin="rerun")
131
+ out = _rerun(spec, source_task, target, registry, start_at=start_at, feedback=feedback, settings=settings,
132
+ task_id=task_id, workspace_from=workspace_from, same_branch=same_branch, drop_rulings=drop_rulings,
133
+ accept_external=accept_external, check=check)
134
+ if isinstance(out, RunOutcome) and out.thread_id: # BUD-B6 holds for the new thread too
135
+ return _reopening(out, spec, out.thread_id.partition("/")[2], target, registry, settings)
136
+ return out
137
+
138
+
139
+ def _rerun(spec: WorkflowSpec, source_task: str, target: Path, registry: Registry, *, start_at: str,
140
+ feedback: str | None, settings: RunSettings, task_id: str | None, workspace_from: str,
141
+ same_branch: bool, drop_rulings: bool, accept_external: bool, check: bool
142
+ ) -> RunOutcome | dict[str, Any]:
143
+ src = thread_id(spec.name, source_task)
144
+ try:
145
+ root = _root(target)
146
+ except NotInRepository:
147
+ return _refuse("not_git", "not inside a git repository")
148
+ state = classify(root, spec, source_task)
149
+ if state in (ThreadState.NONE, ThreadState.RUNNING):
150
+ return _refuse(str(state), f"{src}: a rerun needs a source that exists and is not running", tid=src)
151
+ if same_branch and state is not ThreadState.FINISHED:
152
+ return _refuse("same_branch_not_finished", f"{src}: --same-branch needs a finished source", tid=src)
153
+ if feedback and len(feedback) > gatemod.FEEDBACK_LIMIT:
154
+ return _refuse("feedback_too_long", f"feedback is over {gatemod.FEEDBACK_LIMIT} characters", tid=src)
155
+ if start_at != "start" and start_at not in spec.units:
156
+ return _refuse("units_behind", f"{start_at} is not a unit of {spec.name} {spec.version}", tid=src)
157
+ fork = find_fork(spec, root, src, start_at)
158
+ if fork is None:
159
+ return _refuse("fork_not_found", f"{src} never reached {start_at}", tid=src)
160
+ latest = _latest(spec, root, src)
161
+ path = list(((latest.get("run") or {}).get("path") or {}).get("units") or [])
162
+ behind = [u for u in path if u not in with_outcome(spec).units] # the compiled outcome unit is ours
163
+ if behind: # MIG-B15 with `start_at` as the pending unit
164
+ return _refuse("units_behind", f"units behind: {', '.join(behind)} are no longer in the workflow", tid=src)
165
+ first = flow.effective_order(spec)[0]
166
+ cleared = cleared_units(spec, first if start_at == "start" else start_at, latest)
167
+ effects = external_effects(spec, cleared, latest)
168
+ if effects and not accept_external:
169
+ return _refuse("external_effects", "units after the fork point had external effects: "
170
+ f"{'; '.join(effects)}; pass --accept-external", effects, tid=src)
171
+ new_task, n = (task_id, 0) if task_id else next_rerun_id(root, spec, source_task)
172
+ new = thread_id(spec.name, new_task)
173
+ if classify(root, spec, new_task) is not ThreadState.NONE:
174
+ return _refuse("thread_exists", f"{new} already exists", tid=new)
175
+ try:
176
+ if settings.caller:
177
+ from tempergraph import settings as rst
178
+ from tempergraph.run.runner import decided
179
+
180
+ settings = decided(settings, deciding=bool(feedback or any(rst.is_widening(k)
181
+ for k in settings.all_flags())),
182
+ words=("rerun",))
183
+ settled = settle_resume(spec, settings, root, fork.values if start_at != "start" else latest)
184
+ except SettingsRefused as exc:
185
+ return _refuse_settings(exc, new)
186
+ rv = settled.run
187
+ rep = preflight(settled.spec, registry, enforce_tools=bool(rv["enforce_tools"]),
188
+ strict_permissions=bool(rv["strict_permissions"]))
189
+ if not rep.ok:
190
+ first_f = rep.refusals[0]
191
+ return _refuse(first_f.code, f"{first_f.unit or spec.name}: {first_f.message}", tid=new)
192
+ run_spec = with_outcome(settled.spec)
193
+ src_ws = latest.get("workspace") or {}
194
+ try:
195
+ plan = _workspace_plan(run_spec, target, src_ws, new_task, n, workspace_from, root, src, start_at, rv)
196
+ if same_branch and plan.mode == "worktree": # the source's branch and worktree (RRN-B17, RRN-B18)
197
+ plan = dataclasses.replace(plan, branch=str(src_ws.get("branch") or plan.branch),
198
+ path=Path(str(src_ws.get("path") or plan.path)),
199
+ base_commit=str(src_ws.get("last_head") or plan.base_commit))
200
+ except WorkspaceRefused as exc:
201
+ return _refuse(exc.word, str(exc), tid=new)
202
+ started = last_record(run_dir(root, spec.name, source_task) / "run.jsonl", "run_started") or {}
203
+ rerun_of = {"thread": src, "unit": start_at, "checkpoint_id": fork.checkpoint_id,
204
+ "workflow_version": started.get("workflow_version")}
205
+ if check:
206
+ return {"schema_version": 1, "status": "ok", "thread_id": new, "rerun_of": rerun_of, "cleared": cleared,
207
+ "external_effects": effects, "workspace": {"mode": plan.mode, "branch": plan.branch or None,
208
+ "base_commit": plan.base_commit or None},
209
+ "settings_digest": settled.resolved.digest, "warnings": list(plan.warnings)}
210
+ ensure_state_root(root)
211
+ lock = RunLock(lock_path(root, spec.name, new_task))
212
+ try:
213
+ lock.acquire()
214
+ except LockHeld:
215
+ return _refuse("running", f"{new} is running", tid=new)
216
+ try:
217
+ try:
218
+ if same_branch and plan.mode == "worktree":
219
+ rec = attach_workspace(WorkspaceRecord.from_json(dict(src_ws)), new, run_spec.worktree, root)
220
+ gitmod.git(["worktree", "lock", "--reason", LOCK_REASON + new, "--end-of-options", rec.path],
221
+ Path(rec.path), check=False)
222
+ rec.state = "active"
223
+ else:
224
+ rec = prepare_workspace(new, plan, run_spec.worktree, root,
225
+ read_include=bool(rv["worktree.read_worktreeinclude"]))
226
+ except WorkspaceRefused as exc:
227
+ return _refuse(exc.word, str(exc), tid=new)
228
+ meta = {**(((fork.values.get("run") or {}).get("meta")) or {}), "origin": "rerun", "rerun_of": rerun_of}
229
+ writes = _writes(run_spec, fork, start_at, cleared, None if settings.ruling else feedback, drop_rulings,
230
+ settled.snapshot_json(), rec.to_json(), meta)
231
+ if settings.ruling and feedback:
232
+ writes = _with_ruling(writes, run_spec, fork, start_at, feedback, drop_rulings, dict(settings.caller))
233
+ if start_at == "start":
234
+ first_input: Any = {"request": dict(latest.get("request") or {}), **writes}
235
+ before = None
236
+ else:
237
+ first_input = None
238
+
239
+ def before(cw: Any) -> None:
240
+ saver = cw.graph.checkpointer
241
+ assert fork.config is not None
242
+ tup = saver.get_tuple(fork.config)
243
+ cfg = {"configurable": {"thread_id": new, "checkpoint_ns": ""}}
244
+ saver.put(cfg, tup.checkpoint, {**(tup.metadata or {}), "source": "fork"},
245
+ dict(tup.checkpoint.get("channel_versions") or {}))
246
+ cw.graph.update_state(cw.config(new), writes, as_node=fork.writer)
247
+ _lineage(root, spec, source_task, new, start_at, superseded=same_branch)
248
+ Ledger(path=root / "ledger.jsonl").append({ # the rerun is a steer touch on its source (SUP-B10)
249
+ "kind": "intervention", "id": uuid.uuid4().hex, "thread_id": src, "workflow": spec.name,
250
+ "workflow_version": spec.version, **join_keys(root, settings),
251
+ "unit": start_at, "caller": dict(settings.caller), "touches": [{"class": "steer", "action": "rerun"}],
252
+ "pause_kind": "finished" if state is ThreadState.FINISHED else str(state), "decision": f"rerun:{start_at}",
253
+ "wait_s": None, "feedback": bool(feedback), "ruling": settings.ruling,
254
+ "settings_changed": list(settled.changed), "grants": [], "cause": "rerun", "rerun": new})
255
+ out = _drive(run_spec, new_task, root, registry, settings, rep.judges, first_input, settled, before=before,
256
+ executors=rep.step_executors, rerun_of=rerun_of, workspace=rec.to_json())
257
+ out.warnings = list(plan.warnings) + out.warnings
258
+ return out
259
+ finally:
260
+ lock.release()
261
+
262
+
263
+ def _with_ruling(w: dict[str, Any], spec: WorkflowSpec, fork: Fork, start_at: str, text: str, drop: bool,
264
+ caller: Mapping[str, Any]) -> dict[str, Any]:
265
+ """`rerun --ruling`: the text is a ruling given at the fork unit, not its visit reason."""
266
+ have = {} if drop else dict(fork.values.get("rulings") or {})
267
+ at = start_at if start_at != "start" else flow.effective_order(spec)[0]
268
+ w["rulings"] = {**w.get("rulings", {}), **gatemod.ruling_writes(
269
+ {"rulings": have}, {"feedback": text, "ruling": {"applies_to": []}, "caller": dict(caller)}, at)}
270
+ return w
271
+
272
+
273
+ def _latest(spec: WorkflowSpec, root: Path, src: str) -> dict[str, Any]:
274
+ from tempergraph.durability.checkpoint import thread_values
275
+
276
+ return thread_values(engine_file.checkpoint_of(root, spec.name, src.partition("/")[2]), with_outcome(spec), src)
277
+
278
+
279
+ def _writes(spec: WorkflowSpec, fork: Fork, start_at: str, cleared: list[str], feedback: str | None,
280
+ drop_rulings: bool, options: Mapping[str, Any], workspace: Mapping[str, Any], meta: Mapping[str, Any]
281
+ ) -> dict[str, Any]:
282
+ """The new thread's state edits: a trip back from `start_at`, fresh budgets and cost, the rerun's records."""
283
+ v = fork.values
284
+ w: dict[str, Any] = {}
285
+ if start_at != "start":
286
+ w = gatemod.clear_from(spec, start_at, v)
287
+ visits = (v.get("visits") or {}).get(start_at) or {}
288
+ w["visits"] = {**w.get("visits", {}), start_at: {"visit": int(visits.get("visit", 1)) + 1,
289
+ "reason": feedback or "rerun by a person",
290
+ "from": None, "entered_from": "rerun"}}
291
+ w["pause"] = {u: None for u in (v.get("pause") or {})}
292
+ w["feedback"] = {u: None for u in (v.get("feedback") or {})}
293
+ # The edits are applied as the node that wrote the fork checkpoint, and its router runs again: a unit
294
+ # whose route sent the run to `start_at` (a trip back) keeps that route, else it reads None (RRN-B17).
295
+ into = flow.step_node(start_at)
296
+ keep = {u for u, r in (v.get("route") or {}).items() if isinstance(r, Mapping) and r.get("node") == into}
297
+ w["route"] = {u: None for u in cleared if u != start_at and u not in keep}
298
+ w["counters"] = {u: None for u in spec.units} # fresh retry, loop and human budgets (RRN-B17, RRN-B18)
299
+ if drop_rulings:
300
+ w["rulings"] = {rid: None for rid in (v.get("rulings") or {})}
301
+
302
+ w["workspace"] = dict(workspace)
303
+ w["run"] = {"cost": None, "stopped": None, "options": dict(options), "meta": dict(meta)}
304
+ return w
305
+
306
+
307
+ def _workspace_plan(spec: WorkflowSpec, target: Path, src_ws: Mapping[str, Any], new_task: str, n: int,
308
+ workspace_from: str, root: Path, src: str, start_at: str, rv: Mapping[str, Any]) -> Any:
309
+ """RRN-B17, RRN-B18 Workspace: a new branch `<branch>-r<n>` from the source branch's tip or its commit at the unit."""
310
+ plan = resolve_workspace(spec, target, "worktree" if src_ws.get("mode") == "worktree" else "in_place",
311
+ task_id=new_task, prefix=str(rv["worktree.branch_prefix"]),
312
+ root=str(rv.get("worktree.root") or "sibling"))
313
+ if plan.mode != "worktree":
314
+ return dataclasses.replace(plan, warnings=(*plan.warnings, "in_place_rerun: the rerun starts from the "
315
+ "files as they are now"))
316
+ branch = str(src_ws.get("branch") or "")
317
+ if workspace_from == "at-unit":
318
+ entered = last_record(run_dir(root, spec.name, src.split("/", 1)[1]) / "run.jsonl", "unit_entered",
319
+ unit=start_at)
320
+ base = str((entered or {}).get("head_commit") or "")
321
+ if not base:
322
+ raise WorkspaceRefused("no_commit_at_unit", f"no commit is recorded for {start_at}; use --workspace "
323
+ "current")
324
+ else:
325
+ base = gitmod.git(["rev-parse", "--verify", "--end-of-options", branch], plan.main or target,
326
+ check=False).strip() if branch else ""
327
+ base = base or plan.base_commit
328
+ new_branch = f"{branch}-r{n or 1}" if branch else plan.branch
329
+ if not is_safe_ref(new_branch):
330
+ raise WorkspaceRefused("branch_invalid", f"derived branch {new_branch!r} is not a valid ref")
331
+ path, kind = (place(plan.main, str(rv.get("worktree.root") or "sibling"), spec.name, new_task)
332
+ if plan.main else (plan.path, plan.root_kind))
333
+ return dataclasses.replace(plan, branch=new_branch, base_commit=base, path=path, root_kind=kind)
334
+
335
+
336
+ def _lineage(root: Path, spec: WorkflowSpec, source_task: str, new: str, start_at: str, *,
337
+ superseded: bool = False) -> None:
338
+ p = run_dir(root, spec.name, source_task) / "lineage.json"
339
+ try:
340
+ doc = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {}
341
+ except (OSError, ValueError):
342
+ doc = {}
343
+ doc = doc if isinstance(doc, dict) else {}
344
+ doc.setdefault("schema_version", 1)
345
+ doc.setdefault("reruns", []).append({"thread": new, "from": start_at,
346
+ "at": datetime.now(UTC).isoformat(timespec="seconds"),
347
+ **({"same_branch": True} if superseded else {})})
348
+ if superseded:
349
+ doc["superseded_by"] = new # the source's branch now carries the rerun's work
350
+ write_json(p, doc)
351
+
@@ -0,0 +1,85 @@
1
+ """Reservations for the sessions that run at once: the branches of a parallel block, writer branches included, the
2
+ items of a concurrent map, the slots of a contest and the member and chair sessions of a council, their step and judge
3
+ sessions alike (BUD-B12 to BUD-B15).
4
+
5
+ A thread-safe ledger of what each running session holds. A branch's, an item's, a slot's or a member's cost reaches the
6
+ run state only when its superstep or its node (or its council attempt) ends, so the cost check cannot see a sibling; the
7
+ ledger counts what is in flight, and adds the real cost of sessions that ended under the same snapshot of the state, which
8
+ the state a sibling read at its start does not hold. The width a caller gives `share` is the number of branches of the
9
+ block, the items of the map or the slots of the contest that may run at once (the lower of `concurrency` and the number
10
+ of items or slots), or the members of the round; a session that runs alone has width 1.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import threading
16
+ from collections.abc import Callable
17
+
18
+ WAIT_S = 1.0
19
+
20
+ Write = Callable[..., object]
21
+
22
+
23
+ def share(cap_usd: float, spent_usd: float, width: int) -> tuple[float, str]:
24
+ """The run's remaining cap divided by the number of branches, items or slots that may run at once (BUD-B12, third tier)."""
25
+ return round((cap_usd - spent_usd) / max(width, 1), 6), "share"
26
+
27
+
28
+ def session_amount(session_cap: float | None, cap_usd: float, spent_usd: float, width: int) -> tuple[float, str]:
29
+ """The session's own cost cap when it has one, else the share. No per-unit projection exists in the central
30
+ run stats, so the `projection` source is never produced."""
31
+ if session_cap is not None:
32
+ return float(session_cap), "session_cap"
33
+ return share(cap_usd, spent_usd, width)
34
+
35
+
36
+ class Ledger:
37
+ def __init__(self) -> None:
38
+ self._cond = threading.Condition()
39
+ self.held: dict[str, float] = {} # session key to the amount it reserved
40
+ self.ended: dict[int, float] = {} # snapshot id to the real cost of sessions that ended under it
41
+
42
+ def acquire(self, key: str, *, snapshot: int, spent_usd: float, cap_usd: float,
43
+ amount: Callable[[float], tuple[float, str]], write: Write,
44
+ drain: Callable[[], str | None]) -> str | None:
45
+ """Take the reservation of `key`: None when held, else the reason to drain. A reservation that would take
46
+ spend plus reservations strictly over the cap waits for a running session to end; with none running it is
47
+ refused (BUD-B12, BUD-B14, BUD-B15)."""
48
+ waited = False
49
+ with self._cond:
50
+ while True:
51
+ spent = round(spent_usd + self.ended.get(snapshot, 0.0), 6)
52
+ reserved, source = amount(spent)
53
+ reserved = max(reserved, 0.0) # a share of a remainder below zero is nothing to reserve, never a credit
54
+ in_flight = round(sum(self.held.values()), 6)
55
+ figures = {"reserved_usd": reserved, "source": source, "spent_usd": spent,
56
+ "in_flight_usd": in_flight, "cap_usd": cap_usd}
57
+ if round(spent + in_flight + reserved, 6) <= cap_usd:
58
+ self.held[key] = reserved
59
+ write("held", **figures)
60
+ return None
61
+ if not self.held:
62
+ write("refused", **figures)
63
+ self._cond.notify_all()
64
+ return "cost_cap"
65
+ if not waited:
66
+ write("waiting", **figures, waiting_for=sorted(self.held))
67
+ waited = True
68
+ self._cond.wait(WAIT_S)
69
+ reason = drain()
70
+ if reason:
71
+ return reason
72
+
73
+ def add_ended(self, snapshot: int, usd: float) -> None:
74
+ """A session of this snapshot ended before this process (a council member that a rerun found kept): its real cost
75
+ counts as spent for the sessions that follow."""
76
+ with self._cond:
77
+ self.ended[snapshot] = round(self.ended.get(snapshot, 0.0) + usd, 6)
78
+ self._cond.notify_all()
79
+
80
+ def release(self, key: str, *, snapshot: int, real_usd: float) -> None:
81
+ """A session ended: its reservation is replaced by its real cost."""
82
+ with self._cond:
83
+ if self.held.pop(key, None) is not None:
84
+ self.ended[snapshot] = round(self.ended.get(snapshot, 0.0) + real_usd, 6)
85
+ self._cond.notify_all()
@@ -0,0 +1,76 @@
1
+ """The `resources` line of the activity journal (EVT-B17, EVT-B18, EVT-B7, EVT-B19): CPU seconds, peak resident memory and the process
2
+ count of a session's process group, from a read-only process listing with constant argv. POSIX only; a
3
+ listing that fails gives no line, never an error."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import threading
9
+ import time
10
+ from collections.abc import Callable
11
+ from typing import Any
12
+
13
+ EVERY_S = 10.0
14
+
15
+
16
+ def cpu_seconds(text: str) -> float:
17
+ """`ps` time `[[dd-]hh:]mm:ss[.cc]` in seconds."""
18
+ days, _, rest = text.rpartition("-")
19
+ parts = [float(p) for p in rest.split(":")]
20
+ while len(parts) < 3:
21
+ parts.insert(0, 0.0)
22
+ h, m, s = parts[-3:]
23
+ return (int(days) if days else 0) * 86400 + h * 3600 + m * 60 + s
24
+
25
+
26
+ def sample(pgid: int, listing: Callable[[], str] | None = None) -> dict[str, Any] | None:
27
+ """One sample of the group: `cpu_s`, `rss_kb` (summed now) and `processes`; None when unreadable."""
28
+ from tempergraph.executors.launcher import process_listing
29
+
30
+ try:
31
+ text = (listing or process_listing)()
32
+ except OSError:
33
+ return None
34
+ cpu, rss, n = 0.0, 0, 0
35
+ for line in text.splitlines():
36
+ f = line.split()
37
+ if len(f) != 3 or f[0] != str(pgid):
38
+ continue
39
+ try:
40
+ rss += int(f[1])
41
+ cpu += cpu_seconds(f[2])
42
+ except ValueError:
43
+ continue
44
+ n += 1
45
+ return {"cpu_s": round(cpu, 2), "rss_kb": rss, "processes": n} if n else None
46
+
47
+
48
+ class Sampler:
49
+ """Every `EVERY_S` while the session runs, one sample into `out`; the peak resident memory is kept."""
50
+
51
+ def __init__(self, pgid: int, out: Callable[[dict[str, Any]], None], *, every_s: float = EVERY_S,
52
+ listing: Callable[[], str] | None = None, clock: Callable[[], float] = time.monotonic) -> None:
53
+ self.pgid, self.out, self.every_s, self.listing, self.clock = pgid, out, every_s, listing, clock
54
+ self.peak_kb = 0
55
+ self.done = threading.Event()
56
+ self.thread: threading.Thread | None = None
57
+
58
+ def start(self) -> Sampler:
59
+ if os.name == "posix":
60
+ self.thread = threading.Thread(target=self._run, name="resources", daemon=True)
61
+ self.thread.start()
62
+ return self
63
+
64
+ def once(self) -> None:
65
+ got = sample(self.pgid, self.listing)
66
+ if got is None:
67
+ return
68
+ self.peak_kb = max(self.peak_kb, int(got.pop("rss_kb")))
69
+ self.out({"ev": "resources", "t": round(self.clock(), 3), **got, "rss_peak_kb": self.peak_kb})
70
+
71
+ def _run(self) -> None:
72
+ while not self.done.wait(self.every_s):
73
+ self.once()
74
+
75
+ def stop(self) -> None:
76
+ self.done.set()