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,651 @@
|
|
|
1
|
+
"""The loop child: judged lenses after a final exit, then filing (SIL-B1, SIL-B10, SIL-B17, SIL-B18; T12.1.5).
|
|
2
|
+
|
|
3
|
+
The run's exit writes a hand-off ticket (ids, enums and paths only, never request text) under the home and
|
|
4
|
+
starts `python -m tempergraph.improve.child drain` through the detached child launcher (SEC-B7). The child
|
|
5
|
+
claims each ticket, runs the friction judge over the findings' metadata, decides each candidate with the filing
|
|
6
|
+
rules and files. Its failure never reaches the parent: the parent has exited and its exit code is written.
|
|
7
|
+
|
|
8
|
+
Release 1 shape: a fixed engine program of one judged session per ticket, not a compiled workflow; the judge
|
|
9
|
+
follows the run's judge executor on the mid-tier alias for 1800 s. The outcome lens spends no session: its
|
|
10
|
+
candidates are the final criteria the outcome gate's own judge graded unmet, and they file only while that judge
|
|
11
|
+
is `accepted` by calibration (SIL-B7, JCL); until then they are recorded `uncalibrated`. Like all filing code,
|
|
12
|
+
this module never opens the evidence file.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
import dataclasses
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import sys
|
|
23
|
+
import time
|
|
24
|
+
import uuid
|
|
25
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
26
|
+
from datetime import UTC, datetime
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from tempergraph.contracts import SessionOptions, SessionRequest, ViewSet, WorkflowSpec
|
|
31
|
+
from tempergraph.docs import append_jsonl, write_json
|
|
32
|
+
from tempergraph.durability import lock as durability_lock
|
|
33
|
+
from tempergraph.executors.registry import Registry, default_registry
|
|
34
|
+
from tempergraph.improve import autonomy, escape, filing, params, pause_facts, pr_later
|
|
35
|
+
from tempergraph.improve.codehost import CodeHost, GhCodeHost
|
|
36
|
+
from tempergraph.improve.record import read_findings
|
|
37
|
+
from tempergraph.run.log import Ledger, LiveSink, estimate
|
|
38
|
+
from tempergraph.store.layout import home_path, now_iso, run_dir
|
|
39
|
+
|
|
40
|
+
ALIAS = "medium"
|
|
41
|
+
EFFORT = "max" # the loop reads session logs: Sonnet thinks at its most (SIL-B17)
|
|
42
|
+
TIMEOUT_S = 1800
|
|
43
|
+
clock = time.time # replaceable, so a test runs the wait of SIL-B25 on a fake clock
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def filing_clock() -> datetime:
|
|
47
|
+
"""The time a ticket files at (ISS-B13 day bound, mute age); replaceable, so a test makes two UTC days."""
|
|
48
|
+
return datetime.now(UTC)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _ticket_cap(t: Mapping[str, Any]) -> int:
|
|
52
|
+
"""ICAP-B2: the ticket's `issue_cap`; 3 when it holds none or a value that is not a whole number from 0 to 50."""
|
|
53
|
+
v = t.get("issue_cap", 3)
|
|
54
|
+
return v if isinstance(v, int) and not isinstance(v, bool) and 0 <= v <= 50 else 3
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
sleep = time.sleep
|
|
58
|
+
FENCE = re.compile(r"```(?:json)?\s*\n(.*?)\n```", re.S)
|
|
59
|
+
BRIEF = """You review the friction of one workflow run for a self-improvement loop.
|
|
60
|
+
|
|
61
|
+
Each finding below was derived by rules from the run's records: a cause code, the side the rule blames
|
|
62
|
+
(`engine`, `workflow`, `executor:<name>` or `host`), the unit and a count. You see metadata only, never the
|
|
63
|
+
request or the outputs. For each finding decide whether the fault really lies on the side named, and how sure
|
|
64
|
+
you are (0 to 1). Say `attributed: false` when the records point elsewhere, for example a retry burst that
|
|
65
|
+
follows an infrastructure failure, or a check failure that a person's ruling caused.
|
|
66
|
+
|
|
67
|
+
An answer `attributed: true` can file the finding by the count whatever its confidence, so answer attribution
|
|
68
|
+
on the records, not on how sure you are of the remedy.
|
|
69
|
+
|
|
70
|
+
The section `What answered each pause` appears when a finding comes from a segment that ended in a pause. Each row
|
|
71
|
+
names the paused unit and item, why it paused, who answered it and how (the decision, whether a ruling or feedback
|
|
72
|
+
was given, never its words), the class of the decision's touch, whether the workspace changed between the pause and
|
|
73
|
+
the resume, and the verdict of the next gate of that unit and item. A `retry` that passes with the workspace
|
|
74
|
+
unchanged points at the judge or the check and not at the step, because the same work passed on a second look.
|
|
75
|
+
A `proceed` with a ruling says a person or the supervising caller overrode the gate, so the check's failure is not
|
|
76
|
+
by itself a fault of the step. An operator reason other than `plan` or `request` points away from the workflow's
|
|
77
|
+
step: `engine_defect`, `judge_error`, `environment` and `other` say the cause lay outside what the step did.
|
|
78
|
+
|
|
79
|
+
End with one fenced JSON block:
|
|
80
|
+
```json
|
|
81
|
+
{"findings": [{"fingerprint": "<id>", "attributed": true, "confidence": 0.8}]}
|
|
82
|
+
```"""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def tickets_dir(home: Path) -> Path:
|
|
86
|
+
return home / "improve" / "tickets"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def loop_log(root: Path, workflow: str, task_id: str) -> Path:
|
|
90
|
+
return run_dir(root, workflow, task_id) / "loop.jsonl" # LOS-B7, LOS-B8, LOS-B9
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def alias_of(t: Mapping[str, Any]) -> str:
|
|
94
|
+
"""The alias of the loop's own sessions: the run setting `loop_model` the ticket carries, else `medium`."""
|
|
95
|
+
return str(t.get("alias") or ALIAS)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def options_of(t: Mapping[str, Any]) -> SessionOptions:
|
|
99
|
+
"""The options of the loop's own sessions: the run setting `loop_effort` the ticket carries, else `max`."""
|
|
100
|
+
return SessionOptions(effort=t.get("effort") or EFFORT) # type: ignore[arg-type]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def mode() -> str:
|
|
104
|
+
return os.environ.get("TEMPERGRAPH_LOOP", "detached")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def declared_labels(spec: WorkflowSpec) -> list[Any] | None:
|
|
108
|
+
"""ISS-B1: `improvement.issue_labels` of the workflow's `tempergraph.json`; none when absent or unreadable."""
|
|
109
|
+
if spec.package_root is None:
|
|
110
|
+
return None
|
|
111
|
+
try:
|
|
112
|
+
doc = json.loads((spec.package_root / "tempergraph.json").read_text(encoding="utf-8"))
|
|
113
|
+
except (OSError, ValueError):
|
|
114
|
+
return None
|
|
115
|
+
got = (doc.get("improvement") or {}).get("issue_labels") if isinstance(doc, dict) else None
|
|
116
|
+
return list(got) if isinstance(got, list) else None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _prompts(spec: WorkflowSpec) -> dict[str, dict[str, str]]:
|
|
120
|
+
"""ALN-B25, ALN-B26: each unit's step prompt as declared: `text` (inline, or a package file read now),
|
|
121
|
+
`default`, or `unreadable` with no text. A unit with no step has no entry."""
|
|
122
|
+
from tempergraph.contracts import TextRef
|
|
123
|
+
from tempergraph.model.text import TextUnreadable, load_text
|
|
124
|
+
|
|
125
|
+
out: dict[str, dict[str, str]] = {}
|
|
126
|
+
for name, u in spec.units.items():
|
|
127
|
+
if u.step is None:
|
|
128
|
+
continue
|
|
129
|
+
p = u.step.prompt
|
|
130
|
+
if p == "default":
|
|
131
|
+
out[name] = {"kind": "default"}
|
|
132
|
+
continue
|
|
133
|
+
try:
|
|
134
|
+
out[name] = {"kind": "text", "text": load_text(spec, p if isinstance(p, TextRef) else str(p))}
|
|
135
|
+
except TextUnreadable:
|
|
136
|
+
out[name] = {"kind": "unreadable"}
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def hand_off(root: Path, spec: WorkflowSpec, task_id: str, thread: str, summary: Mapping[str, Any], *,
|
|
141
|
+
dry_run: bool, judge_executor: str, home: Path | None = None, operator_review: str | None = None,
|
|
142
|
+
run_cost_usd: float = 0.0, trial: bool = False, daily_cap_usd: float | None = None,
|
|
143
|
+
loop_model: str | None = None, loop_effort: str | None = None, trigger: str | None = None,
|
|
144
|
+
loop_autonomy: str | None = None, dry_source: str = "default", lift: bool = False,
|
|
145
|
+
issue_cap: int = 3, base_branch: str = "") -> Path | None:
|
|
146
|
+
"""Writes the ticket when a judged lens fired at this final exit and there is a fault to judge, when the
|
|
147
|
+
outcome lens has candidates, or when the session review (SRV-B13, SRV-B14, SRV-B15) has a depth other than none;
|
|
148
|
+
a `signals` review whose plan has no depth (a clean first-pass stable run) writes none (SIL-B1, SRV-B4)."""
|
|
149
|
+
from tempergraph.improve import proposals as prp
|
|
150
|
+
from tempergraph.improve import review
|
|
151
|
+
from tempergraph.improve.calibration import has_score
|
|
152
|
+
from tempergraph.improve.record import unit_decls
|
|
153
|
+
|
|
154
|
+
lenses = summary.get("lenses") or {}
|
|
155
|
+
friction = bool(lenses.get("friction")) and bool(summary.get("fault_fingerprints"))
|
|
156
|
+
outcome = bool(summary.get("outcome_fingerprints")) # graded by the outcome gate's own judge: no new session
|
|
157
|
+
final = "lenses" in summary # a final exit (SIL-B8)
|
|
158
|
+
prob = review.probation(root, spec.name, spec.version)
|
|
159
|
+
depth = review.effective(spec.session_review, operator_review, spec.improvement_mode, prob, trial) \
|
|
160
|
+
if final else "off"
|
|
161
|
+
setting = depth # ALN-B1: the setting before the `signals` probe lowers the depth
|
|
162
|
+
reason = "trial" if trial else "probation" if prob and spec.improvement_mode != "dev" else \
|
|
163
|
+
"dev" if spec.improvement_mode == "dev" else "signal"
|
|
164
|
+
if depth == "signals": # SIL-B1, SRV-B4: a `signals` plan with no depth is no review, so it starts no child
|
|
165
|
+
try:
|
|
166
|
+
probe = review.plan_for(
|
|
167
|
+
{"state_root": str(root), "workflow": spec.name, "task_id": task_id, "workflow_version": spec.version,
|
|
168
|
+
"review": "signals", "mode": spec.improvement_mode, "run_cost_usd": float(run_cost_usd or 0.0),
|
|
169
|
+
"fingerprints": list(summary.get("fingerprints") or []),
|
|
170
|
+
"daily_cap_usd": autonomy.daily_cap(spec.improvement_mode, daily_cap_usd)}, reason=reason)
|
|
171
|
+
if probe["depth"] == "none":
|
|
172
|
+
depth = "off"
|
|
173
|
+
except Exception: # noqa: BLE001 - the loop is best effort: when the plan cannot be made, keep the setting
|
|
174
|
+
pass
|
|
175
|
+
# LFS-B2, LFS-B4, LFS-B6: the level, the dry run and the hold decide the filing; the improvement mode has no part
|
|
176
|
+
level, why = prp.filing_level(spec, os.environ.get("TEMPERGRAPH_AUTONOMY"), loop_autonomy, lift)
|
|
177
|
+
held = level == "record"
|
|
178
|
+
filing = "held" if held else "dry_run" if dry_run else "file"
|
|
179
|
+
filing_source = (why if why in ("machine_hold", "declared_record") else "declared_record") if held else dry_source
|
|
180
|
+
# PRP-B26: a final exit of a workflow with a proposal to watch reads its pull request, a clean exit included
|
|
181
|
+
watch = final and not dry_run and not trial and level != "record" and (
|
|
182
|
+
prp.watching(root, spec.name) or bool(pr_later.pending(root, spec.name))) # OUT-B23: a recorded pull request too
|
|
183
|
+
if not (friction or outcome) and depth == "off" and not watch:
|
|
184
|
+
if final: # ALN-B24: a final exit that makes no ticket leaves one record; a pause leaves none
|
|
185
|
+
append_jsonl(loop_log(root, spec.name, task_id),
|
|
186
|
+
{"ts": now_iso(), "kind": "artifact_review_skipped", "reason": "no_ticket"})
|
|
187
|
+
return None
|
|
188
|
+
tid = uuid.uuid4().hex[:16]
|
|
189
|
+
artifact_block: dict[str, Any] | None = None
|
|
190
|
+
if final and (friction or outcome or depth != "off"): # ALN-B1: no new trigger; a watch-only ticket carries none
|
|
191
|
+
from tempergraph.model import flow
|
|
192
|
+
from tempergraph.package.manifest import declared_step_files
|
|
193
|
+
|
|
194
|
+
criteria = [{"unit": u, "id": str(c["id"]), "text": str(c["text"])}
|
|
195
|
+
for u, d in unit_decls(spec).items() for c in d["criteria"]]
|
|
196
|
+
if spec.outcome is not None:
|
|
197
|
+
criteria += [{"unit": flow.OUTCOME_UNIT, "id": str(c.id), "text": str(c.text)}
|
|
198
|
+
for c in spec.outcome.final]
|
|
199
|
+
artifact_block = {"setting": setting, "mode_ok": spec.improvement_mode == "dev" or prob,
|
|
200
|
+
"statement": spec.outcome.statement if spec.outcome is not None else "",
|
|
201
|
+
"step_files": list(declared_step_files(spec.package_root)), "criteria": criteria,
|
|
202
|
+
"base_branch": base_branch, "prompts": _prompts(spec)}
|
|
203
|
+
ticket = {"schema_version": 1, "ticket_id": tid, "thread": thread, "workflow": spec.name,
|
|
204
|
+
"workflow_version": spec.version, "task_id": task_id, "state_root": str(root),
|
|
205
|
+
"issue_repository": spec.issue_repository, "mode": spec.improvement_mode, "dry_run": dry_run,
|
|
206
|
+
"executor": judge_executor, "fingerprints": list(summary.get("fingerprints") or []),
|
|
207
|
+
"pause_fingerprints": list(summary.get("pause_fingerprints") or []), # SIL-B28: judged, never reviewed
|
|
208
|
+
"lenses": {"friction": friction, "outcome": outcome},
|
|
209
|
+
"outcome_calibrated": outcome and has_score(spec, "outcome", root), "at": now_iso(),
|
|
210
|
+
"review": depth, "review_reason": reason, "run_cost_usd": round(float(run_cost_usd or 0.0), 6),
|
|
211
|
+
"units": unit_decls(spec) if depth != "off" else {},
|
|
212
|
+
"autonomy": level, "issue_cap": issue_cap, "filing": filing, "filing_source": filing_source, "watch_only": not (friction or outcome) and depth == "off",
|
|
213
|
+
"daily_cap_usd": autonomy.daily_cap(spec.improvement_mode, daily_cap_usd),
|
|
214
|
+
"alias": loop_model or ALIAS, "effort": loop_effort or EFFORT, "trigger": trigger,
|
|
215
|
+
"package_root": str(spec.package_root) if spec.package_root else None,
|
|
216
|
+
"issue_labels": declared_labels(spec)}
|
|
217
|
+
if artifact_block is not None:
|
|
218
|
+
ticket["artifact"] = artifact_block
|
|
219
|
+
path = tickets_dir(home or home_path()) / f"{tid}.json"
|
|
220
|
+
write_json(path, ticket)
|
|
221
|
+
return path
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def started_for(root: Path, workflow: str, task_id: str, thread: str, trigger: str, home: Path | None = None) -> bool:
|
|
225
|
+
"""SIL-B31: a loop for this thread and trigger exists: a ticket waiting or claimed, or a `loop_started` record."""
|
|
226
|
+
folder = tickets_dir(home or home_path())
|
|
227
|
+
for path in [*folder.glob("*.json"), *folder.glob("*.claimed")] if folder.is_dir() else ():
|
|
228
|
+
try:
|
|
229
|
+
t = json.loads(path.read_text(encoding="utf-8"))
|
|
230
|
+
except (OSError, ValueError):
|
|
231
|
+
continue
|
|
232
|
+
if isinstance(t, dict) and t.get("thread") == thread and t.get("trigger") == trigger \
|
|
233
|
+
and str(t.get("state_root")) == str(root):
|
|
234
|
+
return True
|
|
235
|
+
try:
|
|
236
|
+
lines = loop_log(root, workflow, task_id).read_text(encoding="utf-8").splitlines()
|
|
237
|
+
except OSError:
|
|
238
|
+
return False
|
|
239
|
+
for ln in lines:
|
|
240
|
+
with contextlib.suppress(ValueError):
|
|
241
|
+
r = json.loads(ln)
|
|
242
|
+
if isinstance(r, dict) and r.get("kind") == "loop_started" and r.get("trigger") == trigger:
|
|
243
|
+
return True
|
|
244
|
+
return False
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def held_by_tickets(root: Path, thread: str, home: Path | None = None) -> set[str]:
|
|
248
|
+
"""SIL-B28: the fingerprints that a waiting or claimed ticket of the thread holds (`fingerprints` and
|
|
249
|
+
`pause_fingerprints`), read as `started_for` reads the tickets."""
|
|
250
|
+
folder = tickets_dir(home or home_path())
|
|
251
|
+
out: set[str] = set()
|
|
252
|
+
for path in [*folder.glob("*.json"), *folder.glob("*.claimed")] if folder.is_dir() else ():
|
|
253
|
+
try:
|
|
254
|
+
t = json.loads(path.read_text(encoding="utf-8"))
|
|
255
|
+
except (OSError, ValueError):
|
|
256
|
+
continue
|
|
257
|
+
if isinstance(t, dict) and t.get("thread") == thread and str(t.get("state_root")) == str(root):
|
|
258
|
+
out |= {str(x) for x in [*(t.get("fingerprints") or ()), *(t.get("pause_fingerprints") or ())]}
|
|
259
|
+
return out
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def recorded_judgements(root: Path, workflow: str, task_id: str) -> dict[str, dict[str, Any]]:
|
|
263
|
+
"""SIL-B49: the judge's answers recorded in the thread's loop log, the latest for each fingerprint; a failed read
|
|
264
|
+
gives none."""
|
|
265
|
+
out: dict[str, dict[str, Any]] = {}
|
|
266
|
+
try:
|
|
267
|
+
lines = loop_log(root, workflow, task_id).read_text(encoding="utf-8").splitlines()
|
|
268
|
+
except OSError:
|
|
269
|
+
return out
|
|
270
|
+
for ln in lines:
|
|
271
|
+
with contextlib.suppress(ValueError, TypeError, KeyError):
|
|
272
|
+
r = json.loads(ln)
|
|
273
|
+
if isinstance(r, dict) and r.get("kind") == "loop_judged":
|
|
274
|
+
for a in r.get("answers") or ():
|
|
275
|
+
out[str(a["fingerprint"])] = {"attributed": a["attributed"] is True,
|
|
276
|
+
"confidence": float(a["confidence"])}
|
|
277
|
+
return out
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def launch(home: Path | None = None) -> bool:
|
|
281
|
+
from tempergraph import detach
|
|
282
|
+
|
|
283
|
+
return detach.start("tempergraph.improve.child", ("drain",), home or home_path())
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def drain(home: Path | None = None, registry: Registry | None = None,
|
|
287
|
+
host: Callable[[], CodeHost] = GhCodeHost) -> list[dict[str, Any]]:
|
|
288
|
+
"""Claims and processes every waiting ticket, oldest first; one ticket's failure never stops the next."""
|
|
289
|
+
folder = tickets_dir(home or home_path())
|
|
290
|
+
done: list[dict[str, Any]] = []
|
|
291
|
+
for path in sorted(folder.glob("*.json"), key=lambda p: p.stat().st_mtime) if folder.is_dir() else ():
|
|
292
|
+
claim = path.with_suffix(".claimed")
|
|
293
|
+
try:
|
|
294
|
+
os.replace(path, claim) # one child per ticket
|
|
295
|
+
except OSError:
|
|
296
|
+
continue
|
|
297
|
+
try:
|
|
298
|
+
t = json.loads(claim.read_text(encoding="utf-8"))
|
|
299
|
+
done.append(process(t, registry or default_registry(), host()))
|
|
300
|
+
except Exception as exc: # noqa: BLE001 - the loop is best effort (SIL-B1)
|
|
301
|
+
done.append({"ticket": path.stem, "error": type(exc).__name__})
|
|
302
|
+
finally:
|
|
303
|
+
claim.unlink(missing_ok=True)
|
|
304
|
+
return done
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _history(root: Path, workflow: str, thread: str) -> list[dict[str, Any]]:
|
|
308
|
+
out: list[dict[str, Any]] = []
|
|
309
|
+
base = root / "runs" / workflow
|
|
310
|
+
for d in sorted(base.iterdir()) if base.is_dir() else ():
|
|
311
|
+
out += [f for f in read_findings(root, workflow, d.name) if f.get("thread") != thread]
|
|
312
|
+
return out
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _records(root: Path, workflow: str, task_id: str) -> list[dict[str, Any]]:
|
|
316
|
+
try:
|
|
317
|
+
lines = (run_dir(root, workflow, task_id) / "run.jsonl").read_text(encoding="utf-8").splitlines()
|
|
318
|
+
except OSError:
|
|
319
|
+
return []
|
|
320
|
+
out = []
|
|
321
|
+
for ln in lines:
|
|
322
|
+
with contextlib.suppress(ValueError):
|
|
323
|
+
r = json.loads(ln)
|
|
324
|
+
if isinstance(r, dict):
|
|
325
|
+
out.append(r)
|
|
326
|
+
return out
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _answered(findings: Sequence[Mapping[str, Any]], answers: Mapping[str, Mapping[str, str]]) -> str:
|
|
330
|
+
"""SIL-B37: one line for each finding of a paused segment: what answered the pause, in the words of `pause_facts`."""
|
|
331
|
+
rows = []
|
|
332
|
+
for f in findings:
|
|
333
|
+
a = answers.get(str(f.get("fingerprint")))
|
|
334
|
+
if a:
|
|
335
|
+
w = a["workspace"]
|
|
336
|
+
ruling = a.get("ruling", "not recorded")
|
|
337
|
+
given = a.get("operator_reason")
|
|
338
|
+
op_reason = f"operator reason `{given}`" if given in pause_facts.OPERATOR_REASONS \
|
|
339
|
+
else "operator reason not given"
|
|
340
|
+
rows.append(f"- `{f.get('fingerprint')}`: unit `{a.get('unit', '-')}` item `{a.get('item', '-')}`; "
|
|
341
|
+
f"reason `{a['reason']}`; decision `{a['decision']}`; caller `{a['caller']}`; "
|
|
342
|
+
f"ruling {'given' if ruling == 'given' else 'not given' if ruling == 'not given' else 'not recorded'}; "
|
|
343
|
+
f"feedback {a['feedback']}; touch `{a.get('touch', 'not recorded')}`; "
|
|
344
|
+
f"{op_reason}; "
|
|
345
|
+
f"workspace {w if w in ('changed', 'unchanged') else 'not recorded'}; "
|
|
346
|
+
f"next gate verdict `{a['next_gate']}`")
|
|
347
|
+
return "\n## What answered each pause\n" + "\n".join(rows) + "\n" if rows else ""
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def prompt(findings: Sequence[Mapping[str, Any]], records: Sequence[Mapping[str, Any]],
|
|
351
|
+
answers: Mapping[str, Mapping[str, str]] | None = None) -> str:
|
|
352
|
+
"""Metadata only: findings, what answered each paused segment's pause, and the last segment's record kinds per
|
|
353
|
+
unit with criterion ids."""
|
|
354
|
+
starts = [i for i, r in enumerate(records) if r.get("kind") == "run_started"] or [0]
|
|
355
|
+
bounds = list(zip(starts, [*starts[1:], len(records)], strict=False))
|
|
356
|
+
bound = {id(f): pause_facts.segment_of(f, records) for f in findings} # SIL-B51: the same binding as the facts row
|
|
357
|
+
# SIL-B45: every earlier segment that holds a bound listed finding, then the last segment
|
|
358
|
+
chosen = [b for b in bounds[:-1] if any(v == b for v in bound.values())] + [bounds[-1]]
|
|
359
|
+
rows = [f"- `{f.get('fingerprint')}` cause `{f.get('cause')}` class {f.get('class')} side `{f.get('side')}` "
|
|
360
|
+
f"unit `{(f['child'] + '/') if f.get('child') else ''}{f.get('unit') or '-'}` count {f.get('count')}"
|
|
361
|
+
+ (f" (a child of `{f.get('parent')}`: workflow `{f.get('workflow')}`)" if f.get("child") else "")
|
|
362
|
+
for f in findings]
|
|
363
|
+
sections = "".join(_segment_section(records[lo:hi], [f for f in findings if bound[id(f)] == (lo, hi)])
|
|
364
|
+
for lo, hi in chosen)
|
|
365
|
+
return BRIEF + "\n\n## Findings\n" + "\n".join(rows) + "\n" + _answered(findings, answers or {}) + sections
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _segment_section(seg_records: Sequence[Mapping[str, Any]], findings: Sequence[Mapping[str, Any]] = ()) -> str:
|
|
369
|
+
"""One segment's record kinds per unit with criterion ids, headed by its exit code and the reason of its pause (the
|
|
370
|
+
run's own exit reason for a segment that did not pause); never text (SIL-B45)."""
|
|
371
|
+
counts: dict[str, dict[str, int]] = {}
|
|
372
|
+
blockers: dict[str, set[str]] = {}
|
|
373
|
+
for r in seg_records:
|
|
374
|
+
unit = f"{r['child']}/{r.get('unit') or '-'}" if r.get("child") else str(r.get("unit") or "-") # SWF-B9
|
|
375
|
+
k = str(r.get("kind") or "")
|
|
376
|
+
counts.setdefault(unit, {})[k] = counts.get(unit, {}).get(k, 0) + 1
|
|
377
|
+
for cid in r.get("blockers") or () if k == "judgement" else ():
|
|
378
|
+
blockers.setdefault(unit, set()).add(str(cid))
|
|
379
|
+
done = next((r for r in reversed(seg_records) if r.get("kind") == "run_exit"), None)
|
|
380
|
+
head = ""
|
|
381
|
+
if done is not None and isinstance(done.get("exit_code"), int):
|
|
382
|
+
why = pause_facts.pause_reason(seg_records, findings) if done["exit_code"] == 3 else \
|
|
383
|
+
re.sub(r"[^A-Za-z0-9_.:-]", "", str(done.get("reason") or "-"))
|
|
384
|
+
head = f" (exit code {done['exit_code']}, reason {why})"
|
|
385
|
+
seg = [f"- `{u}`: " + ", ".join(f"{k} {n}" for k, n in sorted(c.items()))
|
|
386
|
+
+ (f"; blocked on {', '.join(sorted(blockers[u]))}" if u in blockers else "") for u, c in counts.items()]
|
|
387
|
+
return f"\n## The segment's records{head}\n" + "\n".join(seg) + "\n"
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def parse(text: str) -> dict[str, dict[str, Any]]:
|
|
391
|
+
blocks = FENCE.findall(text or "")
|
|
392
|
+
if not blocks:
|
|
393
|
+
return {}
|
|
394
|
+
try:
|
|
395
|
+
doc = json.loads(blocks[-1])
|
|
396
|
+
except ValueError:
|
|
397
|
+
return {}
|
|
398
|
+
out: dict[str, dict[str, Any]] = {}
|
|
399
|
+
for row in doc.get("findings") or [] if isinstance(doc, dict) else []:
|
|
400
|
+
if isinstance(row, dict) and isinstance(row.get("confidence"), (int, float)):
|
|
401
|
+
out[str(row.get("fingerprint"))] = {"attributed": row.get("attributed") is True,
|
|
402
|
+
"confidence": max(0.0, min(1.0, float(row["confidence"])))}
|
|
403
|
+
return out
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _latest(findings: Sequence[Mapping[str, Any]], fps: set[str]) -> list[Mapping[str, Any]]:
|
|
407
|
+
by: dict[str, Mapping[str, Any]] = {}
|
|
408
|
+
for f in findings:
|
|
409
|
+
if str(f.get("fingerprint")) in fps:
|
|
410
|
+
by[str(f.get("fingerprint"))] = f
|
|
411
|
+
return list(by.values())
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _retry_usage_limited(t: Mapping[str, Any], registry: Registry, log: Path, limited: Sequence[Mapping[str, Any]],
|
|
415
|
+
cost: dict[str, float], left: float | None) -> None:
|
|
416
|
+
"""SIL-B25, SIL-B26: wait for the latest reset reported within `review.retry_wait_hours` and run those reviews once
|
|
417
|
+
more, every record marked `retry`, within the money caps. Never waits in the foreground (`TEMPERGRAPH_LOOP=inline`)
|
|
418
|
+
or for an unknown or distant reset, and never runs a third time. A retry's failure is recorded and stops nothing."""
|
|
419
|
+
if mode() == "inline":
|
|
420
|
+
return
|
|
421
|
+
bound = clock() + float(params.value("review.retry_wait_hours")) * 3600
|
|
422
|
+
due = [e for e in limited if isinstance(e.get("resets_at"), int | float) and not isinstance(e.get("resets_at"), bool)
|
|
423
|
+
and float(e["resets_at"]) <= bound]
|
|
424
|
+
if not due:
|
|
425
|
+
return
|
|
426
|
+
try:
|
|
427
|
+
from tempergraph.improve import review
|
|
428
|
+
|
|
429
|
+
wait = max(float(e["resets_at"]) for e in due) - clock()
|
|
430
|
+
if wait > 0:
|
|
431
|
+
sleep(wait)
|
|
432
|
+
spent = cost["reported"] + cost["estimated_only"]
|
|
433
|
+
rv = review.run(t, registry, reason=str(t.get("review_reason") or "dev"),
|
|
434
|
+
keys=[str(e["session_key"]) for e in due], force_full=True, retry=True,
|
|
435
|
+
room=None if left is None else round(left - spent, 6))
|
|
436
|
+
cost["reported"] += rv["cost"]["reported"]
|
|
437
|
+
cost["estimated_only"] += rv["cost"]["estimated_only"]
|
|
438
|
+
except Exception as exc: # noqa: BLE001 - best effort (SIL-B1); the failure is a review that raised (SRV-B29)
|
|
439
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "review_failed", "error_class": "error",
|
|
440
|
+
"error": type(exc).__name__, "retry": True})
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def process(t: Mapping[str, Any], registry: Registry, host: CodeHost) -> dict[str, Any]:
|
|
444
|
+
root = Path(str(t["state_root"]))
|
|
445
|
+
wf, task, thread = str(t["workflow"]), str(t["task_id"]), str(t["thread"])
|
|
446
|
+
log = loop_log(root, wf, task)
|
|
447
|
+
judged_fps = {*(t.get("fingerprints") or ()), *(t.get("pause_fingerprints") or ())} # SIL-B28
|
|
448
|
+
mine = _latest(read_findings(root, wf, task), judged_fps)
|
|
449
|
+
faults = [f for f in mine if f.get("class") == "fault" and f.get("lens") not in ("outcome", "review")]
|
|
450
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_started", "ticket": t.get("ticket_id"),
|
|
451
|
+
"lenses": t.get("lenses"), "findings": len(mine), "trigger": t.get("trigger"),
|
|
452
|
+
"fingerprints": sorted(judged_fps),
|
|
453
|
+
"held": t.get("autonomy") == "record" or bool(t.get("dry_run"))}) # SIL-B47: handed again
|
|
454
|
+
escaped: list[tuple[dict[str, Any], str]] = [] # the escape findings this read recorded, with their run's task
|
|
455
|
+
if t.get("autonomy") != "record" and not t.get("dry_run"): # PRP-B26, PRP-B27, PRP-B28: best effort (SIL-B1)
|
|
456
|
+
try:
|
|
457
|
+
from tempergraph.improve import proposals as prp
|
|
458
|
+
|
|
459
|
+
prp.sync_pr_state(root, wf, host)
|
|
460
|
+
except Exception as exc: # noqa: BLE001
|
|
461
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_skipped", "step": "pr_state", "reason": "error",
|
|
462
|
+
"error": type(exc).__name__})
|
|
463
|
+
try: # OUT-B23, OUT-B24, OUT-B25: the pull requests that runs of the workflow recorded
|
|
464
|
+
# OUT-B30: one read at a time for the workflow, so overlapping reads leave one entry and one finding
|
|
465
|
+
with durability_lock.exclusive(root / "locks" / "pull-request-read" / f"{wf}.lock"):
|
|
466
|
+
for got in pr_later.read(root, wf, host):
|
|
467
|
+
if got.get("error"): # OUT-B31: one record, no text, and the other pull requests are read
|
|
468
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_skipped", "step": "pull_request_read",
|
|
469
|
+
"reason": "error", "thread": got["thread_id"], "number": got["number"],
|
|
470
|
+
"error": got["error"]})
|
|
471
|
+
continue
|
|
472
|
+
try: # OUT-B32: the finding follows the state, appended entry or not
|
|
473
|
+
lines = escape.record(root, wf, got["thread_id"], got["changed"]) # SIL-B33: no model call
|
|
474
|
+
except Exception as exc: # noqa: BLE001 - left to the next read
|
|
475
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_skipped", "step": "pull_request_read",
|
|
476
|
+
"reason": "error", "thread": got["thread_id"],
|
|
477
|
+
"error": type(exc).__name__})
|
|
478
|
+
continue
|
|
479
|
+
if lines and t.get("mode") == "stable": # SIL-B10: the outcome lens, for the earlier run
|
|
480
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_lens", "lens": "outcome",
|
|
481
|
+
"trigger": "outcome_escape", "thread": got["thread_id"]})
|
|
482
|
+
escaped += [(f, got["task"]) for f in lines]
|
|
483
|
+
except Exception as exc: # noqa: BLE001
|
|
484
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_skipped", "step": "pull_request_read", "reason": "error",
|
|
485
|
+
"error": type(exc).__name__})
|
|
486
|
+
try: # PRP-B9: a proposal that has just become merged is compared in the same ticket
|
|
487
|
+
from tempergraph.improve import release
|
|
488
|
+
|
|
489
|
+
release.compare_due(root, wf, host, filing.Outbox.at(root))
|
|
490
|
+
except Exception as exc: # noqa: BLE001
|
|
491
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_skipped", "step": "release", "reason": "error",
|
|
492
|
+
"error": type(exc).__name__})
|
|
493
|
+
if t.get("watch_only"): # ALN-B24: a watch-only ticket makes no artifact review, an escape or not
|
|
494
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "artifact_review_skipped", "reason": "watch_only"})
|
|
495
|
+
if t.get("watch_only") and not escaped: # a read of the pull request and nothing else: no judge, review, filing or ledger row
|
|
496
|
+
return {"ticket": t.get("ticket_id"), "thread": thread, "results": [], "cost": {"reported": 0.0,
|
|
497
|
+
"estimated_only": 0.0},
|
|
498
|
+
"acted": {}}
|
|
499
|
+
judged: dict[str, dict[str, Any]] = {}
|
|
500
|
+
cost = {"reported": 0.0, "estimated_only": 0.0}
|
|
501
|
+
left = autonomy.room(t, root) # SIL-B19, SIL-B20: stable mode's daily cap skips the judges; records are still written
|
|
502
|
+
capped = left is not None and left <= 0
|
|
503
|
+
if capped:
|
|
504
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_skipped", "step": "judges", "reason": "daily_cap"})
|
|
505
|
+
try: # FFD-B1: the answers recorded before this exit's own; a failed read gives none
|
|
506
|
+
earlier = filing.recorded_answers(root, wf, exclude=log) # this thread's one answer is counted once, by decide
|
|
507
|
+
except Exception: # noqa: BLE001 - best effort (SIL-B1)
|
|
508
|
+
earlier = {}
|
|
509
|
+
try: # FFD-B14: the workflow's threads that reached a final exit, read once; a failed read counts the exit's own
|
|
510
|
+
threads_final = filing.final_threads(root, wf, task)
|
|
511
|
+
except Exception: # noqa: BLE001 - best effort (SIL-B1)
|
|
512
|
+
threads_final = 1
|
|
513
|
+
try: # SIL-B37: what answered each pause; the loop is best effort (SIL-B1), so a failed read leaves it out
|
|
514
|
+
answered = pause_facts.of(root, wf, task, faults)
|
|
515
|
+
except Exception: # noqa: BLE001
|
|
516
|
+
answered = {}
|
|
517
|
+
recorded = recorded_judgements(root, wf, task) if (t.get("lenses") or {}).get("friction") else {}
|
|
518
|
+
unanswered = [f for f in faults if str(f.get("fingerprint")) not in recorded] # SIL-B49: one answer per fingerprint
|
|
519
|
+
judged = {k: v for k, v in recorded.items() if k in {str(f.get("fingerprint")) for f in faults}}
|
|
520
|
+
if (t.get("lenses") or {}).get("friction") and unanswered and not capped:
|
|
521
|
+
ex = registry.get(str(t.get("executor") or "claude"))
|
|
522
|
+
sdir = run_dir(root, wf, task) / "loop" / "sessions" / f"friction-{t.get('ticket_id')}"
|
|
523
|
+
req = SessionRequest(kind="judge", prompt=prompt(unanswered, _records(root, wf, task), answered), workdir=root,
|
|
524
|
+
alias=alias_of(t), session_key=f"loop.{t.get('ticket_id')}.judge", timeout_s=TIMEOUT_S,
|
|
525
|
+
session_dir=sdir, options=options_of(t))
|
|
526
|
+
res = ex.run_judge(req, ViewSet(), LiveSink(sdir))
|
|
527
|
+
if res.usage.reported_cost_usd is not None:
|
|
528
|
+
cost["reported"] += res.usage.reported_cost_usd
|
|
529
|
+
else:
|
|
530
|
+
cost["estimated_only"] += float(res.usage.estimated_cost_usd or estimate(res.usage, res.model) or 0.0)
|
|
531
|
+
got = parse(res.text) if res.ok else {}
|
|
532
|
+
judged.update({k: v for k, v in got.items() if k in {str(f.get("fingerprint")) for f in unanswered}})
|
|
533
|
+
answers = [{"fingerprint": str(f.get("fingerprint")), # SIL-B36: what the judge answered, none of its text
|
|
534
|
+
"confidence": got[str(f.get("fingerprint"))]["confidence"],
|
|
535
|
+
"attributed": got[str(f.get("fingerprint"))]["attributed"]}
|
|
536
|
+
for f in unanswered if str(f.get("fingerprint")) in got]
|
|
537
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_judged", "lens": "friction", "executor": ex.name,
|
|
538
|
+
"alias": alias_of(t), "effort": options_of(t).effort, "ok": res.ok, "parsed": bool(got), "usage": dataclasses.asdict(res.usage),
|
|
539
|
+
"session_id": res.session_id, "answers": answers})
|
|
540
|
+
limited: list[dict[str, Any]] = [] # SIL-B25: the reviews that failed as `usage_limit`, with the reported reset
|
|
541
|
+
categories: frozenset[str] = frozenset()
|
|
542
|
+
if str(t.get("review") or "off") != "off" and not capped: # SRV-B13, SRV-B14, SRV-B15, SIL-B17: before deciding and filing
|
|
543
|
+
try:
|
|
544
|
+
from tempergraph.improve import review
|
|
545
|
+
|
|
546
|
+
categories = frozenset(review.CATALOG)
|
|
547
|
+
spent = cost["reported"] + cost["estimated_only"] # the judges above came out of the day's room too
|
|
548
|
+
rv = review.run(t, registry, reason=str(t.get("review_reason") or "dev"),
|
|
549
|
+
room=None if left is None else round(left - spent, 6)) # SRV-B21, SIL-B20
|
|
550
|
+
cost["reported"] += rv["cost"]["reported"]
|
|
551
|
+
cost["estimated_only"] += rv["cost"]["estimated_only"]
|
|
552
|
+
limited = list(rv.get("usage_limit") or [])
|
|
553
|
+
except Exception as exc: # noqa: BLE001 - the review is best effort (SRV-B1, SRV-B20, SRV-B21, SRV-B22, SRV-B18)
|
|
554
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "review_failed", "error_class": "error",
|
|
555
|
+
"error": type(exc).__name__}) # SRV-B29: names no session, counts as one review
|
|
556
|
+
mine = _latest(read_findings(root, wf, task), judged_fps) # SRV-B7: now corroborated
|
|
557
|
+
if t.get("artifact"): # ALN-B1, ALN-B14, ALN-B16: after the session reviews, before the filing; files nothing
|
|
558
|
+
try:
|
|
559
|
+
from tempergraph.improve import artifact
|
|
560
|
+
|
|
561
|
+
spent = cost["reported"] + cost["estimated_only"]
|
|
562
|
+
av = artifact.run(t, registry, room=None if left is None else round(left - spent, 6), log=log)
|
|
563
|
+
cost["reported"] += av["cost"]["reported"]
|
|
564
|
+
cost["estimated_only"] += av["cost"]["estimated_only"]
|
|
565
|
+
except Exception as exc: # noqa: BLE001 - best effort (SIL-B1)
|
|
566
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "artifact_review_failed", "error_class": "error",
|
|
567
|
+
"error": type(exc).__name__})
|
|
568
|
+
cands: list[filing.Candidate] = []
|
|
569
|
+
context: dict[str, Any] = {"records": _records(root, wf, task), "mode": t.get("mode"), # ISS-B8 to ISS-B10
|
|
570
|
+
"judge_executor": t.get("executor")}
|
|
571
|
+
thread_findings = read_findings(root, wf, task)
|
|
572
|
+
for f in mine:
|
|
573
|
+
if f.get("lens") == "review": # SRV-B28: a finding made of review observations never files, in any run
|
|
574
|
+
continue
|
|
575
|
+
if f.get("lens") == "outcome": # SIL-B7: files only once the outcome gate's judge is `accepted` (JCL)
|
|
576
|
+
cands.append(filing.Candidate(finding=f, lens="outcome", calibrated=bool(t.get("outcome_calibrated")),
|
|
577
|
+
request_digest=f.get("request_digest"), issue_labels=t.get("issue_labels"),
|
|
578
|
+
review_categories=categories, **context))
|
|
579
|
+
continue
|
|
580
|
+
if not (t.get("lenses") or {}).get("friction"): # a review-only ticket files no friction finding
|
|
581
|
+
continue
|
|
582
|
+
j = judged.get(str(f.get("fingerprint")))
|
|
583
|
+
if str(f.get("cause") or "").split(":", 1)[0] == filing.THREAD_COUNT_CAUSE: # FFD-B8: the thread's count, all segments
|
|
584
|
+
f = {**f, "count": sum(int(g.get("count") or 0) for g in thread_findings
|
|
585
|
+
if g.get("fingerprint") == f.get("fingerprint"))}
|
|
586
|
+
cands.append(filing.Candidate(finding=f, lens="friction", confidence=j["confidence"] if j else None,
|
|
587
|
+
attributed=bool(j and j["attributed"]), request_digest=f.get("request_digest"),
|
|
588
|
+
earlier_answers=earlier.get(str(f.get("fingerprint")), ()),
|
|
589
|
+
threads_final=threads_final,
|
|
590
|
+
facts=answered.get(str(f.get("fingerprint")), {}),
|
|
591
|
+
issue_labels=t.get("issue_labels"), review_categories=categories, **context))
|
|
592
|
+
for f, etask in escaped: # SIL-B34: an escape finding files by the pattern rule, not by calibration
|
|
593
|
+
cands.append(filing.Candidate(finding=f, lens="outcome", calibrated=False, request_digest=f.get("request_digest"),
|
|
594
|
+
issue_labels=t.get("issue_labels"), review_categories=categories,
|
|
595
|
+
**{**context, "records": _records(root, wf, etask)}))
|
|
596
|
+
history = _history(root, wf, thread)
|
|
597
|
+
decisions = [filing.decide(c, history, str(t.get("issue_repository") or "")) for c in cands]
|
|
598
|
+
if t.get("autonomy") == "record": # PRP-B11: findings, evidence and ledger rows only
|
|
599
|
+
results = [{"op": "recorded", "fingerprint": d.candidate.finding.get("fingerprint"), "reason": "autonomy_record"}
|
|
600
|
+
for d in decisions]
|
|
601
|
+
else:
|
|
602
|
+
filed_at = filing_clock()
|
|
603
|
+
try: # ISS-B13, BND-B3: the "seen again" comments each issue got today over every workflow's runs; a failed read passes none
|
|
604
|
+
today: dict[tuple[str, int], int] | None = filing.comments_by_day(root, None, filed_at)
|
|
605
|
+
except Exception: # noqa: BLE001 - best effort (SIL-B1)
|
|
606
|
+
today = None
|
|
607
|
+
results = filing.file(decisions, host, filing.Outbox.at(root), dry_run=bool(t.get("dry_run")),
|
|
608
|
+
now=filed_at, comments_today=today, issue_cap=_ticket_cap(t))
|
|
609
|
+
by_fp = {str(d.candidate.finding.get("fingerprint")): d for d in decisions}
|
|
610
|
+
for r in results: # IMD-B21 loop events, ids and enums only
|
|
611
|
+
kind = {"filed": "issue_filed", "commented": "issue_commented"}.get(str(r.get("op")), "loop_result")
|
|
612
|
+
d = by_fp.get(str(r.get("fingerprint")))
|
|
613
|
+
extra: dict[str, Any] = {}
|
|
614
|
+
if d is not None and kind != "loop_result": # FFD-B5: why the issue was filed or commented
|
|
615
|
+
extra["reason"] = d.reason
|
|
616
|
+
if d is not None and d.counted and kind == "loop_result": # FFD-B4, FFD-B16: the figures, as numbers
|
|
617
|
+
extra.update({k: round(float(v), 2) if k == "share" else int(v) for k, v in d.counted.items()})
|
|
618
|
+
append_jsonl(log, {"ts": now_iso(), "kind": kind, **extra, **r})
|
|
619
|
+
acted: dict[str, Any] = {}
|
|
620
|
+
try: # PRP-B11: the loop's own proposal and trial, after its judges and within the day's room
|
|
621
|
+
repeats = [str(f["fingerprint"]) for f in read_findings(root, wf, task) # SRV-B28: the review's own findings
|
|
622
|
+
if f.get("lens") == "review" and f.get("class") == "fault" and f.get("fingerprint")] # go to the proposer
|
|
623
|
+
acted = autonomy.act({**t, "fingerprints": sorted({*map(str, t.get("fingerprints") or ()), *repeats})},
|
|
624
|
+
registry, host, log)
|
|
625
|
+
except Exception as exc: # noqa: BLE001 - best effort (SIL-B1)
|
|
626
|
+
append_jsonl(log, {"ts": now_iso(), "kind": "loop_skipped", "step": "propose", "reason": "error",
|
|
627
|
+
"error": type(exc).__name__})
|
|
628
|
+
_retry_usage_limited(t, registry, log, limited, cost, left) # SIL-B25, SIL-B26: once, before the summary
|
|
629
|
+
try: # SIL-B22: one summary per ticket for `attention` and the detail document; never stops the loop
|
|
630
|
+
from tempergraph.improve import loop_summary
|
|
631
|
+
|
|
632
|
+
append_jsonl(log, loop_summary.build(root, wf, task, results, filing=t.get("filing"),
|
|
633
|
+
filing_source=t.get("filing_source"),
|
|
634
|
+
issue_cap=_ticket_cap(t)))
|
|
635
|
+
except Exception: # noqa: BLE001 - best effort (SIL-B1)
|
|
636
|
+
pass
|
|
637
|
+
Ledger(path=root / "ledger.jsonl").append({"kind": "loop", "thread_id": thread, "workflow": wf,
|
|
638
|
+
"workflow_version": t.get("workflow_version"), "cost": cost,
|
|
639
|
+
"ops": sorted({str(r.get("op")) for r in results})})
|
|
640
|
+
return {"ticket": t.get("ticket_id"), "thread": thread, "results": results, "cost": cost, "acted": acted}
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def main(argv: Sequence[str]) -> int:
|
|
644
|
+
if list(argv) != ["drain"]:
|
|
645
|
+
return 2
|
|
646
|
+
drain()
|
|
647
|
+
return 0
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
if __name__ == "__main__":
|
|
651
|
+
sys.exit(main(sys.argv[1:]))
|