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.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- tempergraph_pytest_plugin.py +64 -0
|
@@ -0,0 +1,1579 @@
|
|
|
1
|
+
"""Start and resume a run (DUR-B9, DUR-B11; CON-B12, CON-B13 exit codes; HUM-B2; RCT-B6, RCT-B7).
|
|
2
|
+
|
|
3
|
+
Everything that can refuse runs before anything is created: validation and preflight, the thread
|
|
4
|
+
state (DUR-B1), the workspace plan and the lock. A refusal is exit 2 with nothing written (OVR-B15).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import dataclasses
|
|
11
|
+
import json
|
|
12
|
+
import uuid
|
|
13
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from tempergraph import provenance
|
|
20
|
+
from tempergraph import settings as rst
|
|
21
|
+
from tempergraph.compiler import compile_workflow
|
|
22
|
+
from tempergraph.constants import ENGINE_VERSION, ExitCode
|
|
23
|
+
from tempergraph.contracts import Decision, ResolvedSettings, RunOptions, ThreadState, WorkflowSpec, thread_id
|
|
24
|
+
from tempergraph.docs import read_json, write_json
|
|
25
|
+
from tempergraph.durability import alias as aliases
|
|
26
|
+
from tempergraph.durability import carry as carrymod
|
|
27
|
+
from tempergraph.durability import engine_file as enginefile
|
|
28
|
+
from tempergraph.durability.checkpoint import (
|
|
29
|
+
classify_snapshot,
|
|
30
|
+
open_saver,
|
|
31
|
+
resume_input,
|
|
32
|
+
snapshot,
|
|
33
|
+
update_values,
|
|
34
|
+
)
|
|
35
|
+
from tempergraph.durability.control import StopWatcher, take_stop
|
|
36
|
+
from tempergraph.durability.lock import LockHeld, RunLock, is_held
|
|
37
|
+
from tempergraph.durability.status import breakpoint_at, classify
|
|
38
|
+
from tempergraph.executors.launcher import StopRequest
|
|
39
|
+
from tempergraph.executors.preflight import observer_warnings, preflight
|
|
40
|
+
from tempergraph.executors.registry import Registry
|
|
41
|
+
from tempergraph.git import main_checkout
|
|
42
|
+
from tempergraph.model import flow, subworkflow
|
|
43
|
+
from tempergraph.model.diagram import diagram_model
|
|
44
|
+
from tempergraph.model.validate import Finding
|
|
45
|
+
from tempergraph.run import gate as gatemod
|
|
46
|
+
from tempergraph.run import outcome_record, subrun, supervision
|
|
47
|
+
from tempergraph.run.log import CostTotals, Ledger, RunLog, cost_so_far, last_record, legacy_dry_run
|
|
48
|
+
from tempergraph.run.nodes import Drain, EngineNodes, RunContext
|
|
49
|
+
from tempergraph.run.outcome import with_outcome
|
|
50
|
+
from tempergraph.security.scrub import clip, scrub
|
|
51
|
+
from tempergraph.store import manifest as manifestmod
|
|
52
|
+
from tempergraph.store.layout import (
|
|
53
|
+
NotInRepository,
|
|
54
|
+
ensure_state_root,
|
|
55
|
+
home_path,
|
|
56
|
+
lock_path,
|
|
57
|
+
run_dir,
|
|
58
|
+
state_root_path,
|
|
59
|
+
)
|
|
60
|
+
from tempergraph.workspace import (
|
|
61
|
+
WorkspaceRecord,
|
|
62
|
+
WorkspaceRefused,
|
|
63
|
+
attach_workspace,
|
|
64
|
+
file_missing_at_base,
|
|
65
|
+
prepare_workspace,
|
|
66
|
+
release_workspace,
|
|
67
|
+
resolve_workspace,
|
|
68
|
+
take_pause_mark,
|
|
69
|
+
write_pause_mark,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
STOP_EXIT = {"infra": ExitCode.BUDGET_OR_INFRA, "budget": ExitCode.BUDGET_OR_INFRA, "person": ExitCode.STOPPED}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(kw_only=True)
|
|
76
|
+
class RunOutcome:
|
|
77
|
+
exit_code: ExitCode
|
|
78
|
+
reason: str = ""
|
|
79
|
+
message: str = ""
|
|
80
|
+
payload: dict[str, Any] | None = None
|
|
81
|
+
degraded: bool = False # a gate's fallback target was taken (FLX-B9)
|
|
82
|
+
thread_id: str = ""
|
|
83
|
+
warnings: list[str] = field(default_factory=list)
|
|
84
|
+
refusals: list[str] = field(default_factory=list)
|
|
85
|
+
auto_reopen: int = 0 # `run.auto_reopen` of the segment that ended (BUD-B6)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(kw_only=True)
|
|
89
|
+
class RunSettings:
|
|
90
|
+
workspace: str | None = None
|
|
91
|
+
alias: str | None = None
|
|
92
|
+
label: str | None = None
|
|
93
|
+
origin: str = "cli"
|
|
94
|
+
enforce_tools: bool = False
|
|
95
|
+
strict_permissions: bool = False
|
|
96
|
+
judge_override: str | None = None
|
|
97
|
+
caller: Mapping[str, Any] = field(default_factory=dict)
|
|
98
|
+
sleep: Callable[[float], None] | None = None
|
|
99
|
+
infra_tries: int | None = None
|
|
100
|
+
flags: Mapping[str, Any] = field(default_factory=dict) # `--set` and its named spellings (RST-B22, RST-B23 layer 1)
|
|
101
|
+
profiles: tuple[str, ...] | None = None # None keeps the thread's profiles on resume
|
|
102
|
+
unset: tuple[str, ...] = ()
|
|
103
|
+
reload_settings: bool = False
|
|
104
|
+
ruling: bool = False # `--ruling`: the feedback is a lasting ruling (RRN-B14, RRN-B15)
|
|
105
|
+
ruling_for: tuple[str, ...] = ()
|
|
106
|
+
revoke_rulings: tuple[str, ...] = ()
|
|
107
|
+
accept_external: bool = False # consent to rewind or rerun past external effects (RRN-B16)
|
|
108
|
+
relayed: bool = False # `--relayed`: the call carries a person's decision (PRV-B14)
|
|
109
|
+
dry_run: bool = False # `--dry-run`: self-improvement files nothing for this run (ROP-B1 to ROP-B13)
|
|
110
|
+
home: Path | None = None # the user config folder's parent; default `home_path()`
|
|
111
|
+
escalate: bool = False # `resume --escalate`: take the offered escalation (LAD-B12)
|
|
112
|
+
escalation_record: Callable[[str], bool] | None = None # a seam for LAD-B13's escalation record
|
|
113
|
+
judge_state: Callable[[str], str] | None = None # a seam for a gate's judge binding state (JCL-B17)
|
|
114
|
+
carry: bool = False # `--carry`: carry this thread's state on its own branch (CAR-B5)
|
|
115
|
+
answers: Mapping[str, Any] = field(default_factory=dict) # `answer:<name>=<value>` and `--answers` (ASK-B8)
|
|
116
|
+
apply_deadline: bool = False # `resume --apply-deadline` (FLX-B8)
|
|
117
|
+
pause_before: tuple[str, ...] = () # `--pause-before <unit>`: operator breakpoints of this segment (FLX-B10)
|
|
118
|
+
unit: str | None = None # `resume --unit`: which of several pending gates the decision answers (HUM-B3)
|
|
119
|
+
operator_reason: str | None = None # `resume --reason`: one fixed word on the decision's ledger row (CLI-B24)
|
|
120
|
+
schedule: Mapping[str, Any] | None = None # a scheduled run's `{schedule_id, fire_id, slot}` (TCK-B24)
|
|
121
|
+
audit_seed: int | None = None # a test hook: mixed into the audit judge's draw so a test's sampling is stable (JDG-B7)
|
|
122
|
+
|
|
123
|
+
def all_flags(self) -> dict[str, Any]:
|
|
124
|
+
"""The named run options are spellings of `--set` (ROP-B1 to ROP-B13)."""
|
|
125
|
+
f = dict(self.flags)
|
|
126
|
+
for key, val in (("run.workspace", self.workspace), ("judges.executor", self.judge_override),
|
|
127
|
+
("run.infra_tries", self.infra_tries)):
|
|
128
|
+
if val is not None:
|
|
129
|
+
f.setdefault(key, val)
|
|
130
|
+
for key, on in (("run.enforce_tools", self.enforce_tools), ("run.strict_permissions", self.strict_permissions)):
|
|
131
|
+
if on:
|
|
132
|
+
f.setdefault(key, True)
|
|
133
|
+
return f
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(kw_only=True)
|
|
137
|
+
class Settled:
|
|
138
|
+
"""A resolution applied: the spec the run executes, its settings and the snapshot to keep (RST-B26)."""
|
|
139
|
+
|
|
140
|
+
spec: WorkflowSpec
|
|
141
|
+
resolved: ResolvedSettings
|
|
142
|
+
options: RunOptions
|
|
143
|
+
changed: list[str] = field(default_factory=list)
|
|
144
|
+
before: ResolvedSettings | None = None
|
|
145
|
+
|
|
146
|
+
def grant_changes(self) -> list[dict[str, Any]]:
|
|
147
|
+
"""Grants given or removed by this call, against the thread's previous snapshot (RST-B28, RST-B29, RST-B30)."""
|
|
148
|
+
new = rst.grants(self.resolved)
|
|
149
|
+
old = rst.grants(self.before) if self.before is not None else []
|
|
150
|
+
return ([{**g, "action": "given"} for g in new if g not in old]
|
|
151
|
+
+ [{**g, "action": "removed"} for g in old if g not in new])
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def run(self) -> dict[str, Any]:
|
|
155
|
+
return rst.run_values(self.resolved)
|
|
156
|
+
|
|
157
|
+
def snapshot_json(self) -> dict[str, Any]:
|
|
158
|
+
return {"settings": self.options.settings, "profiles": list(self.options.profiles)}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def decided(settings: RunSettings, *, deciding: bool, words: Sequence[str] = (), since: str | None = None
|
|
162
|
+
) -> RunSettings:
|
|
163
|
+
"""PRV-B14: fill the decider of a deciding call; `--relayed` on a call that decides nothing is refused."""
|
|
164
|
+
if not deciding:
|
|
165
|
+
if settings.relayed:
|
|
166
|
+
raise SettingsRefused([Finding(code="relay_not_applicable", unit=None,
|
|
167
|
+
message="--relayed on a call that decides nothing")])
|
|
168
|
+
return settings
|
|
169
|
+
block = provenance.decide(settings.caller, relayed=settings.relayed, words=words, since=since,
|
|
170
|
+
home=settings.home or home_path())
|
|
171
|
+
return dataclasses.replace(settings, caller=block)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _widen_kind(settings: RunSettings) -> str:
|
|
175
|
+
"""The caller kind the widening rule sees: `person` only for a person or a `turn_named` relay (PRV-B21, PRV-B22)."""
|
|
176
|
+
if not settings.caller: # `run --check` and `config show` read no signals (OVR-B15); the call itself checks
|
|
177
|
+
return "person"
|
|
178
|
+
return "person" if provenance.may_widen(settings.caller) else str(settings.caller.get("decided_by")
|
|
179
|
+
or settings.caller.get("kind") or "unknown")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class SettingsRefused(Exception):
|
|
183
|
+
def __init__(self, findings: list[Any]) -> None:
|
|
184
|
+
super().__init__(findings[0].message)
|
|
185
|
+
self.findings = findings
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def settle_start(spec: WorkflowSpec, settings: RunSettings, root: Path | None) -> Settled:
|
|
189
|
+
"""Read both files once, resolve, validate before spend (RST-B26 Start)."""
|
|
190
|
+
files = rst.load_files(root, settings.home or home_path())
|
|
191
|
+
opts, findings = rst.options_snapshot(spec, settings.all_flags(), tuple(settings.profiles or ()), files,
|
|
192
|
+
via=settings.origin, caller_kind=_widen_kind(settings))
|
|
193
|
+
if findings:
|
|
194
|
+
raise SettingsRefused(findings)
|
|
195
|
+
res = rst.resolve(spec, opts)
|
|
196
|
+
return Settled(spec=rst.effective_spec(spec, res), resolved=res, options=opts)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def settle_resume(spec: WorkflowSpec, settings: RunSettings, root: Path, values: Mapping[str, Any]) -> Settled:
|
|
200
|
+
"""Reapply the thread's snapshot, then this call's `--set`, `--unset`, `--profile`, `--reload-settings`."""
|
|
201
|
+
snap = ((values.get("run") or {}).get("options") or {})
|
|
202
|
+
old = RunOptions(settings={k: dict(v) for k, v in (snap.get("settings") or {}).items()},
|
|
203
|
+
profiles=tuple(snap.get("profiles") or ()))
|
|
204
|
+
flags = {k: c["value"] for k, c in (old.settings.get("flag") or {}).items()}
|
|
205
|
+
for k, v in settings.all_flags().items(): # a later grant adds to the thread's grants (RST-B28, RST-B29, RST-B30 Kept)
|
|
206
|
+
if rst.is_widening(k) and k in flags:
|
|
207
|
+
v = list(dict.fromkeys(rst.as_list(flags[k]) + rst.as_list(v)))
|
|
208
|
+
flags[k] = v
|
|
209
|
+
for k in settings.unset:
|
|
210
|
+
flags.pop(k, None)
|
|
211
|
+
profiles = tuple(settings.profiles) if settings.profiles is not None else old.profiles
|
|
212
|
+
if settings.reload_settings or settings.profiles is not None:
|
|
213
|
+
files = rst.load_files(root, settings.home or home_path())
|
|
214
|
+
new, findings = rst.options_snapshot(spec, flags, profiles, files, via=settings.origin,
|
|
215
|
+
caller_kind=_widen_kind(settings))
|
|
216
|
+
if not settings.reload_settings: # a new profile list reads profiles only; the file layers stay
|
|
217
|
+
new = RunOptions(settings={**{k: v for k, v in old.settings.items()}, "profile": new.settings["profile"],
|
|
218
|
+
"flag": new.settings["flag"]}, profiles=profiles)
|
|
219
|
+
findings = [f for f in findings if f.code in ("unknown_profile", "widening_in_file")]
|
|
220
|
+
else:
|
|
221
|
+
new = RunOptions(settings={**old.settings, "flag": rst.snapshot(spec, flags, (), rst.ConfigFiles(),
|
|
222
|
+
via=settings.origin)[0]["flag"]},
|
|
223
|
+
profiles=profiles)
|
|
224
|
+
findings = []
|
|
225
|
+
if not (settings.reload_settings or settings.profiles is not None):
|
|
226
|
+
findings += rst.validate_layers(spec, new.settings, _widen_kind(settings))
|
|
227
|
+
if findings:
|
|
228
|
+
raise SettingsRefused(findings)
|
|
229
|
+
res = rst.resolve(spec, new)
|
|
230
|
+
before = rst.resolve(spec, old) if snap else None
|
|
231
|
+
changed = rst.changed_keys(before, res)
|
|
232
|
+
return Settled(spec=rst.effective_spec(spec, res), resolved=res, options=new, changed=changed, before=before)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _refuse(reason: str, message: str, refusals: list[str] | None = None, tid: str = "") -> RunOutcome:
|
|
236
|
+
return RunOutcome(exit_code=ExitCode.USAGE, reason=reason, message=message, refusals=refusals or [], thread_id=tid)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _answers(log_path: Path, g: Mapping[str, Any]) -> dict[str, Any] | None:
|
|
240
|
+
"""The pause a grant answers: the refusal class it fixes and that pause's `seq` (EVT-B10 to EVT-B16 `grant`)."""
|
|
241
|
+
pause = last_record(log_path, "pause", unit=g["unit"])
|
|
242
|
+
for item in (pause or {}).get("tool_access") or []:
|
|
243
|
+
if item.get("capability") == g.get("capability"):
|
|
244
|
+
return {"class": item.get("class"), "seq": pause.get("seq") if pause else None}
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _grants_used(spec: WorkflowSpec, registry: Registry, settled: Settled, values: Mapping[str, Any]
|
|
249
|
+
) -> list[dict[str, Any]]:
|
|
250
|
+
"""The ledger row's `grants[]`: whether the unit's last attempt used each grant (RST-B28, RST-B29, RST-B30, IMD-B18)."""
|
|
251
|
+
from tempergraph.executors.capabilities import tool_names
|
|
252
|
+
|
|
253
|
+
out = []
|
|
254
|
+
for g in rst.grants(settled.resolved):
|
|
255
|
+
u = spec.units.get(g["unit"])
|
|
256
|
+
att = ((values.get("attempts") or {}).get(g["unit"]) or {})
|
|
257
|
+
used: bool | None = None
|
|
258
|
+
if "capability" in g and u is not None and u.step is not None and att:
|
|
259
|
+
ex = registry.get(u.step.executor or spec.default_executor)
|
|
260
|
+
used = bool(set(tool_names(ex.capabilities(), g["capability"])) & set(att.get("tools") or []))
|
|
261
|
+
out.append({**{k: v for k, v in g.items() if k != "key"}, "used": used,
|
|
262
|
+
"passed": att.get("ok") if att else None})
|
|
263
|
+
return out
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _refuse_settings(exc: SettingsRefused, tid: str) -> RunOutcome:
|
|
267
|
+
first = exc.findings[0]
|
|
268
|
+
return _refuse(first.code, f"{first.code}: {first.message}", [f"{f.code}: {f.message}" for f in exc.findings],
|
|
269
|
+
tid)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _root(target: Path) -> Path:
|
|
273
|
+
return state_root_path(target)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def exit_file(state_root: Path, workflow: str, task_id: str) -> Path:
|
|
277
|
+
return run_dir(state_root, workflow, task_id) / "exit.json"
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def pause_mark_file(state_root: Path, workflow: str, task_id: str) -> Path:
|
|
281
|
+
"""The head and status of the worktree of a segment that ended to be resumed (WTR-B28)."""
|
|
282
|
+
return run_dir(state_root, workflow, task_id) / "pause-workspace.json"
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _content_version(spec: WorkflowSpec) -> str:
|
|
286
|
+
from tempergraph.package.loader import full_version
|
|
287
|
+
|
|
288
|
+
return full_version(spec)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def children_of(spec: WorkflowSpec, above: str = "", depth: int = 0) -> dict[str, dict[str, Any]]:
|
|
292
|
+
"""SWF-B8: each sub-workflow unit's child as the registry gives it now, keyed by the unit's path (`<unit>`, or
|
|
293
|
+
`<unit>/<unit>` for a child of a child): its name, version, content version, units and spec. A child that cannot be
|
|
294
|
+
read is left out; validation and the resume check speak of it."""
|
|
295
|
+
out: dict[str, dict[str, Any]] = {}
|
|
296
|
+
if depth > subworkflow.MAX_DEPTH:
|
|
297
|
+
return out
|
|
298
|
+
for unit in subworkflow.units_of(spec):
|
|
299
|
+
rec = spec.units[unit].subworkflow
|
|
300
|
+
assert rec is not None
|
|
301
|
+
got = subworkflow.read_child(rec.workflow)
|
|
302
|
+
if not isinstance(got, subworkflow.Child):
|
|
303
|
+
continue
|
|
304
|
+
key = f"{above}{unit}"
|
|
305
|
+
out[key] = {"workflow": got.name, "workflow_version": got.version, "content_version": _content_version(got.spec),
|
|
306
|
+
"units": enginefile.unit_digests(got.spec), "spec": got.spec}
|
|
307
|
+
out.update(children_of(got.spec, f"{key}/", depth + 1))
|
|
308
|
+
return out
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _stage(spec: WorkflowSpec, settings: RunSettings) -> tuple[str, bool]:
|
|
312
|
+
from tempergraph.improve.promotion import stage_of
|
|
313
|
+
|
|
314
|
+
return stage_of(spec, settings.caller)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _context(spec: WorkflowSpec, task_id: str, root: Path, registry: Registry, settings: RunSettings,
|
|
318
|
+
judges: Mapping[str, str], log: RunLog, stop: StopRequest, watcher_box: dict[str, Any],
|
|
319
|
+
main: Path | None, settled: Settled) -> RunContext:
|
|
320
|
+
def drain() -> str | None:
|
|
321
|
+
w = watcher_box.get("w")
|
|
322
|
+
taken = w.check() if w is not None else None
|
|
323
|
+
if taken is not None:
|
|
324
|
+
if not watcher_box.get("logged"):
|
|
325
|
+
log.write("stop_requested", mode=taken.mode, caller=taken.caller)
|
|
326
|
+
watcher_box["logged"] = True
|
|
327
|
+
return "stopped_by_request"
|
|
328
|
+
return None
|
|
329
|
+
|
|
330
|
+
rv = settled.run
|
|
331
|
+
ctx = RunContext(spec=spec, task_id=task_id, state_root=root, registry=registry, log=log, judges=judges,
|
|
332
|
+
enforce_tools=bool(rv["enforce_tools"] or rv["strict_permissions"]), stop=stop,
|
|
333
|
+
drain_requested=drain, main_checkout=main, attempt_cap=int(rv["attempt_cap"]),
|
|
334
|
+
infra_tries=max(1, int(rv["infra_tries"])),
|
|
335
|
+
command_killed_retries=int(rv["command_killed_retries"]), backoff_max_s=int(rv["infra_backoff_max_s"]),
|
|
336
|
+
settings=rst.workflow_settings(settled.resolved), origin=settings.origin, judge_state=settings.judge_state,
|
|
337
|
+
escalation_record=settings.escalation_record,
|
|
338
|
+
stage=_stage(spec, settings)[0], self_check_limit=int(rv.get("self_check_limit") or 3),
|
|
339
|
+
audit_rate=float(rv.get("audit_rate") or 0.0), audit_executor=rv.get("audit_executor") or None,
|
|
340
|
+
audit_seed=settings.audit_seed,
|
|
341
|
+
read_worktreeinclude=bool(rv.get("worktree.read_worktreeinclude", True)))
|
|
342
|
+
if settings.sleep is not None:
|
|
343
|
+
ctx.sleep = settings.sleep
|
|
344
|
+
return ctx
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _observers(cap: rst.Capture) -> tuple[Any, list[str]]:
|
|
348
|
+
"""The observers the operator config names (EVT-B22, EVT-B23, EVT-B24); none is enabled by default."""
|
|
349
|
+
if not cap.observers:
|
|
350
|
+
return None, []
|
|
351
|
+
from tempergraph.run.events import ObserverHub, register_observers
|
|
352
|
+
|
|
353
|
+
found, missing = register_observers(names=cap.observers)
|
|
354
|
+
return (ObserverHub(found) if found else None), missing
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
FIXED_AT_START = frozenset({"run.workspace", "run.worktree.root", "run.worktree.base", "run.worktree.branch_prefix"})
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _observer_warnings(root: Path, settings: RunSettings) -> list[Finding]:
|
|
361
|
+
"""EVT-B23: the observers the operator config names that are not installed, as preflight warnings. Reads the
|
|
362
|
+
entry-point names only; the observers themselves are loaded once, per segment, by `_observers`."""
|
|
363
|
+
cap = rst.capture(rst.load_files(root, settings.home or home_path()))
|
|
364
|
+
if not cap.observers:
|
|
365
|
+
return []
|
|
366
|
+
from tempergraph.run import events as evmod
|
|
367
|
+
|
|
368
|
+
installed = {ep.name for ep in evmod.entry_points(group="tempergraph.observers")}
|
|
369
|
+
return observer_warnings(sorted(set(cap.observers) - installed))
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _dry_segment(settings: RunSettings, meta: Mapping[str, Any], settled: Settled, log_path: Path) -> bool:
|
|
373
|
+
"""LFS-B1, LFS-B3, EVT-B10: is the value in force for this segment a dry run, from any source?
|
|
374
|
+
|
|
375
|
+
The engine's own flag or a resolved `run.loop_dry_run` of `true` is one. A thread whose meta holds `dry_run` and
|
|
376
|
+
that has never had a value of the setting (no row now, none in its log) stays dry: that is a thread the engine
|
|
377
|
+
started dry or one written before the setting."""
|
|
378
|
+
if settings.dry_run or settled.run.get("loop_dry_run") is True:
|
|
379
|
+
return True
|
|
380
|
+
if not meta.get("dry_run"):
|
|
381
|
+
return False
|
|
382
|
+
if any(r.key == "run.loop_dry_run" for r in settled.resolved.rows):
|
|
383
|
+
return False
|
|
384
|
+
try:
|
|
385
|
+
with open(log_path, encoding="utf-8") as fh:
|
|
386
|
+
for line in fh:
|
|
387
|
+
if '"settings_resolved"' in line and '"run.loop_dry_run"' in line:
|
|
388
|
+
return False
|
|
389
|
+
except OSError:
|
|
390
|
+
pass
|
|
391
|
+
return True
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _drive(spec: WorkflowSpec, task_id: str, root: Path, registry: Registry, settings: RunSettings,
|
|
395
|
+
judges: Mapping[str, str], first_input: Any, settled: Settled, *,
|
|
396
|
+
before: Callable[[Any], None] | None = None, executors: Mapping[str, str] | None = None,
|
|
397
|
+
ruling_records: Sequence[Mapping[str, Any]] = (), rerun_of: Mapping[str, Any] | None = None,
|
|
398
|
+
workspace: Mapping[str, Any] | None = None, skip_breakpoint: str | None = None) -> RunOutcome:
|
|
399
|
+
"""Run the graph from `first_input` while holding the lock, then turn the thread state into an exit."""
|
|
400
|
+
tid = thread_id(spec.name, task_id)
|
|
401
|
+
stops = [flow.step_node(u) for u in settings.pause_before if u != skip_breakpoint] # FLX-B10
|
|
402
|
+
cap = rst.capture(rst.load_files(root, settings.home or home_path())) # operator config, per segment
|
|
403
|
+
hub, missing = _observers(cap)
|
|
404
|
+
log = RunLog(run_dir(root, spec.name, task_id) / "run.jsonl", observers=hub)
|
|
405
|
+
stop = StopRequest()
|
|
406
|
+
box: dict[str, Any] = {}
|
|
407
|
+
main = main_checkout(root.parent)
|
|
408
|
+
ctx = _context(spec, task_id, root, registry, settings, judges, log, stop, box, main, settled)
|
|
409
|
+
ctx.capture = cap
|
|
410
|
+
saver = open_saver(enginefile.checkpoint_of(root, spec.name, task_id))
|
|
411
|
+
try:
|
|
412
|
+
cw = compile_workflow(spec, EngineNodes(ctx), saver)
|
|
413
|
+
cfg = cw.config(tid)
|
|
414
|
+
if before is not None:
|
|
415
|
+
before(cw)
|
|
416
|
+
if callable(first_input): # an answer to one of several pending gates is addressed after `before`
|
|
417
|
+
first_input = first_input(cw)
|
|
418
|
+
meta = (((cw.graph.get_state(cfg).values or {}).get("run") or {}).get("meta") or {})
|
|
419
|
+
shape = diagram_model(spec)["digest"]
|
|
420
|
+
was = enginefile.last(enginefile.read(root, spec.name, task_id))
|
|
421
|
+
kids = children_of(spec) # SWF-B8: each child as it is registered now
|
|
422
|
+
try: # MIG-B8: the thread's engine record; never changes the run (OVR-B4)
|
|
423
|
+
moved = enginefile.record(root, spec, task_id, content_version=_content_version(spec),
|
|
424
|
+
shape_digest=shape, resumed=bool(meta),
|
|
425
|
+
children={u: {"workflow": c["workflow"], "workflow_version": c["content_version"],
|
|
426
|
+
"units": c["units"]} for u, c in kids.items()})
|
|
427
|
+
except OSError:
|
|
428
|
+
moved = None
|
|
429
|
+
sched = settings.schedule or meta.get("schedule") # TCK-B24: the fire this thread is, kept across resumes
|
|
430
|
+
log.write("run_started", origin=("schedule" if sched else settings.origin), caller=dict(settings.caller),
|
|
431
|
+
**({"schedule": dict(sched)} if sched else {}),
|
|
432
|
+
alias=aliases.alias_of(root, tid), label=settings.label or meta.get("label"),
|
|
433
|
+
engine_version=ENGINE_VERSION, shape_digest=shape, **({"moved_from": moved} if moved else {}),
|
|
434
|
+
**({"children": {u: {k: c[k] for k in ("workflow", "workflow_version", "content_version")}
|
|
435
|
+
for u, c in kids.items()}} if kids else {}),
|
|
436
|
+
workflow_version=spec.version, content_version=_content_version(spec), plan_digest=shape,
|
|
437
|
+
executors={"steps": dict(executors or {}), "judges": dict(judges)},
|
|
438
|
+
settings_digest=settled.resolved.digest, profiles=list(settled.options.profiles),
|
|
439
|
+
**({"rerun_of": dict(rerun_of)} if rerun_of else {}),
|
|
440
|
+
**({"dry_run": True} if _dry_segment(settings, meta, settled, log.path) else {}),
|
|
441
|
+
overridden_keys=rst.overridden_keys(settled.resolved),
|
|
442
|
+
**({"capture_lowered": cap.lowered()} if cap.lowered() else {}),
|
|
443
|
+
**({"observers": list(cap.observers), "observers_missing": missing} if cap.observers else {}))
|
|
444
|
+
rec: dict[str, Any] = {"settings_digest": settled.resolved.digest, "rows": rst.rows_json(settled.resolved),
|
|
445
|
+
"changed_keys": settled.changed, "stage": ctx.stage}
|
|
446
|
+
if _stage(spec, settings)[1]:
|
|
447
|
+
rec["unpromoted_pipeline"] = True
|
|
448
|
+
if settled.changed:
|
|
449
|
+
rec["caller"] = dict(settings.caller)
|
|
450
|
+
log.write("settings_resolved", **rec)
|
|
451
|
+
if moved and moved.get("workflow_version") and moved["workflow_version"] != _content_version(spec): # MIG-B15
|
|
452
|
+
log.write("workflow_changed", from_version=moved.get("workflow_version"),
|
|
453
|
+
to_version=_content_version(spec), units=enginefile.changed_units(was, spec))
|
|
454
|
+
for unit, now in kids.items(): # SWF-B3: one record per child whose version changed under a paused parent
|
|
455
|
+
held = (was.get("children") or {}).get(unit) or {}
|
|
456
|
+
if held.get("workflow_version") and held["workflow_version"] != now["content_version"]:
|
|
457
|
+
log.write("workflow_changed", child=unit, from_version=held["workflow_version"],
|
|
458
|
+
to_version=now["content_version"], units=enginefile.changed_units(held, now["spec"]))
|
|
459
|
+
if workspace:
|
|
460
|
+
workspace_record(log, workspace)
|
|
461
|
+
for r in ruling_records:
|
|
462
|
+
log.write("ruling", **r)
|
|
463
|
+
for g in settled.grant_changes():
|
|
464
|
+
log.write("grant", unit=g["unit"], capability=g.get("capability"), prefix=g.get("prefix"),
|
|
465
|
+
action=g["action"], answers=_answers(log.path, g), by=dict(settings.caller), via=settings.origin)
|
|
466
|
+
outcome: RunOutcome
|
|
467
|
+
with StopWatcher(root, spec.name, task_id, stop, poll_s=1.0) as watcher:
|
|
468
|
+
box["w"] = watcher
|
|
469
|
+
try:
|
|
470
|
+
cw.graph.invoke(first_input, cfg, **({"interrupt_before": stops} if stops else {}))
|
|
471
|
+
outcome = _settle(cw, cfg, spec, task_id, root, stops, log,
|
|
472
|
+
cleanup=str(settled.run.get("worktree.cleanup") or "never"))
|
|
473
|
+
except Drain as d:
|
|
474
|
+
code = ExitCode.BUDGET_OR_INFRA if d.reason == "cost_cap" else ExitCode.STOPPED
|
|
475
|
+
outcome = RunOutcome(exit_code=code, reason=d.reason, thread_id=tid,
|
|
476
|
+
message=f"{tid} stopped at a boundary ({d.reason}); resume continues it")
|
|
477
|
+
final = cw.graph.get_state(cfg).values or {}
|
|
478
|
+
if outcome.exit_code is ExitCode.FINISHED and (final.get("workspace") or {}).get("state") in (
|
|
479
|
+
"released", "removed"):
|
|
480
|
+
workspace_record(log, final["workspace"])
|
|
481
|
+
cost = CostTotals.from_json((final.get("run") or {}).get("cost"))
|
|
482
|
+
inside = subrun.pending_cost(cw, tid) # SWF-B4: a child stopped or paused in has not handed its spend back
|
|
483
|
+
if inside is not None and inside.sessions > cost.sessions:
|
|
484
|
+
cost = inside
|
|
485
|
+
orec = outcome_record.build(spec, final, log.path)
|
|
486
|
+
if orec is not None and orec["verdict"] != "not_reached":
|
|
487
|
+
log.write("outcome", **orec) # OUT-B18, OUT-B19; a thread's latest `outcome` record is its record
|
|
488
|
+
sup = supervision.build(root / "ledger.jsonl", log.path, tid, supervision.path_units(final))
|
|
489
|
+
log.write("supervision", **sup) # SUP-B10, before run_exit
|
|
490
|
+
degraded = (final.get("run") or {}).get("degraded") or None # FLX-B9: a fallback was taken
|
|
491
|
+
deg = {"degraded": True, "degraded_unit": degraded.get("unit")} if degraded else {}
|
|
492
|
+
outcome.degraded = bool(degraded)
|
|
493
|
+
capped: dict[str, Any] = {}
|
|
494
|
+
if outcome.reason == "attempt_cap": # CMP-B20: the exit says what repeated
|
|
495
|
+
capped = ctx.report()
|
|
496
|
+
outcome.payload = {**(outcome.payload or {}), **capped}
|
|
497
|
+
log.write("run_exit", exit_code=int(outcome.exit_code), reason=outcome.reason, cost=cost.to_json(),
|
|
498
|
+
cost_so_far=cost_so_far(cost.to_json()), **deg, **capped)
|
|
499
|
+
mark_ws = final.get("workspace") or {}
|
|
500
|
+
if outcome.exit_code in (ExitCode.PAUSED, ExitCode.STOPPED) and mark_ws.get("mode") == "worktree" \
|
|
501
|
+
and mark_ws.get("path") and Path(str(mark_ws["path"])).exists():
|
|
502
|
+
try: # WTR-B28: what the resume compares the worktree with
|
|
503
|
+
write_pause_mark(pause_mark_file(root, spec.name, task_id), Path(str(mark_ws["path"])))
|
|
504
|
+
except OSError:
|
|
505
|
+
log.write("engine_error", scope="pause_workspace", error="OSError")
|
|
506
|
+
try:
|
|
507
|
+
write_json(exit_file(root, spec.name, task_id), {"schema_version": 1,
|
|
508
|
+
"exit_code": int(outcome.exit_code),
|
|
509
|
+
"reason": outcome.reason, **deg})
|
|
510
|
+
except OSError as exc: # OBS-B3: logging never changes the exit; one record of the failure is attempted
|
|
511
|
+
log.write("engine_error", scope="exit_file", error=type(exc).__name__)
|
|
512
|
+
ledger = Ledger(path=root / "ledger.jsonl")
|
|
513
|
+
try: # FIN-B11: a failure to build the record leaves the field out and never changes the exit
|
|
514
|
+
from tempergraph.run.finalize import recorded_pull_request
|
|
515
|
+
|
|
516
|
+
wpath = (final.get("workspace") or {}).get("path")
|
|
517
|
+
pr = recorded_pull_request(final.get("finalized"), Path(wpath) if wpath else None)
|
|
518
|
+
except Exception: # noqa: BLE001
|
|
519
|
+
pr = None
|
|
520
|
+
ledger.append({"kind": "run_segment", "thread_id": tid, "workflow": spec.name,
|
|
521
|
+
"workflow_version": spec.version, **join_keys(root, settings),
|
|
522
|
+
**({"pull_request": pr} if pr else {}),
|
|
523
|
+
"exit_code": int(outcome.exit_code), "reason": outcome.reason,
|
|
524
|
+
"cost": cost.to_json(), "origin": settings.origin, "stage": _stage(spec, settings)[0],
|
|
525
|
+
**({"schedule_id": settings.schedule["schedule_id"]} if settings.schedule else {}),
|
|
526
|
+
"settings_digest": settled.resolved.digest, **deg,
|
|
527
|
+
"overridden_keys": rst.overridden_keys(settled.resolved),
|
|
528
|
+
"grants": _grants_used(spec, registry, settled, final),
|
|
529
|
+
"supervision": sup, **({"outcome": orec} if orec is not None else {})})
|
|
530
|
+
for unit, kid in ((final.get("run") or {}).get("children") or {}).items():
|
|
531
|
+
# SWF-B9: the outcome record of a child that ran inside this thread counts in the child's own measures. It is
|
|
532
|
+
# no run segment of the child and no folder of its own: the thread, the log and the `run_segment` row are the parent's
|
|
533
|
+
if isinstance(kid, Mapping) and kid.get("outcome"):
|
|
534
|
+
ledger.append({"kind": "child_outcome", "thread_id": tid, "workflow": kid.get("workflow"),
|
|
535
|
+
"workflow_version": kid.get("version"), "parent": spec.name, "child": unit,
|
|
536
|
+
**join_keys(root, settings), "origin": f"{outcome_record.CHILD_ORIGIN}{spec.name}",
|
|
537
|
+
"outcome": kid["outcome"]})
|
|
538
|
+
if ledger.failures:
|
|
539
|
+
log.write("engine_error", scope="ledger", error="write_failed")
|
|
540
|
+
try: # SIL-B8: every exit is recorded, no model call; never changes the exit (OVR-B4)
|
|
541
|
+
from tempergraph.improve.record import record_exit
|
|
542
|
+
|
|
543
|
+
seg_row = next((r for r in reversed(ledger_rows(root)) if r.get("kind") == "run_segment"
|
|
544
|
+
and r.get("thread_id") == tid), None)
|
|
545
|
+
if seg_row is not None:
|
|
546
|
+
summary = record_exit(root, spec, task_id, log.path, final, seg_row)
|
|
547
|
+
from tempergraph.improve.reliability import after_exit
|
|
548
|
+
|
|
549
|
+
summary["labels"] = after_exit(root, spec.name, task_id, seg_row) # FBK-B9, FBK-B14
|
|
550
|
+
log.write("finding_recorded", **summary)
|
|
551
|
+
hand_to_loop(root, spec, task_id, tid, summary, settings, registry, judges,
|
|
552
|
+
operator_review=settled.run.get("session_review"),
|
|
553
|
+
run_cost_usd=cost.reported + cost.estimated_only,
|
|
554
|
+
daily_cap_usd=settled.run.get("daily_cap_usd"), loop_model=settled.run.get("loop_model"),
|
|
555
|
+
loop_effort=settled.run.get("loop_effort"), options=settled.options,
|
|
556
|
+
base_branch=str((final.get("workspace") or {}).get("base_branch") or ""))
|
|
557
|
+
except Exception as exc: # noqa: BLE001
|
|
558
|
+
log.write("engine_error", scope="improve", error=type(exc).__name__)
|
|
559
|
+
outcome.thread_id = tid
|
|
560
|
+
outcome.auto_reopen = int(settled.run.get("auto_reopen") or 0)
|
|
561
|
+
return outcome
|
|
562
|
+
finally:
|
|
563
|
+
saver.conn.close()
|
|
564
|
+
if hub is not None:
|
|
565
|
+
hub.close()
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def hand_to_loop(root: Path, spec: WorkflowSpec, task_id: str, tid: str, summary: Mapping[str, Any],
|
|
569
|
+
settings: RunSettings | None, registry: Registry, judges: Mapping[str, str], *,
|
|
570
|
+
operator_review: str | None = None, run_cost_usd: float = 0.0, daily_cap_usd: float | None = None,
|
|
571
|
+
loop_model: str | None = None, loop_effort: str | None = None, trigger: str | None = None,
|
|
572
|
+
options: RunOptions | None = None, base_branch: str = "") -> None:
|
|
573
|
+
"""SIL-B1: hand the judged lenses to the detached loop child; `TEMPERGRAPH_LOOP=inline|off` for tests.
|
|
574
|
+
`settings` is None for an exit no run of this process made (SIL-B29): not a trial, `--dry-run` read from the log.
|
|
575
|
+
`options` is the thread's snapshot: resolved again against the settings files now, it gives the operator's
|
|
576
|
+
`loop_autonomy` (PRP-B31)."""
|
|
577
|
+
from tempergraph.improve import child
|
|
578
|
+
|
|
579
|
+
if child.mode() == "off" or spec.builtin:
|
|
580
|
+
return
|
|
581
|
+
held: str | None = None
|
|
582
|
+
issue_cap = 3 # ICAP-B2: the cap in force at this exit; 3 when the settings cannot be resolved
|
|
583
|
+
if options is not None:
|
|
584
|
+
try: # as `status` resolves a snapshot (RST-B27): a files error or any failure leaves the setting unread
|
|
585
|
+
files = rst.load_files(root, (settings.home if settings else None) or home_path())
|
|
586
|
+
if not files.errors:
|
|
587
|
+
values = rst.run_values(rst.resolve(spec, options, files))
|
|
588
|
+
got = values.get("loop_autonomy")
|
|
589
|
+
held = str(got) if got else None
|
|
590
|
+
cap = values.get("loop_issue_cap")
|
|
591
|
+
issue_cap = cap if isinstance(cap, int) and not isinstance(cap, bool) and 0 <= cap <= 50 else 3
|
|
592
|
+
except Exception: # noqa: BLE001 - the hold is best effort; the loop never stops a run
|
|
593
|
+
held = None
|
|
594
|
+
issue_cap = 3
|
|
595
|
+
names = list(judges.values())
|
|
596
|
+
executor = max(set(names), key=names.count) if names else spec.default_executor
|
|
597
|
+
# LFS-B1, LFS-B3, LFS-B5: the thread's value of `run.loop_dry_run` (its snapshot, no file read), else the legacy rule
|
|
598
|
+
value, layer = False, ""
|
|
599
|
+
if options is not None:
|
|
600
|
+
try:
|
|
601
|
+
res = rst.resolve(spec, options)
|
|
602
|
+
value = res.values.get("run.loop_dry_run") is True
|
|
603
|
+
layer = next((r.layer for r in res.rows if r.key == "run.loop_dry_run"), "")
|
|
604
|
+
except Exception: # noqa: BLE001 - best effort: an unreadable snapshot leaves the setting unread
|
|
605
|
+
value, layer = False, ""
|
|
606
|
+
legacy = (settings is not None and settings.dry_run) or legacy_dry_run(run_dir(root, spec.name, task_id) / "run.jsonl")
|
|
607
|
+
dry = value or legacy
|
|
608
|
+
source = ("argument" if layer in ("flag",) else "settings" if layer in rst.OPERATOR_LAYERS
|
|
609
|
+
else "workflow" if layer.startswith("workflow:") else "default")
|
|
610
|
+
if dry and not value:
|
|
611
|
+
source = "argument" # the engine's own flag or a log written before the setting
|
|
612
|
+
lift = layer == "flag" and not value
|
|
613
|
+
if child.hand_off(root, spec, task_id, tid, summary, dry_run=dry, judge_executor=executor,
|
|
614
|
+
dry_source=source, lift=lift,
|
|
615
|
+
operator_review=operator_review, run_cost_usd=run_cost_usd,
|
|
616
|
+
trial=settings is not None and settings.origin == "trial", daily_cap_usd=daily_cap_usd,
|
|
617
|
+
loop_model=loop_model, loop_effort=loop_effort, trigger=trigger, loop_autonomy=held,
|
|
618
|
+
issue_cap=issue_cap, base_branch=base_branch) is None:
|
|
619
|
+
return
|
|
620
|
+
if child.mode() == "inline":
|
|
621
|
+
child.drain(registry=registry)
|
|
622
|
+
else:
|
|
623
|
+
child.launch()
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _record_stop(root: Path, spec: WorkflowSpec, task_id: str, log: RunLog, values: Mapping[str, Any],
|
|
627
|
+
registry: Registry, settings: RunSettings, settled: Settled, judges: Mapping[str, str]) -> None:
|
|
628
|
+
"""SIL-B27: a person's stop before a unit is an exit with code 4 and reason `person`: its ledger row, the records of
|
|
629
|
+
SIL-B8 and the hand-off to the loop. The stop has no segment of its own, so the records it covers are those written
|
|
630
|
+
after the paused segment's `run_exit` (the paused segment's findings were derived when it paused). Never changes
|
|
631
|
+
the stop's result (OVR-B4)."""
|
|
632
|
+
tid = thread_id(spec.name, task_id)
|
|
633
|
+
try:
|
|
634
|
+
cost = CostTotals.from_json((values.get("run") or {}).get("cost"))
|
|
635
|
+
ledger = Ledger(path=root / "ledger.jsonl")
|
|
636
|
+
ledger.append({"kind": "run_segment", "thread_id": tid, "workflow": spec.name,
|
|
637
|
+
"workflow_version": spec.version, **join_keys(root, settings),
|
|
638
|
+
"exit_code": int(ExitCode.STOPPED), "reason": "person",
|
|
639
|
+
"cost": cost.to_json(), "origin": settings.origin, "stage": _stage(spec, settings)[0],
|
|
640
|
+
**({"schedule_id": settings.schedule["schedule_id"]} if settings.schedule else {}),
|
|
641
|
+
"settings_digest": settled.resolved.digest,
|
|
642
|
+
"overridden_keys": rst.overridden_keys(settled.resolved),
|
|
643
|
+
"grants": _grants_used(spec, registry, settled, values)})
|
|
644
|
+
if ledger.failures:
|
|
645
|
+
log.write("engine_error", scope="ledger", error="write_failed")
|
|
646
|
+
from tempergraph.improve.record import record_exit
|
|
647
|
+
|
|
648
|
+
records = _log_records(log.path)
|
|
649
|
+
after = max((i for i, r in enumerate(records) if r.get("kind") == "run_exit"), default=-1) + 1
|
|
650
|
+
seg_row = next((r for r in reversed(ledger_rows(root)) if r.get("kind") == "run_segment"
|
|
651
|
+
and r.get("thread_id") == tid), None)
|
|
652
|
+
if seg_row is not None:
|
|
653
|
+
summary = record_exit(root, spec, task_id, log.path, values, seg_row, seg=records[after:])
|
|
654
|
+
from tempergraph.improve.reliability import after_exit
|
|
655
|
+
|
|
656
|
+
summary["labels"] = after_exit(root, spec.name, task_id, seg_row)
|
|
657
|
+
log.write("finding_recorded", **summary)
|
|
658
|
+
hand_to_loop(root, spec, task_id, tid, summary, settings, registry, judges,
|
|
659
|
+
operator_review=settled.run.get("session_review"),
|
|
660
|
+
run_cost_usd=cost.reported + cost.estimated_only,
|
|
661
|
+
daily_cap_usd=settled.run.get("daily_cap_usd"), loop_model=settled.run.get("loop_model"),
|
|
662
|
+
loop_effort=settled.run.get("loop_effort"), options=settled.options,
|
|
663
|
+
base_branch=str((values.get("workspace") or {}).get("base_branch") or ""))
|
|
664
|
+
except Exception as exc: # noqa: BLE001
|
|
665
|
+
log.write("engine_error", scope="improve", error=type(exc).__name__)
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def _log_records(path: Path) -> list[dict[str, Any]]:
|
|
669
|
+
out: list[dict[str, Any]] = []
|
|
670
|
+
try:
|
|
671
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
672
|
+
except OSError:
|
|
673
|
+
return out
|
|
674
|
+
for ln in lines:
|
|
675
|
+
with contextlib.suppress(ValueError):
|
|
676
|
+
r = json.loads(ln)
|
|
677
|
+
if isinstance(r, dict):
|
|
678
|
+
out.append(r)
|
|
679
|
+
return out
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def ledger_rows(root: Path) -> list[dict[str, Any]]:
|
|
683
|
+
out: list[dict[str, Any]] = []
|
|
684
|
+
try:
|
|
685
|
+
lines = (root / "ledger.jsonl").read_text(encoding="utf-8").splitlines()
|
|
686
|
+
except OSError:
|
|
687
|
+
return out
|
|
688
|
+
for ln in lines:
|
|
689
|
+
with contextlib.suppress(ValueError):
|
|
690
|
+
r = json.loads(ln)
|
|
691
|
+
if isinstance(r, dict):
|
|
692
|
+
out.append(r)
|
|
693
|
+
return out
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def join_keys(root: Path, settings: RunSettings) -> dict[str, Any]:
|
|
697
|
+
"""IMD-B5: the pseudonymous machine id and repository digest every ledger row carries."""
|
|
698
|
+
from tempergraph import identity
|
|
699
|
+
|
|
700
|
+
return {"machine": identity.machine_id(settings.home), "repo": identity.repo_id(main_checkout(root.parent))}
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def workspace_record(log: RunLog, ws: Mapping[str, Any]) -> None:
|
|
704
|
+
"""EVT-B10 to EVT-B16 `workspace`: prepared, reused, attached, external_change or kept (WTR-B22, WTR-B26).
|
|
705
|
+
|
|
706
|
+
The path goes to the local run log only; the ledger and exports never carry it.
|
|
707
|
+
"""
|
|
708
|
+
boot = ws.get("bootstrap") or {}
|
|
709
|
+
counts = {k: boot[k] for k in ("external_commits", "external_changed") if k in boot}
|
|
710
|
+
if ws.get("cleanup"): # WTR-B22: `released`, then `removed` or `kept` with the reason, one per worktree
|
|
711
|
+
log.write("workspace", action="released", mode=ws.get("mode"), resolved_by=ws.get("resolved_by"),
|
|
712
|
+
branch=ws.get("branch") or None, base_commit=ws.get("base_commit") or None,
|
|
713
|
+
reason=ws.get("requested"), counts=counts, path=ws.get("path"))
|
|
714
|
+
for c in ws["cleanup"]:
|
|
715
|
+
log.write("workspace", action=c["result"], mode=ws.get("mode"), resolved_by=ws.get("resolved_by"),
|
|
716
|
+
branch=ws.get("branch") or None, base_commit=ws.get("base_commit") or None,
|
|
717
|
+
reason=c.get("reason") or None, counts=counts, path=c.get("path"))
|
|
718
|
+
return
|
|
719
|
+
log.write("workspace", action=ws.get("action") or "prepared", mode=ws.get("mode"),
|
|
720
|
+
resolved_by=ws.get("resolved_by"), branch=ws.get("branch") or None,
|
|
721
|
+
base_commit=ws.get("base_commit") or None, reason=ws.get("requested"), counts=counts,
|
|
722
|
+
path=ws.get("path"))
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def breakpoint_file(root: Path, workflow: str, task_id: str) -> Path:
|
|
726
|
+
return run_dir(root, workflow, task_id) / "breakpoint.json" # read by `durability.status.breakpoint_at`
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def _settle(cw: Any, cfg: Mapping[str, Any], spec: WorkflowSpec, task_id: str, root: Path,
|
|
730
|
+
stops: Sequence[str] = (), log: RunLog | None = None, cleanup: str = "never") -> RunOutcome:
|
|
731
|
+
snap = snapshot(cw, cfg["configurable"]["thread_id"])
|
|
732
|
+
state = classify_snapshot(snap, lock_held=False)
|
|
733
|
+
tid = cfg["configurable"]["thread_id"]
|
|
734
|
+
at = next((n for n in snap.next if n in stops), None) if state is ThreadState.UNFINISHED else None
|
|
735
|
+
if at is not None: # FLX-B10: nothing of the unit ran; no session and no attempt record
|
|
736
|
+
unit = at.rsplit(".", 1)[0]
|
|
737
|
+
u = spec.units.get(unit)
|
|
738
|
+
prompt = u.step.prompt if u is not None and u.step is not None else None
|
|
739
|
+
words = ["proceed", "stop"]
|
|
740
|
+
payload: Any = {"kind": "breakpoint", "unit": unit, "item": None, "reason": "breakpoint", "decisions": words,
|
|
741
|
+
"prompt": str(getattr(prompt, "path", "") or "inline") if prompt is not None else None,
|
|
742
|
+
"resume": gatemod.resume_command(spec, task_id, words)}
|
|
743
|
+
write_json(breakpoint_file(root, spec.name, task_id), {"schema_version": 1, **payload})
|
|
744
|
+
if log is not None:
|
|
745
|
+
log.write("pause", unit=unit, item=None, pause_kind="breakpoint", decisions=words,
|
|
746
|
+
resume=payload["resume"], reason="breakpoint",
|
|
747
|
+
cost_so_far=cost_so_far((snap.values.get("run") or {}).get("cost")))
|
|
748
|
+
return RunOutcome(exit_code=ExitCode.PAUSED, reason="breakpoint", payload=payload,
|
|
749
|
+
message=f"{tid} is paused before {unit}")
|
|
750
|
+
if state is ThreadState.PAUSED:
|
|
751
|
+
payload = snap.interrupts[0][1] if snap.interrupts else None
|
|
752
|
+
return RunOutcome(exit_code=ExitCode.PAUSED, reason=str((payload or {}).get("kind", "escalation")),
|
|
753
|
+
payload=payload, message=f"{tid} is waiting for a person")
|
|
754
|
+
if state is ThreadState.FINISHED:
|
|
755
|
+
ws = snap.values.get("workspace") or {}
|
|
756
|
+
fin = snap.values.get("finalized") or {}
|
|
757
|
+
if ws: # WTR-B22, WTR-B23: unlock, and under `cleanup: on_finish` remove what is clean (never on `error`)
|
|
758
|
+
rec = release_workspace(WorkspaceRecord.from_json(ws), cleanup, root, outcome=str(fin.get("outcome", "")))
|
|
759
|
+
cw.graph.update_state(cfg, {"workspace": rec.to_json()}, as_node=flow.FINALIZER)
|
|
760
|
+
return RunOutcome(exit_code=ExitCode.FINISHED, reason=str(fin.get("outcome", "finished")),
|
|
761
|
+
message=f"{tid} finished")
|
|
762
|
+
stopped = (snap.values.get("run") or {}).get("stopped") or {}
|
|
763
|
+
reason = str(stopped.get("reason", "stopped"))
|
|
764
|
+
return RunOutcome(exit_code=STOP_EXIT.get(reason, ExitCode.STOPPED), reason=reason,
|
|
765
|
+
message=f"{tid} stopped at {stopped.get('unit')} ({reason})")
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def start(spec: WorkflowSpec, task_id: str, inputs: Mapping[str, str], target: Path, registry: Registry,
|
|
769
|
+
settings: RunSettings | None = None) -> RunOutcome:
|
|
770
|
+
settings = settings or RunSettings()
|
|
771
|
+
return _reopening(_start(spec, task_id, inputs, target, registry, settings), spec, task_id, target, registry,
|
|
772
|
+
settings)
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def _bad_breakpoint(spec: WorkflowSpec, settings: RunSettings) -> RunOutcome | None:
|
|
776
|
+
"""FLX-B11: `--pause-before` naming a unit the workflow does not have is refused before spend."""
|
|
777
|
+
for name in settings.pause_before:
|
|
778
|
+
if name in spec.units or name == flow.OUTCOME_UNIT and spec.outcome is not None:
|
|
779
|
+
continue
|
|
780
|
+
if name.split(".", 1)[0] in spec.units:
|
|
781
|
+
return _refuse("not_in_release", f"--pause-before {name}: a breakpoint on one item of a map is not "
|
|
782
|
+
"built in this release; name the unit")
|
|
783
|
+
return _refuse("breakpoint_unknown", f"--pause-before {name}: the workflow has no such unit")
|
|
784
|
+
return None
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def needs_git(spec: WorkflowSpec, settings: RunSettings) -> list[str]:
|
|
788
|
+
"""WSP-B15 to WSP-B18: what a run outside a git repository cannot use; empty when it can start."""
|
|
789
|
+
out: list[str] = []
|
|
790
|
+
if settings.carry:
|
|
791
|
+
out.append("--carry (run state on a branch)")
|
|
792
|
+
out += subworkflow.unit_reasons(spec) # the risk rule, the `changed_paths` measure and each writer branch (WSP-B18)
|
|
793
|
+
out += subworkflow.needs_git(spec) # SWF-B6: a child, or a child of a child, that needs git
|
|
794
|
+
return out
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
def _start(spec: WorkflowSpec, task_id: str, inputs: Mapping[str, str], target: Path, registry: Registry,
|
|
798
|
+
settings: RunSettings) -> RunOutcome:
|
|
799
|
+
tid = thread_id(spec.name, task_id)
|
|
800
|
+
bad = _bad_breakpoint(spec, settings)
|
|
801
|
+
if bad is not None:
|
|
802
|
+
return bad
|
|
803
|
+
try:
|
|
804
|
+
root = _root(target)
|
|
805
|
+
except NotInRepository as exc:
|
|
806
|
+
return _refuse("not_git", str(exc))
|
|
807
|
+
if classify(root, spec, task_id) is not ThreadState.NONE:
|
|
808
|
+
return _refuse("thread_exists", f"{tid} already exists; resume it with `tempergraph resume {spec.name} "
|
|
809
|
+
f"{task_id}` or start a new thread with another task id", tid=tid)
|
|
810
|
+
try:
|
|
811
|
+
settings = decided(settings, deciding=any(rst.is_widening(k) for k in settings.all_flags()),
|
|
812
|
+
words=("grant",))
|
|
813
|
+
settled = settle_start(spec, settings, root)
|
|
814
|
+
except SettingsRefused as exc:
|
|
815
|
+
return _refuse_settings(exc, tid)
|
|
816
|
+
rv = settled.run
|
|
817
|
+
spec = settled.spec
|
|
818
|
+
rep = preflight(spec, registry, enforce_tools=bool(rv["enforce_tools"]),
|
|
819
|
+
strict_permissions=bool(rv["strict_permissions"]))
|
|
820
|
+
rep.warnings.extend(_observer_warnings(root, settings)) # EVT-B23: a missing observer warns, the run starts
|
|
821
|
+
if not rep.ok:
|
|
822
|
+
first = rep.refusals[0]
|
|
823
|
+
return _refuse(first.code, f"{first.unit or spec.name}: {first.message}",
|
|
824
|
+
[f"{f.code}: {f.unit}: {f.message}" for f in rep.refusals], tid)
|
|
825
|
+
spec = with_outcome(spec)
|
|
826
|
+
try:
|
|
827
|
+
plan = resolve_workspace(spec, target, rv["workspace"], task_id=task_id,
|
|
828
|
+
prefix=str(rv["worktree.branch_prefix"]), base=str(rv.get("worktree.base") or "head"),
|
|
829
|
+
root=str(rv.get("worktree.root") or "sibling"))
|
|
830
|
+
except WorkspaceRefused as exc:
|
|
831
|
+
return _refuse(exc.word, str(exc), tid=tid)
|
|
832
|
+
if spec.input.kind == "file" and plan.base_ref not in ("head", "") and plan.main is not None:
|
|
833
|
+
err = file_missing_at_base(plan.main, plan.base_commit, plan.base_ref, inputs.get("file", ""))
|
|
834
|
+
if err:
|
|
835
|
+
return _refuse("request_missing_at_base", err, tid=tid)
|
|
836
|
+
if plan.main is None: # WSP-B15 to WSP-B18: what needs git is refused before anything is created
|
|
837
|
+
needs = needs_git(spec, settings)
|
|
838
|
+
if needs:
|
|
839
|
+
return _refuse("needs_git", f"outside a git repository this run cannot use {needs[0]}",
|
|
840
|
+
[f"needs_git: {n}" for n in needs], tid)
|
|
841
|
+
guarded = any(u.gate is not None and u.gate.judge is not None for u in spec.units.values())
|
|
842
|
+
if guarded and manifestmod.count_over(plan.path):
|
|
843
|
+
return _refuse("workspace_too_large", f"{plan.path} holds more than {manifestmod.MAX_FILES} files; "
|
|
844
|
+
"outside git the guard cannot watch it for a read-only session", tid=tid)
|
|
845
|
+
carry_remote = None
|
|
846
|
+
if settings.carry: # CAR-B5, CAR-B8, CAR-B11, CAR-B6: refused at start without a remote, before anything is created
|
|
847
|
+
try:
|
|
848
|
+
carry_remote = carrymod.remote_of(root.parent)
|
|
849
|
+
except carrymod.CarryRefused as exc:
|
|
850
|
+
return _refuse(exc.code, str(exc), tid=tid)
|
|
851
|
+
ensure_state_root(root)
|
|
852
|
+
lock = RunLock(lock_path(root, spec.name, task_id))
|
|
853
|
+
try:
|
|
854
|
+
lock.acquire()
|
|
855
|
+
except LockHeld:
|
|
856
|
+
return _refuse("running", f"{tid} is running", tid=tid)
|
|
857
|
+
try:
|
|
858
|
+
if settings.alias:
|
|
859
|
+
try:
|
|
860
|
+
aliases.claim(root, settings.alias, tid, lambda t: _live(root, spec, t))
|
|
861
|
+
except (aliases.AliasTaken, aliases.AliasInvalid) as exc:
|
|
862
|
+
return _refuse("alias", str(exc), tid=tid)
|
|
863
|
+
try:
|
|
864
|
+
rec = prepare_workspace(tid, plan, spec.worktree, root,
|
|
865
|
+
read_include=bool(rv["worktree.read_worktreeinclude"]))
|
|
866
|
+
except WorkspaceRefused as exc:
|
|
867
|
+
return _refuse(exc.word, str(exc), tid=tid)
|
|
868
|
+
if carry_remote:
|
|
869
|
+
carrymod.set_marker(root, spec.name, task_id, on=True, remote=carry_remote, state="on")
|
|
870
|
+
if plan.main is None: # the thread's first manifest: what `changed_paths` is measured against
|
|
871
|
+
with contextlib.suppress(OSError, manifestmod.TooManyFiles):
|
|
872
|
+
write_json(run_dir(root, spec.name, task_id) / "manifest.json",
|
|
873
|
+
{"schema_version": 1, "files": {k: list(v) for k, v in manifestmod.scan(plan.path).items()}})
|
|
874
|
+
RunLog(run_dir(root, spec.name, task_id) / "run.jsonl").write(
|
|
875
|
+
"task", chars=sum(len(v) for v in inputs.values()), request=clip(scrub(inputs.get("request", "")), 200))
|
|
876
|
+
initial = {"request": {"task_id": task_id, "inputs": dict(inputs)}, "workspace": rec.to_json(),
|
|
877
|
+
"run": {"meta": {"origin": settings.origin, "label": clip(scrub(settings.label or ""), 80) or None,
|
|
878
|
+
**({"schedule": dict(settings.schedule)} if settings.schedule else {}),
|
|
879
|
+
**({"dry_run": True} if settings.dry_run else {})},
|
|
880
|
+
"options": settled.snapshot_json()}}
|
|
881
|
+
out = _drive(spec, task_id, root, registry, settings, rep.judges, initial, settled,
|
|
882
|
+
executors=rep.step_executors, workspace=rec.to_json())
|
|
883
|
+
fetch = ([f"base_fetch: failed; the worktree starts from the local copy of {rec.base_branch}"]
|
|
884
|
+
if rec.base_fetch == "failed" else []) # WTR-B21, WTR-B7
|
|
885
|
+
out.warnings = list(plan.warnings) + fetch + [f"{w.code}: {w.message}" for w in rep.warnings]
|
|
886
|
+
return _carry_exit(root, spec, task_id, settings, out)
|
|
887
|
+
finally:
|
|
888
|
+
lock.release()
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def _carry_exit(root: Path, spec: WorkflowSpec, task_id: str, settings: RunSettings, out: RunOutcome) -> RunOutcome:
|
|
892
|
+
"""CAR-B8, CAR-B3: push the new state at a pause or an unfinished exit, delete the branch at the finish. The
|
|
893
|
+
exit never changes (OVR-B4); what is left to do is a warning and the thread's carry record."""
|
|
894
|
+
try:
|
|
895
|
+
warn = carrymod.after_exit(root, root.parent, spec.name, task_id, exit_code=int(out.exit_code),
|
|
896
|
+
workflow_version=_content_version(spec),
|
|
897
|
+
machine=join_keys(root, settings)["machine"])
|
|
898
|
+
except Exception as exc: # noqa: BLE001
|
|
899
|
+
warn = f"carry: failed ({type(exc).__name__})"
|
|
900
|
+
if warn:
|
|
901
|
+
out.warnings.append(warn)
|
|
902
|
+
return out
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def _live(root: Path, spec: WorkflowSpec, tid: str) -> bool:
|
|
906
|
+
w, _, task = tid.partition("/")
|
|
907
|
+
if w != spec.name:
|
|
908
|
+
return is_held(lock_path(root, w, task))
|
|
909
|
+
return classify(root, spec, task) not in (ThreadState.FINISHED, ThreadState.NONE)
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def resume(spec: WorkflowSpec, task_id: str, target: Path, registry: Registry, *, decision: str | None = None,
|
|
913
|
+
feedback: str | None = None, settings: RunSettings | None = None) -> RunOutcome:
|
|
914
|
+
settings = settings or RunSettings()
|
|
915
|
+
out = _resume(spec, task_id, target, registry, decision=decision, feedback=feedback, settings=settings)
|
|
916
|
+
return _reopening(out, spec, task_id, target, registry, settings)
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
# BUD-B6: the stop reasons an automatic re-open answers (spent retries, a step timeout or an infra failure).
|
|
920
|
+
REOPEN_REASONS = frozenset({"budget", "infra"})
|
|
921
|
+
ENGINE_CALLER: Mapping[str, Any] = {"kind": "engine", "confidence": "attested", "decided_by": "engine",
|
|
922
|
+
"relay": "none", "host": "engine", "host_session": None, "caller_app": None,
|
|
923
|
+
"parent": None, "schedule": None, "trace_id": None, "evidence": []}
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
def _reopens(root: Path, tid: str) -> int:
|
|
927
|
+
path = root / "ledger.jsonl"
|
|
928
|
+
try:
|
|
929
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
930
|
+
except OSError:
|
|
931
|
+
return 0
|
|
932
|
+
n = 0
|
|
933
|
+
for ln in lines:
|
|
934
|
+
with contextlib.suppress(ValueError):
|
|
935
|
+
r = json.loads(ln)
|
|
936
|
+
n += isinstance(r, dict) and r.get("kind") == "intervention" and r.get("thread_id") == tid \
|
|
937
|
+
and r.get("cause") == "auto_reopen"
|
|
938
|
+
return n
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
def _reopening(out: RunOutcome, spec: WorkflowSpec, task_id: str, target: Path, registry: Registry,
|
|
942
|
+
settings: RunSettings) -> RunOutcome:
|
|
943
|
+
"""BUD-B6: re-open a stopped run at most `run.auto_reopen` times on the thread, as a retry given in advance.
|
|
944
|
+
|
|
945
|
+
Never answers a pause, never undoes a person's stop or a cost cap drain.
|
|
946
|
+
"""
|
|
947
|
+
warnings = list(out.warnings)
|
|
948
|
+
while (out.exit_code is ExitCode.BUDGET_OR_INFRA and out.reason in REOPEN_REASONS and out.auto_reopen > 0):
|
|
949
|
+
try:
|
|
950
|
+
root = _root(target)
|
|
951
|
+
except NotInRepository:
|
|
952
|
+
break
|
|
953
|
+
if _reopens(root, thread_id(spec.name, task_id)) >= out.auto_reopen:
|
|
954
|
+
break
|
|
955
|
+
engine = dataclasses.replace(settings, caller=dict(ENGINE_CALLER, call_id=uuid.uuid4().hex), relayed=False,
|
|
956
|
+
flags={}, profiles=None, unset=(), reload_settings=False, ruling=False,
|
|
957
|
+
ruling_for=(), revoke_rulings=(), accept_external=False)
|
|
958
|
+
nxt = _resume(spec, task_id, target, registry, decision="retry", feedback=None, settings=engine)
|
|
959
|
+
if nxt.exit_code is ExitCode.USAGE:
|
|
960
|
+
warnings.append(f"auto_reopen_refused: {nxt.reason}")
|
|
961
|
+
break
|
|
962
|
+
warnings.append(f"auto_reopen: {out.reason}")
|
|
963
|
+
out = nxt
|
|
964
|
+
warnings.extend(out.warnings)
|
|
965
|
+
out.warnings = warnings
|
|
966
|
+
return out
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def _resume(spec: WorkflowSpec, task_id: str, target: Path, registry: Registry, *, decision: str | None,
|
|
970
|
+
feedback: str | None, settings: RunSettings) -> RunOutcome:
|
|
971
|
+
tid = thread_id(spec.name, task_id)
|
|
972
|
+
try:
|
|
973
|
+
root = _root(target)
|
|
974
|
+
except NotInRepository as exc:
|
|
975
|
+
return _refuse("not_git", str(exc))
|
|
976
|
+
action, detail = enginefile.at_resume(root, spec.name, task_id, write=False) # MIG-B12, MIG-B13, MIG-B14; the CLI dispatches
|
|
977
|
+
if action != "move":
|
|
978
|
+
return _refuse("engine_pinned", str(detail) if action == "refuse" else
|
|
979
|
+
f"{tid} resumes on engine {detail}, not this one", tid=tid)
|
|
980
|
+
bad = _bad_breakpoint(spec, settings)
|
|
981
|
+
if bad is not None:
|
|
982
|
+
return bad
|
|
983
|
+
state = classify(root, spec, task_id)
|
|
984
|
+
if state in (ThreadState.NONE, ThreadState.RUNNING, ThreadState.FINISHED):
|
|
985
|
+
hint = {"none": "no such thread", "running": "it is running",
|
|
986
|
+
"finished": f"it finished; `tempergraph rerun {spec.name} {task_id}` starts a linked thread"}
|
|
987
|
+
return _refuse(str(state), f"{tid}: {hint[str(state)]}", tid=tid)
|
|
988
|
+
try:
|
|
989
|
+
d = Decision.parse(decision) if decision else None
|
|
990
|
+
except ValueError as exc:
|
|
991
|
+
return _refuse("decision_invalid", str(exc), tid=tid)
|
|
992
|
+
if feedback and len(feedback) > gatemod.FEEDBACK_LIMIT:
|
|
993
|
+
return _refuse("feedback_too_long", f"feedback is {len(feedback)} characters; at most "
|
|
994
|
+
f"{gatemod.FEEDBACK_LIMIT}", tid=tid)
|
|
995
|
+
if settings.ruling and not feedback:
|
|
996
|
+
return _refuse("ruling_without_text", "--ruling needs --feedback or --feedback-file", tid=tid)
|
|
997
|
+
unknown = [u for u in settings.ruling_for if u not in spec.units]
|
|
998
|
+
if unknown:
|
|
999
|
+
return _refuse("ruling_for_unknown", f"--ruling-for names no unit {', '.join(unknown)}", tid=tid)
|
|
1000
|
+
if settings.escalate:
|
|
1001
|
+
if d is not None and d.word != "retry":
|
|
1002
|
+
return _refuse("decision_invalid", "--escalate goes with a retry, not another decision", tid=tid)
|
|
1003
|
+
d = Decision.parse("retry")
|
|
1004
|
+
human_payload: dict[str, Any] = {"feedback": feedback, "caller": dict(settings.caller),
|
|
1005
|
+
"escalate": settings.escalate,
|
|
1006
|
+
"ruling": {"applies_to": list(settings.ruling_for)} if settings.ruling else None,
|
|
1007
|
+
"revoke": list(settings.revoke_rulings)}
|
|
1008
|
+
declared = spec
|
|
1009
|
+
ensure_state_root(root) # MIG-B9, MIG-B10, MIG-B5: a resume is a writing verb, so an older layout moves forward here
|
|
1010
|
+
lock = RunLock(lock_path(root, spec.name, task_id))
|
|
1011
|
+
try:
|
|
1012
|
+
lock.acquire()
|
|
1013
|
+
except LockHeld:
|
|
1014
|
+
return _refuse("running", f"{tid} is running", tid=tid)
|
|
1015
|
+
try:
|
|
1016
|
+
stale = take_stop(root, spec.name, task_id, stale=True)
|
|
1017
|
+
saver = open_saver(enginefile.checkpoint_of(root, spec.name, task_id))
|
|
1018
|
+
try:
|
|
1019
|
+
cw = compile_workflow(with_outcome(declared), _Inert(), saver)
|
|
1020
|
+
snap = snapshot(cw, tid)
|
|
1021
|
+
values = snap.values
|
|
1022
|
+
kids = subrun.child_states(cw, tid) # SWF-B2, SWF-B3: the state of a child this thread is inside of
|
|
1023
|
+
finally:
|
|
1024
|
+
saver.conn.close()
|
|
1025
|
+
was = enginefile.last(enginefile.read(root, spec.name, task_id))
|
|
1026
|
+
gone = _child_gone(declared, snap, kids, tid) # SWF-B8: a child removed while the parent was paused inside it
|
|
1027
|
+
if gone is not None:
|
|
1028
|
+
return gone
|
|
1029
|
+
changed = _child_changed(declared, was, snap, kids, tid) # SWF-B3: the change rules, applied to the child's units
|
|
1030
|
+
if changed is not None:
|
|
1031
|
+
return changed
|
|
1032
|
+
if was.get("units") and was.get("workflow_version") != _content_version(declared): # MIG-B15
|
|
1033
|
+
pending = [n.rsplit(".", 1)[0] for n, _ in snap.interrupts] or \
|
|
1034
|
+
[n.rsplit(".", 1)[0] for n in snap.next if n.rsplit(".", 1)[0] in was["units"]]
|
|
1035
|
+
if not pending: # the unit it waits at is gone from the new graph
|
|
1036
|
+
at = last_record(run_dir(root, spec.name, task_id) / "run.jsonl", "pause")
|
|
1037
|
+
pending = [str(at["unit"])] if at and at.get("unit") else []
|
|
1038
|
+
broken = enginefile.breaks(was, with_outcome(declared), values, list(dict.fromkeys(pending)))
|
|
1039
|
+
if broken:
|
|
1040
|
+
return _refuse("workflow_changed", f"{tid} cannot resume on workflow version "
|
|
1041
|
+
f"{_content_version(declared)}: {'; '.join(broken)}. Reinstall the version it ran "
|
|
1042
|
+
f"on ({was.get('workflow_version')}) and resume, or start a new thread", broken,
|
|
1043
|
+
tid=tid)
|
|
1044
|
+
try:
|
|
1045
|
+
pause = last_record(run_dir(root, spec.name, task_id) / "run.jsonl", "pause")
|
|
1046
|
+
deciding = bool(d is not None or feedback or settings.ruling or settings.revoke_rulings
|
|
1047
|
+
or any(rst.is_widening(k) for k in settings.all_flags()))
|
|
1048
|
+
settings = decided(settings, deciding=deciding, words=(d.word,) if d else ("grant",),
|
|
1049
|
+
since=(pause or {}).get("ts"))
|
|
1050
|
+
human_payload["caller"] = dict(settings.caller)
|
|
1051
|
+
if settings.escalate:
|
|
1052
|
+
if not (pause or {}).get("escalation"):
|
|
1053
|
+
return _refuse("no_escalation_offered", f"{tid} offers no escalation", tid=tid)
|
|
1054
|
+
if settings.caller and not provenance.may_widen(settings.caller): # LAD-B6, PRV-B21, PRV-B22
|
|
1055
|
+
return _refuse("escalate_needs_person",
|
|
1056
|
+
"--escalate is a person's choice: run it at a terminal, or relay it", tid=tid)
|
|
1057
|
+
fixed = [k for k in settings.all_flags() if k in FIXED_AT_START]
|
|
1058
|
+
if fixed: # WTR-B15, WTR-B17: the record already names a path and a branch; only the cleanup may change
|
|
1059
|
+
raise SettingsRefused([Finding(code="fixed_at_start", unit=None, message=(
|
|
1060
|
+
f"{fixed[0]} is fixed at the start of a thread; only run.worktree.cleanup changes at resume"))])
|
|
1061
|
+
settled = settle_resume(declared, settings, root, values)
|
|
1062
|
+
except SettingsRefused as exc:
|
|
1063
|
+
return _refuse_settings(exc, tid)
|
|
1064
|
+
rv = settled.run
|
|
1065
|
+
rep = preflight(settled.spec, registry, enforce_tools=bool(rv["enforce_tools"]),
|
|
1066
|
+
strict_permissions=bool(rv["strict_permissions"]))
|
|
1067
|
+
rep.warnings.extend(_observer_warnings(root, settings))
|
|
1068
|
+
if not rep.ok:
|
|
1069
|
+
first = rep.refusals[0]
|
|
1070
|
+
return _refuse(first.code, f"{first.unit or spec.name}: {first.message}", tid=tid)
|
|
1071
|
+
spec = with_outcome(settled.spec)
|
|
1072
|
+
human_cap = int(rv["human_cap"])
|
|
1073
|
+
if d is not None and d.word == "rewind" and d.unit and not settings.accept_external:
|
|
1074
|
+
from tempergraph.run.rerun import cleared_units, external_effects
|
|
1075
|
+
|
|
1076
|
+
effects = external_effects(spec, cleared_units(spec, d.unit, values), values)
|
|
1077
|
+
if effects:
|
|
1078
|
+
return _refuse("external_effects", f"rewind:{d.unit} clears units with external effects: "
|
|
1079
|
+
f"{'; '.join(effects)}; pass --accept-external", effects, tid=tid)
|
|
1080
|
+
try:
|
|
1081
|
+
gatemod.check_rulings(values, feedback if settings.ruling else None, settings.revoke_rulings)
|
|
1082
|
+
except gatemod.DecisionRefused as exc:
|
|
1083
|
+
return _refuse("ruling_refused", str(exc), tid=tid)
|
|
1084
|
+
skip_bp: str | None = None
|
|
1085
|
+
row_decision: str | None = None
|
|
1086
|
+
if state is ThreadState.PAUSED and not snap.interrupts: # an operator's breakpoint (FLX-B10)
|
|
1087
|
+
bp = breakpoint_at(root, spec.name, task_id) or {}
|
|
1088
|
+
unit = str(bp.get("unit") or "")
|
|
1089
|
+
if d is None or d.word not in ("proceed", "stop"):
|
|
1090
|
+
return _refuse("decision_missing" if d is None else "decision_refused",
|
|
1091
|
+
f"{tid} is paused before {unit}; pass --decision proceed or stop", tid=tid)
|
|
1092
|
+
touch = (unit, "breakpoint", "")
|
|
1093
|
+
with contextlib.suppress(OSError):
|
|
1094
|
+
breakpoint_file(root, spec.name, task_id).unlink()
|
|
1095
|
+
if d.word == "stop": # the segment ends; the thread stays unfinished and a resume continues it
|
|
1096
|
+
intervention(root, spec, task_id, touch, d, feedback, settings, settled)
|
|
1097
|
+
stop_log = RunLog(run_dir(root, spec.name, task_id) / "run.jsonl")
|
|
1098
|
+
stop_log.write("human", unit=unit, decision="stop", caller=dict(settings.caller), feedback=False)
|
|
1099
|
+
write_json(exit_file(root, spec.name, task_id), {"schema_version": 1,
|
|
1100
|
+
"exit_code": int(ExitCode.STOPPED),
|
|
1101
|
+
"reason": "person"})
|
|
1102
|
+
_record_stop(root, spec, task_id, stop_log, values, registry, settings, settled, rep.judges) # SIL-B27
|
|
1103
|
+
return RunOutcome(exit_code=ExitCode.STOPPED, reason="person", thread_id=tid,
|
|
1104
|
+
message=f"{tid} stopped before {unit}; resume continues it")
|
|
1105
|
+
first_input, before, skip_bp = None, None, unit
|
|
1106
|
+
elif state is ThreadState.PAUSED:
|
|
1107
|
+
gates: dict[str, dict[str, Any]] = {n.rsplit(".", 1)[0]: (p if isinstance(p, dict) else {})
|
|
1108
|
+
for n, p in snap.interrupts}
|
|
1109
|
+
if len(gates) > 1 and settings.unit is None: # HUM-B3: each gate is answered by unit
|
|
1110
|
+
from tempergraph.improve.pause_facts import OPERATOR_REASONS
|
|
1111
|
+
|
|
1112
|
+
lines = [f"{u}: tempergraph resume {spec.name} {task_id} --unit {u} --decision "
|
|
1113
|
+
f"<{'|'.join(p.get('decisions') or [])}> --reason <{'|'.join(OPERATOR_REASONS)}>"
|
|
1114
|
+
for u, p in gates.items()]
|
|
1115
|
+
return _refuse("unit_missing", f"{tid} has {len(gates)} pending gates; name one with --unit",
|
|
1116
|
+
lines, tid=tid)
|
|
1117
|
+
if settings.unit is not None and settings.unit not in gates:
|
|
1118
|
+
return _refuse("unit_unknown", f"{tid} is not paused at {settings.unit}", tid=tid)
|
|
1119
|
+
unit = settings.unit or next(iter(gates))
|
|
1120
|
+
pause = gates[unit]
|
|
1121
|
+
dspec, dunit, dvalues = spec, unit, values # what the decision is checked against: the child's, inside a child
|
|
1122
|
+
if unit not in spec.units and pause.get("slot") == unit: # MAP-B6: one item of a concurrent map, by its slot
|
|
1123
|
+
from tempergraph.run import mapping
|
|
1124
|
+
|
|
1125
|
+
dunit, dvalues = str(pause["unit"]), mapping.item_view(values, str(pause["unit"]), str(pause["item"]))
|
|
1126
|
+
elif "/" in unit: # SWF-B2: a child's pause is answered as any pause, against the child's gate and state
|
|
1127
|
+
found = subrun.locate(spec, unit, settled.snapshot_json())
|
|
1128
|
+
held = _child_values(kids, unit)
|
|
1129
|
+
if found is None or held is None:
|
|
1130
|
+
return _refuse("child_unreadable", f"{tid}: the pause at {unit} belongs to a child that cannot be "
|
|
1131
|
+
"read", tid=tid)
|
|
1132
|
+
(dspec, dunit), dvalues = found, held
|
|
1133
|
+
kind = str(pause.get("kind") or "escalation")
|
|
1134
|
+
touch = (unit, kind, str(pause.get("reason") or ""))
|
|
1135
|
+
by = str(settings.caller.get("decided_by") or settings.caller.get("kind") or "")
|
|
1136
|
+
if (by == "agent" and not settings.operator_reason and not settings.apply_deadline
|
|
1137
|
+
and (d is not None or settings.answers)): # CLI-B30, HUM-B20: an agent says why, before any change
|
|
1138
|
+
from tempergraph.improve.pause_facts import OPERATOR_REASONS
|
|
1139
|
+
|
|
1140
|
+
return _refuse("reason_missing", f"{tid}: an agent's decision at a pause needs --reason "
|
|
1141
|
+
f"<{'|'.join(OPERATOR_REASONS)}>", tid=tid)
|
|
1142
|
+
extra: dict[str, Any] = {}
|
|
1143
|
+
if settings.apply_deadline: # FLX-B8
|
|
1144
|
+
if d is not None or settings.answers:
|
|
1145
|
+
return _refuse("decision_refused", "--apply-deadline goes with no decision", tid=tid)
|
|
1146
|
+
if settings.caller.get("kind") == "orchestrator":
|
|
1147
|
+
return _refuse("deadline_needs_person", "an orchestration supervisor never applies a deadline",
|
|
1148
|
+
tid=tid)
|
|
1149
|
+
due = str(pause.get("deadline_at") or "")
|
|
1150
|
+
if not due or datetime.fromisoformat(due) > datetime.now(datetime.fromisoformat(due).tzinfo):
|
|
1151
|
+
return _refuse("deadline_not_passed", f"{tid} has no overdue pause at {unit}"
|
|
1152
|
+
+ (f"; its deadline is {due}" if due else ""), tid=tid)
|
|
1153
|
+
row_decision = "deadline"
|
|
1154
|
+
d = Decision(word="proceed") # only for the intervention row's shape; the node applies the deadline
|
|
1155
|
+
if kind == "input" and (flow.deadline_of(spec, unit) or (0, ""))[1] == "defaults": # ASK-B10
|
|
1156
|
+
got = _deadline_answers(spec, task_id, root, unit, values, settings)
|
|
1157
|
+
if isinstance(got, RunOutcome): # the check refused the defaults: the ask stays open
|
|
1158
|
+
intervention(root, spec, task_id, touch, d, feedback, settings, settled, decision="deadline")
|
|
1159
|
+
got.thread_id = tid
|
|
1160
|
+
return got
|
|
1161
|
+
extra = got
|
|
1162
|
+
first_input = resume_input({"decision": "deadline", **human_payload, **extra})
|
|
1163
|
+
elif kind == "input":
|
|
1164
|
+
got = _answers_step(dspec, task_id, root, dunit, dvalues, d, settings)
|
|
1165
|
+
if isinstance(got, RunOutcome):
|
|
1166
|
+
if got.exit_code is ExitCode.PAUSED: # accepted, still asking: the graph does not move
|
|
1167
|
+
intervention(root, spec, task_id, touch, Decision(word="answer", name="", value=""),
|
|
1168
|
+
feedback, settings, settled)
|
|
1169
|
+
got.thread_id = tid
|
|
1170
|
+
return got
|
|
1171
|
+
extra = got
|
|
1172
|
+
d = d or Decision(word="proceed")
|
|
1173
|
+
elif settings.answers and dspec.units[dunit].kind == "council": # CNL-B13: `answer:decision=<option>`
|
|
1174
|
+
if d is not None and d.word != "proceed":
|
|
1175
|
+
return _refuse("decision_refused", "a council's pause takes answer:decision=<option> alone", tid=tid)
|
|
1176
|
+
try:
|
|
1177
|
+
extra = {"council_decision": gatemod.check_council_answer(dspec, dunit, dvalues, settings.answers)}
|
|
1178
|
+
except gatemod.DecisionRefused as exc:
|
|
1179
|
+
return _refuse("decision_refused", str(exc), tid=tid)
|
|
1180
|
+
d = Decision(word="proceed")
|
|
1181
|
+
elif (d is None and str(pause.get("reason") or "") == "usage_limit" and kind == "escalation"
|
|
1182
|
+
and not feedback and not settings.answers and not settings.revoke_rulings):
|
|
1183
|
+
# DUR-B12: a plain resume reruns the session the usage limit ended; no check against the reset instant
|
|
1184
|
+
row_decision = ""
|
|
1185
|
+
d = Decision(word="proceed") # only for the intervention row's shape; the human node reruns the session
|
|
1186
|
+
limit_in = {"decision": "usage_limit", **human_payload}
|
|
1187
|
+
if len(gates) == 1:
|
|
1188
|
+
first_input = resume_input(limit_in)
|
|
1189
|
+
else:
|
|
1190
|
+
def first_input(cw2: Any, payload_in: dict[str, Any] = limit_in, unit: str = unit) -> Any:
|
|
1191
|
+
ids = snapshot(cw2, tid).interrupt_ids
|
|
1192
|
+
return resume_input({i: payload_in for i, u in ids.items() if u == unit})
|
|
1193
|
+
elif d is None:
|
|
1194
|
+
return _refuse("decision_missing", f"{tid} is paused at {', '.join(gates)}; pass --decision",
|
|
1195
|
+
tid=tid)
|
|
1196
|
+
if row_decision is None:
|
|
1197
|
+
try:
|
|
1198
|
+
gatemod.check_decision(dspec, dunit, dvalues, d, human_cap=human_cap,
|
|
1199
|
+
command_killed_cap=int(rv["command_killed_retries"]))
|
|
1200
|
+
except gatemod.DecisionRefused as exc:
|
|
1201
|
+
return _refuse("decision_refused", str(exc), tid=tid)
|
|
1202
|
+
payload_in = {"decision": str(d), **human_payload, **extra}
|
|
1203
|
+
if len(gates) == 1:
|
|
1204
|
+
first_input = resume_input(payload_in)
|
|
1205
|
+
else:
|
|
1206
|
+
def first_input(cw2: Any, payload_in: dict[str, Any] = payload_in, unit: str = unit) -> Any:
|
|
1207
|
+
ids = snapshot(cw2, tid).interrupt_ids
|
|
1208
|
+
return resume_input({i: payload_in for i, u in ids.items() if u == unit})
|
|
1209
|
+
before = None
|
|
1210
|
+
elif state is ThreadState.UNFINISHED:
|
|
1211
|
+
if d is not None and d.word != "rewind":
|
|
1212
|
+
return _refuse("decision_refused", "an unfinished thread accepts only `rewind:<unit>`", tid=tid)
|
|
1213
|
+
first_input, before = None, None
|
|
1214
|
+
touch = None
|
|
1215
|
+
if d is not None:
|
|
1216
|
+
unit = _last_unit(values)
|
|
1217
|
+
before = _human_update(spec, unit, values, d, human_payload)
|
|
1218
|
+
touch = (unit, "unfinished", "rewind")
|
|
1219
|
+
elif feedback or settings.revoke_rulings: # RRN-B4: the pending unit's next attempt and its judge
|
|
1220
|
+
waiting = next((n.rsplit(".", 1)[0] for n in snap.next if n.endswith(".step")), _last_unit(values))
|
|
1221
|
+
before = _pending_update(spec, waiting, values, human_payload)
|
|
1222
|
+
else: # stopped
|
|
1223
|
+
stop_at = (values.get("run") or {}).get("stopped") or {}
|
|
1224
|
+
unit = str(stop_at.get("unit") or _last_unit(values))
|
|
1225
|
+
if d is None or d.word not in ("retry", "back", "rewind"):
|
|
1226
|
+
return _refuse("decision_refused", "a stopped thread re-opens with retry, back:<unit> or rewind:<unit>; "
|
|
1227
|
+
f"it stopped at {unit} ({stop_at.get('reason') or 'stopped'})", tid=tid)
|
|
1228
|
+
try:
|
|
1229
|
+
gatemod.check_decision(spec, unit, values, d, human_cap=human_cap,
|
|
1230
|
+
command_killed_cap=int(rv["command_killed_retries"]))
|
|
1231
|
+
except gatemod.DecisionRefused as exc:
|
|
1232
|
+
return _refuse("decision_refused", str(exc), tid=tid)
|
|
1233
|
+
first_input, before = None, _human_update(spec, unit, values, d, human_payload)
|
|
1234
|
+
reason = str(((values.get("run") or {}).get("stopped") or {}).get("reason") or "")
|
|
1235
|
+
touch = (unit, "stopped", reason)
|
|
1236
|
+
carry_warnings: list[str] = []
|
|
1237
|
+
if settings.carry and not carrymod.is_on(root, spec.name, task_id):
|
|
1238
|
+
try:
|
|
1239
|
+
carrymod.set_marker(root, spec.name, task_id, on=True, remote=carrymod.remote_of(root.parent),
|
|
1240
|
+
state="on")
|
|
1241
|
+
except carrymod.CarryRefused as exc:
|
|
1242
|
+
return _refuse(exc.code, str(exc), tid=tid)
|
|
1243
|
+
ws = values.get("workspace") or {}
|
|
1244
|
+
if carrymod.is_on(root, spec.name, task_id): # CAR-B9, CAR-B4: the lease, before the first attempt
|
|
1245
|
+
try:
|
|
1246
|
+
carry_warnings = carrymod.before_resume(
|
|
1247
|
+
root, root.parent, spec.name, task_id, workflow_version=_content_version(declared),
|
|
1248
|
+
machine=join_keys(root, settings)["machine"])
|
|
1249
|
+
except carrymod.CarryRefused as exc:
|
|
1250
|
+
return _refuse(exc.code, str(exc), tid=tid)
|
|
1251
|
+
ws = carrymod.relocate(root, root.parent, spec.name, task_id, ws) if ws else ws
|
|
1252
|
+
if ws:
|
|
1253
|
+
try:
|
|
1254
|
+
rec = attach_workspace(WorkspaceRecord.from_json(ws), tid, spec.worktree, root,
|
|
1255
|
+
marked=take_pause_mark(pause_mark_file(root, spec.name, task_id)))
|
|
1256
|
+
except WorkspaceRefused as exc:
|
|
1257
|
+
return _refuse(exc.word, str(exc), tid=tid)
|
|
1258
|
+
ws_update = rec.to_json()
|
|
1259
|
+
else:
|
|
1260
|
+
ws_update = None
|
|
1261
|
+
prior = before
|
|
1262
|
+
if touch is not None and d is not None:
|
|
1263
|
+
intervention(root, spec, task_id, touch, d, feedback, settings, settled, decision=row_decision)
|
|
1264
|
+
|
|
1265
|
+
def before_all(cw2: Any) -> None:
|
|
1266
|
+
cfg = cw2.config(tid)
|
|
1267
|
+
for update in ({"run": {"options": settled.snapshot_json()}},
|
|
1268
|
+
*([{"workspace": ws_update}] if ws_update is not None else [])):
|
|
1269
|
+
if not update_values(cw2, cfg, update): # several nodes pending: the first to run carries it
|
|
1270
|
+
cw2.engine.defer(update)
|
|
1271
|
+
if prior is not None:
|
|
1272
|
+
prior(cw2)
|
|
1273
|
+
|
|
1274
|
+
out = _drive(spec, task_id, root, registry, settings, rep.judges, first_input, settled, before=before_all,
|
|
1275
|
+
executors=rep.step_executors, workspace=ws_update, skip_breakpoint=skip_bp, ruling_records=_ruling_records(spec, values, d, touch, settings,
|
|
1276
|
+
feedback, snap.next))
|
|
1277
|
+
if stale is not None:
|
|
1278
|
+
out.warnings.append("stale_stop_request_removed")
|
|
1279
|
+
out.warnings.extend(carry_warnings)
|
|
1280
|
+
return _carry_exit(root, spec, task_id, settings, out)
|
|
1281
|
+
finally:
|
|
1282
|
+
lock.release()
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
def _inside(spec: WorkflowSpec, snap: Any, kids: Mapping[str, Any]) -> list[str]:
|
|
1286
|
+
"""The sub-workflow units a thread is inside of: paused at a gate of their child (`<unit>/<child unit>`), or waiting at
|
|
1287
|
+
their step with the child's state kept."""
|
|
1288
|
+
out = [n.split("/", 1)[0] for n, _ in snap.interrupts if "/" in n]
|
|
1289
|
+
out += [n.rsplit(".", 1)[0] for n in snap.next if n.endswith(".step") and kids
|
|
1290
|
+
and n.rsplit(".", 1)[0] in subworkflow.units_of(spec)]
|
|
1291
|
+
return list(dict.fromkeys(out))
|
|
1292
|
+
|
|
1293
|
+
|
|
1294
|
+
def _child_values(kids: Mapping[str, Mapping[str, Any]], path: str) -> dict[str, Any] | None:
|
|
1295
|
+
"""The kept state of the child a pause at `path` (`<unit>/<child unit>`) is in."""
|
|
1296
|
+
for values in kids.values():
|
|
1297
|
+
if any(isinstance(p, Mapping) and p.get("unit") == path for p in (values.get("pause") or {}).values()):
|
|
1298
|
+
return dict(values)
|
|
1299
|
+
return None
|
|
1300
|
+
|
|
1301
|
+
|
|
1302
|
+
def _child_gone(spec: WorkflowSpec, snap: Any, kids: Mapping[str, Any], tid: str) -> RunOutcome | None:
|
|
1303
|
+
"""SWF-B8: a resume whose child was removed while the parent was paused inside it is refused with exit 2 naming the
|
|
1304
|
+
child; `workflows register` restores it."""
|
|
1305
|
+
for unit in _inside(spec, snap, kids):
|
|
1306
|
+
rec = spec.units[unit].subworkflow if unit in spec.units else None
|
|
1307
|
+
if rec is not None and not isinstance(subworkflow.read_child(rec.workflow), subworkflow.Child):
|
|
1308
|
+
return _refuse("child_removed", f"{tid} is paused inside the child {rec.workflow!r} (unit {unit!r}), which is "
|
|
1309
|
+
f"no longer registered; run `tempergraph workflows register` for {rec.workflow!r} "
|
|
1310
|
+
"to restore it, then resume", tid=tid)
|
|
1311
|
+
return None
|
|
1312
|
+
|
|
1313
|
+
|
|
1314
|
+
def _child_changed(spec: WorkflowSpec, was: Mapping[str, Any], snap: Any, kids: Mapping[str, Any], tid: str
|
|
1315
|
+
) -> RunOutcome | None:
|
|
1316
|
+
"""SWF-B3: the change-under-a-thread rules (MIG-B15) applied, per child, to the units of a child whose version
|
|
1317
|
+
changed while the parent was paused inside it."""
|
|
1318
|
+
options = ((snap.values.get("run") or {}).get("options") or {})
|
|
1319
|
+
for unit in _inside(spec, snap, kids):
|
|
1320
|
+
rec = spec.units[unit].subworkflow if unit in spec.units else None
|
|
1321
|
+
held = (was.get("children") or {}).get(unit) or {}
|
|
1322
|
+
got = subworkflow.read_child(rec.workflow) if rec is not None else None
|
|
1323
|
+
if not isinstance(got, subworkflow.Child) or not held.get("units"):
|
|
1324
|
+
continue
|
|
1325
|
+
if held.get("workflow_version") == _content_version(got.spec):
|
|
1326
|
+
continue
|
|
1327
|
+
cspec, _ = subrun.applied(spec, got, subrun.child_options(unit, options))
|
|
1328
|
+
pending = [n.split("/", 1)[1].rsplit(".", 1)[0] for n, _ in snap.interrupts if n.startswith(f"{unit}/")]
|
|
1329
|
+
cvalues = next((dict(v) for v in kids.values()), {})
|
|
1330
|
+
broken = enginefile.breaks(held, cspec, cvalues, pending)
|
|
1331
|
+
if broken:
|
|
1332
|
+
return _refuse("workflow_changed", f"{tid} cannot resume: the child {rec.workflow if rec else unit!r} changed "
|
|
1333
|
+
f"to {_content_version(got.spec)}: {'; '.join(broken)}. Reinstall the version it ran on "
|
|
1334
|
+
f"({held.get('workflow_version')}) and resume, or start a new thread", broken, tid=tid)
|
|
1335
|
+
return None
|
|
1336
|
+
|
|
1337
|
+
|
|
1338
|
+
RESCUE_PAUSES = frozenset({"escalation", "budget", "tool_access"})
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
def touches(pause_kind: str, stop_reason: str, d: Decision) -> list[dict[str, str]]:
|
|
1342
|
+
"""SUP-B9 touch classes of one accepted resume."""
|
|
1343
|
+
out: list[dict[str, str]] = []
|
|
1344
|
+
if pause_kind == "approval":
|
|
1345
|
+
out.append({"class": "designed", "action": "approve"})
|
|
1346
|
+
elif pause_kind == "input" and d.word != "stop":
|
|
1347
|
+
out.append({"class": "designed", "action": "answer"})
|
|
1348
|
+
elif pause_kind == "event_wait" and d.word != "stop":
|
|
1349
|
+
out.append({"class": "designed", "action": "event"})
|
|
1350
|
+
elif pause_kind == "breakpoint" and d.word != "stop":
|
|
1351
|
+
out.append({"class": "steer", "action": "breakpoint"})
|
|
1352
|
+
elif pause_kind in RESCUE_PAUSES or pause_kind == "stopped" and stop_reason in ("budget", "infra"):
|
|
1353
|
+
out.append({"class": "rescue", "action": "decide"})
|
|
1354
|
+
if d.word == "rewind":
|
|
1355
|
+
out.append({"class": "steer", "action": "rewind"})
|
|
1356
|
+
elif d.word == "stop":
|
|
1357
|
+
out.append({"class": "steer", "action": "stop"})
|
|
1358
|
+
elif pause_kind == "stopped" and stop_reason not in ("budget", "infra") and not out:
|
|
1359
|
+
out.append({"class": "steer", "action": "decide"})
|
|
1360
|
+
return out
|
|
1361
|
+
|
|
1362
|
+
|
|
1363
|
+
def _answers_step(spec: WorkflowSpec, task_id: str, root: Path, unit: str, values: Mapping[str, Any],
|
|
1364
|
+
d: Decision | None, settings: RunSettings) -> dict[str, Any] | RunOutcome:
|
|
1365
|
+
"""ASK-B8: validate and keep this resume's answers. Returns the human node's extra payload when the set
|
|
1366
|
+
is complete and the check passes, else the outcome of this call: a refusal, or `still asking` (exit 3)."""
|
|
1367
|
+
from tempergraph.improve.pause_facts import OPERATOR_REASONS
|
|
1368
|
+
from tempergraph.run import asking
|
|
1369
|
+
|
|
1370
|
+
tid = thread_id(spec.name, task_id)
|
|
1371
|
+
u = spec.units[unit]
|
|
1372
|
+
assert u.ask is not None
|
|
1373
|
+
if d is not None and d.word == "stop":
|
|
1374
|
+
return {}
|
|
1375
|
+
if d is not None and d.word != "proceed":
|
|
1376
|
+
return _refuse("decision_refused", "an ask accepts answer:<name>=<value>, proceed and stop", tid=tid)
|
|
1377
|
+
if d is None and not settings.answers:
|
|
1378
|
+
return _refuse("decision_missing", f"{tid} is asking at {unit}; pass --decision answer:<name>=<value>",
|
|
1379
|
+
tid=tid)
|
|
1380
|
+
qs = [asking.of_json(q) for q in ((values.get("attempts") or {}).get(unit) or {}).get("questions") or []]
|
|
1381
|
+
ws = values.get("workspace") or {}
|
|
1382
|
+
workdir = Path(str(ws.get("path"))) if ws.get("path") else root.parent
|
|
1383
|
+
try:
|
|
1384
|
+
new = asking.accept(qs, settings.answers, workdir)
|
|
1385
|
+
except asking.AnswerRefused as exc:
|
|
1386
|
+
return _refuse("answer_refused", str(exc), tid=tid)
|
|
1387
|
+
path = asking.answers_path(run_dir(root, spec.name, task_id), unit)
|
|
1388
|
+
merged = {**asking.load(path), **new}
|
|
1389
|
+
if d is not None and asking.unanswered(qs, merged, defaults=True): # `proceed` needs the set complete
|
|
1390
|
+
return _refuse("answers_missing", f"{unit} still needs "
|
|
1391
|
+
f"{', '.join(asking.unanswered(qs, merged, defaults=True))}", tid=tid)
|
|
1392
|
+
log = RunLog(run_dir(root, spec.name, task_id) / "run.jsonl")
|
|
1393
|
+
missing = asking.unanswered(qs, merged, defaults=False) if d is None else []
|
|
1394
|
+
final = asking.complete(qs, merged)
|
|
1395
|
+
problems = [] if missing else asking.check_problems(u.ask, final)
|
|
1396
|
+
log.write("answers", unit=unit, answered=sorted(new), missing=missing, check_passed=not problems and not missing,
|
|
1397
|
+
caller=dict(settings.caller))
|
|
1398
|
+
if missing or problems:
|
|
1399
|
+
asking.store(path, unit, merged, done=False)
|
|
1400
|
+
payload = {"kind": "input", "unit": unit, "questions": asking.shown(qs, merged), "missing": missing,
|
|
1401
|
+
"check_problems": problems,
|
|
1402
|
+
"resume": f"tempergraph resume {spec.name} {task_id} --decision answer:<name>=<value> "
|
|
1403
|
+
f"--reason <{'|'.join(OPERATOR_REASONS)}>"}
|
|
1404
|
+
why = f"still needs {', '.join(missing)}" if missing else f"the answers check: {'; '.join(problems)}"
|
|
1405
|
+
return RunOutcome(exit_code=ExitCode.PAUSED, reason="input", payload=payload,
|
|
1406
|
+
message=f"{tid}: answers kept; {unit} {why}")
|
|
1407
|
+
asking.store(path, unit, final, done=True)
|
|
1408
|
+
return {"answers": final, "answers_path": str(path)}
|
|
1409
|
+
|
|
1410
|
+
|
|
1411
|
+
def _deadline_answers(spec: WorkflowSpec, task_id: str, root: Path, unit: str, values: Mapping[str, Any],
|
|
1412
|
+
settings: RunSettings) -> dict[str, Any] | RunOutcome:
|
|
1413
|
+
"""ASK-B10, ASK-B11: complete an overdue ask from its defaults and run the author's check as for a person's
|
|
1414
|
+
answers. A pass returns the human node's extra payload; a refusal keeps only the given answers (exit 3)."""
|
|
1415
|
+
from tempergraph.improve.pause_facts import OPERATOR_REASONS
|
|
1416
|
+
from tempergraph.run import asking
|
|
1417
|
+
|
|
1418
|
+
tid = thread_id(spec.name, task_id)
|
|
1419
|
+
u = spec.units[unit]
|
|
1420
|
+
assert u.ask is not None
|
|
1421
|
+
qs = [asking.of_json(q) for q in ((values.get("attempts") or {}).get(unit) or {}).get("questions") or []]
|
|
1422
|
+
path = asking.answers_path(run_dir(root, spec.name, task_id), unit)
|
|
1423
|
+
given = asking.load(path)
|
|
1424
|
+
took = asking.defaulted(qs, given)
|
|
1425
|
+
final = asking.complete(qs, given)
|
|
1426
|
+
problems = asking.check_problems(u.ask, final)
|
|
1427
|
+
RunLog(run_dir(root, spec.name, task_id) / "run.jsonl").write(
|
|
1428
|
+
"answers", unit=unit, answered=[], missing=[], check_passed=not problems, caller=dict(settings.caller))
|
|
1429
|
+
if problems:
|
|
1430
|
+
asking.store(path, unit, given, done=False)
|
|
1431
|
+
payload = {"kind": "input", "unit": unit, "questions": asking.shown(qs, given), "missing": [],
|
|
1432
|
+
"check_problems": problems,
|
|
1433
|
+
"resume": f"tempergraph resume {spec.name} {task_id} --decision answer:<name>=<value> "
|
|
1434
|
+
f"--reason <{'|'.join(OPERATOR_REASONS)}>"}
|
|
1435
|
+
return RunOutcome(exit_code=ExitCode.PAUSED, reason="input", payload=payload,
|
|
1436
|
+
message=f"{tid}: the deadline's defaults were refused; {unit} the answers check: "
|
|
1437
|
+
f"{'; '.join(problems)}")
|
|
1438
|
+
asking.store(path, unit, final, done=True, defaulted=took)
|
|
1439
|
+
return {"answers": final, "answers_path": str(path)}
|
|
1440
|
+
|
|
1441
|
+
|
|
1442
|
+
def intervention(root: Path, spec: WorkflowSpec, task_id: str, touch: tuple[str, str, str], d: Decision,
|
|
1443
|
+
feedback: str | None, settings: RunSettings, settled: Settled | None = None, *,
|
|
1444
|
+
decision: str | None = None) -> dict[str, Any]:
|
|
1445
|
+
"""HUM-B6: one metadata-only ledger row per accepted resume, appended before the graph runs."""
|
|
1446
|
+
unit, kind, reason = touch
|
|
1447
|
+
owner, _, inner = unit.rpartition("/") # a child's pause reads `<unit>/<child unit>` (SWF-B2)
|
|
1448
|
+
pause = last_record(run_dir(root, spec.name, task_id) / "run.jsonl", "pause", unit=inner,
|
|
1449
|
+
**({"child": owner} if owner else {}))
|
|
1450
|
+
wait_s = None
|
|
1451
|
+
engine = settings.caller.get("kind") == "engine" # an automatic re-open waits on no one (SUP-B9)
|
|
1452
|
+
if pause and pause.get("ts") and not engine:
|
|
1453
|
+
with contextlib.suppress(ValueError, TypeError):
|
|
1454
|
+
wait_s = round((datetime.now(datetime.fromisoformat(pause["ts"]).tzinfo)
|
|
1455
|
+
- datetime.fromisoformat(pause["ts"])).total_seconds(), 1)
|
|
1456
|
+
row = {"kind": "intervention", "id": uuid.uuid4().hex, "thread_id": thread_id(spec.name, task_id),
|
|
1457
|
+
"workflow": spec.name, "workflow_version": spec.version, **join_keys(root, settings), "unit": unit, "caller": dict(settings.caller),
|
|
1458
|
+
"touches": [{"class": "engine", "action": "reopen"}] if engine
|
|
1459
|
+
else [{"class": "designed", "action": "deadline"}] if decision == "deadline"
|
|
1460
|
+
else touches(kind, reason if kind == "stopped" else "", d), "pause_kind": kind,
|
|
1461
|
+
"decision": decision if decision is not None else d.word + (f":{d.unit}" if d.unit else ""), "wait_s": wait_s, "feedback": bool(feedback) and not settings.ruling,
|
|
1462
|
+
"ruling": settings.ruling, "settings_changed": list(settled.changed) if settled else [],
|
|
1463
|
+
"grants": [{k: v for k, v in g.items() if k != "key"} for g in (settled.grant_changes() if settled else [])],
|
|
1464
|
+
"cause": "auto_reopen" if engine else reason or kind}
|
|
1465
|
+
if settings.operator_reason:
|
|
1466
|
+
row["operator_reason"] = settings.operator_reason
|
|
1467
|
+
if decision is None and not engine: # HUM-B19: a decision at a pause holds what it answered
|
|
1468
|
+
item = pause.get("item") if pause and kind != "breakpoint" else None
|
|
1469
|
+
row["item"] = str(item) if item else "none"
|
|
1470
|
+
row["answered"] = _answered(run_dir(root, spec.name, task_id) / "run.jsonl", owner, inner, item,
|
|
1471
|
+
lookup=kind != "breakpoint")
|
|
1472
|
+
Ledger(path=root / "ledger.jsonl").append(row)
|
|
1473
|
+
return row
|
|
1474
|
+
|
|
1475
|
+
|
|
1476
|
+
ANSWERED_FACTS = ("check", "failed", "environmental", "blockers", "gap", "guard", "claim")
|
|
1477
|
+
|
|
1478
|
+
|
|
1479
|
+
def _answered(log: Path, child: str, unit: str, item: Any, *, lookup: bool = True) -> dict[str, Any]:
|
|
1480
|
+
"""HUM-B19: the last `check` and `judgement` records of the unit, child and item after the unit's last
|
|
1481
|
+
`unit_entered`, as ids, enums, booleans and numbers; `not recorded` for each fact the log does not hold."""
|
|
1482
|
+
out: dict[str, Any] = {k: "not recorded" for k in ANSWERED_FACTS}
|
|
1483
|
+
if not lookup:
|
|
1484
|
+
return out
|
|
1485
|
+
from tempergraph.run.events import records as log_records
|
|
1486
|
+
|
|
1487
|
+
def mine(r: Mapping[str, Any]) -> bool:
|
|
1488
|
+
return r.get("unit") == unit and (r.get("child") or "") == child
|
|
1489
|
+
|
|
1490
|
+
recs = [r for r in log_records(log) if mine(r)]
|
|
1491
|
+
entered = [i for i, r in enumerate(recs) if r.get("kind") == "unit_entered"]
|
|
1492
|
+
visit = recs[entered[-1] + 1:] if entered else recs
|
|
1493
|
+
same = [r for r in visit if (r.get("item") or None) == (item or None)]
|
|
1494
|
+
check = next((r for r in reversed(same) if r.get("kind") == "check"), None)
|
|
1495
|
+
judged = next((r for r in reversed(same) if r.get("kind") == "judgement"), None)
|
|
1496
|
+
if check is not None:
|
|
1497
|
+
out["check"] = str(check.get("result") or "not recorded")
|
|
1498
|
+
if isinstance(check.get("failed"), list):
|
|
1499
|
+
out["failed"] = [str(x) for x in check["failed"]]
|
|
1500
|
+
if isinstance(check.get("environmental"), bool):
|
|
1501
|
+
out["environmental"] = check["environmental"]
|
|
1502
|
+
if judged is not None:
|
|
1503
|
+
if isinstance(judged.get("blockers"), list):
|
|
1504
|
+
out["blockers"] = [str(x) for x in judged["blockers"]]
|
|
1505
|
+
if isinstance(judged.get("gap"), bool):
|
|
1506
|
+
out["gap"] = judged["gap"]
|
|
1507
|
+
if judged.get("guard") is not None:
|
|
1508
|
+
out["guard"] = str(judged["guard"])
|
|
1509
|
+
out["claim"] = str(judged.get("claim") or "none")
|
|
1510
|
+
return out
|
|
1511
|
+
|
|
1512
|
+
|
|
1513
|
+
def _last_unit(values: Mapping[str, Any]) -> str:
|
|
1514
|
+
units = ((values.get("run") or {}).get("path") or {}).get("units") or []
|
|
1515
|
+
return str(units[-1]) if units else ""
|
|
1516
|
+
|
|
1517
|
+
|
|
1518
|
+
def _ruling_records(spec: WorkflowSpec, values: Mapping[str, Any], d: Decision | None,
|
|
1519
|
+
touch: tuple[str, str, str] | None, settings: RunSettings, feedback: str | None,
|
|
1520
|
+
pending: Sequence[str]) -> list[dict[str, Any]]:
|
|
1521
|
+
"""EVT `ruling`: given and revoked rulings of this resume, ids and lengths only, never the text."""
|
|
1522
|
+
out: list[dict[str, Any]] = [{"id": rid, "action": "revoked", "by": dict(settings.caller)}
|
|
1523
|
+
for rid in settings.revoke_rulings]
|
|
1524
|
+
if settings.ruling and feedback:
|
|
1525
|
+
if d is not None and touch is not None:
|
|
1526
|
+
at = gatemod.decision_target(spec, touch[0], d)
|
|
1527
|
+
else:
|
|
1528
|
+
at = next((n.rsplit(".", 1)[0] for n in pending if n.endswith(".step")), _last_unit(values))
|
|
1529
|
+
out.append({"id": f"r{len(values.get('rulings') or {}) + 1}", "action": "given", "given_at": at,
|
|
1530
|
+
"applies_to": list(settings.ruling_for), "by": dict(settings.caller), "chars": len(feedback)})
|
|
1531
|
+
return out
|
|
1532
|
+
|
|
1533
|
+
|
|
1534
|
+
def _pending_update(spec: WorkflowSpec, unit: str, values: Mapping[str, Any], payload: Mapping[str, Any]
|
|
1535
|
+
) -> Callable[[Any], None]:
|
|
1536
|
+
"""Feedback, a ruling or a revocation on an unfinished thread, with no decision (RRN-B14, RRN-B15, RRN-B4)."""
|
|
1537
|
+
|
|
1538
|
+
def apply(cw: Any) -> None:
|
|
1539
|
+
w: dict[str, Any] = {}
|
|
1540
|
+
rulings = gatemod.ruling_writes(values, payload, unit)
|
|
1541
|
+
if rulings:
|
|
1542
|
+
w["rulings"] = rulings
|
|
1543
|
+
if payload.get("feedback") and not payload.get("ruling"):
|
|
1544
|
+
w["feedback"] = {unit: {"text": payload["feedback"], "as": "feedback"}}
|
|
1545
|
+
if w:
|
|
1546
|
+
cw.graph.update_state(cw.config(thread_id(spec.name, str((values.get("request") or {}).get("task_id")))),
|
|
1547
|
+
w)
|
|
1548
|
+
|
|
1549
|
+
return apply
|
|
1550
|
+
|
|
1551
|
+
|
|
1552
|
+
def _human_update(spec: WorkflowSpec, unit: str, values: Mapping[str, Any], d: Decision,
|
|
1553
|
+
payload: Mapping[str, Any]) -> Callable[[Any], None]:
|
|
1554
|
+
"""Re-open a stopped thread, or rewind an unfinished one, through the human node's own update."""
|
|
1555
|
+
|
|
1556
|
+
def apply(cw: Any) -> None:
|
|
1557
|
+
w = gatemod.apply_decision(spec, unit, values, {"decision": str(d), **payload})
|
|
1558
|
+
w.setdefault("run", {})["stopped"] = None
|
|
1559
|
+
cw.graph.update_state(cw.config(f"{spec.name}/{values.get('request', {}).get('task_id', '')}"), w,
|
|
1560
|
+
as_node=flow.node_names(unit)[3])
|
|
1561
|
+
|
|
1562
|
+
return apply
|
|
1563
|
+
|
|
1564
|
+
|
|
1565
|
+
class _Inert:
|
|
1566
|
+
def _never(self, *_: Any) -> dict[str, Any]:
|
|
1567
|
+
raise RuntimeError("inert")
|
|
1568
|
+
|
|
1569
|
+
step = judge = gate = human = _never
|
|
1570
|
+
|
|
1571
|
+
def finalizer(self, state: Any) -> dict[str, Any]:
|
|
1572
|
+
return self._never(state)
|
|
1573
|
+
|
|
1574
|
+
|
|
1575
|
+
def read_exit(state_root: Path, workflow: str, task_id: str) -> dict[str, Any] | None:
|
|
1576
|
+
p = exit_file(state_root, workflow, task_id)
|
|
1577
|
+
with contextlib.suppress(OSError, ValueError):
|
|
1578
|
+
return read_json(p, "status") if p.exists() else None
|
|
1579
|
+
return None
|