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