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
tempergraph/identity.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Pseudonymous join keys for the ledger (IMD-B5, R12): the machine id, the repository and request digests.
|
|
2
|
+
|
|
3
|
+
The machine id is the random id of `<home>/machine.json`, never a host name. The repository digest is the
|
|
4
|
+
SHA-256 of the normalized `origin` remote URL (no scheme, no credentials, no `.git`, lower case), cut to 16 hex;
|
|
5
|
+
None when the repository has no `origin`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from tempergraph.git import git
|
|
16
|
+
from tempergraph.store.layout import ensure_home, home_path
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def machine_id(home: Path | None = None) -> str | None:
|
|
20
|
+
try:
|
|
21
|
+
h = ensure_home(home or home_path())
|
|
22
|
+
doc = json.loads((h / "machine.json").read_text(encoding="utf-8"))
|
|
23
|
+
except Exception: # noqa: BLE001 - a missing id never stops a run (OVR-B4)
|
|
24
|
+
return None
|
|
25
|
+
return str(doc.get("machine_id")) if isinstance(doc, dict) and doc.get("machine_id") else None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def normalize_remote(url: str) -> str:
|
|
29
|
+
u = url.strip()
|
|
30
|
+
scheme = re.match(r"^[a-z+]+://", u)
|
|
31
|
+
u = u[scheme.end():] if scheme else u
|
|
32
|
+
u = re.sub(r"^[^@/]+@", "", u) # user and token
|
|
33
|
+
if not scheme: # scp-like `host:path`
|
|
34
|
+
u = u.replace(":", "/", 1)
|
|
35
|
+
u = re.sub(r"\.git$", "", u.rstrip("/"))
|
|
36
|
+
return u.lower()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def repo_id(main: Path | None) -> str | None:
|
|
40
|
+
if main is None:
|
|
41
|
+
return None
|
|
42
|
+
url = git(["config", "--get", "remote.origin.url"], main, check=False).strip()
|
|
43
|
+
if not url:
|
|
44
|
+
return None
|
|
45
|
+
return hashlib.sha256(normalize_remote(url).encode()).hexdigest()[:16]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def request_digest(text: str, home: Path | None = None) -> str | None:
|
|
49
|
+
"""IMD-B16: a keyed hash with a per-installation key, so equal requests match without the text."""
|
|
50
|
+
import hmac
|
|
51
|
+
import os
|
|
52
|
+
import secrets
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
h = ensure_home(home or home_path())
|
|
56
|
+
key_file = h / "request_key"
|
|
57
|
+
if not key_file.exists():
|
|
58
|
+
key_file.write_text(secrets.token_hex(32), encoding="utf-8")
|
|
59
|
+
if os.name == "posix":
|
|
60
|
+
os.chmod(key_file, 0o600)
|
|
61
|
+
key = key_file.read_text(encoding="utf-8").strip().encode()
|
|
62
|
+
except OSError:
|
|
63
|
+
return None
|
|
64
|
+
norm = " ".join(text.split()).lower().encode()
|
|
65
|
+
return hmac.new(key, norm, hashlib.sha256).hexdigest()[:16]
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
"""Cause analysis of one cluster (CAN): the record store.
|
|
2
|
+
|
|
3
|
+
Records live under the state root: `improve/analyses/<analysis_id>.json`, one per analysis, whatever its
|
|
4
|
+
state (`recorded`, `no_cause_found`, `refused`). Session files live in `improve/analyses/sessions/`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
import shutil
|
|
12
|
+
import uuid
|
|
13
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from tempergraph.docs import write_json
|
|
19
|
+
from tempergraph.improve.proposals import SIDE, Added, ProposalError, _request_shingles, literal_hits
|
|
20
|
+
from tempergraph.improve.review import FENCE
|
|
21
|
+
from tempergraph.store.layout import now_iso
|
|
22
|
+
|
|
23
|
+
ANALYSES_DIR = "improve/analyses"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def new_analysis_id() -> str:
|
|
27
|
+
return uuid.uuid4().hex[:12]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def analyses_dir(root: Path) -> Path:
|
|
31
|
+
return root / ANALYSES_DIR
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def write_record(root: Path, rec: Mapping[str, Any]) -> dict[str, Any]:
|
|
35
|
+
out = {"schema_version": 1, **dict(rec)}
|
|
36
|
+
write_json(analyses_dir(root) / f"{out['analysis_id']}.json", out)
|
|
37
|
+
return out
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def load_analysis(root: Path, analysis_id: str) -> dict[str, Any]:
|
|
41
|
+
if not re.match(r"^[A-Za-z0-9_-]{1,64}$", analysis_id):
|
|
42
|
+
raise ProposalError(f"{analysis_id!r} is not an analysis id")
|
|
43
|
+
path = analyses_dir(root) / f"{analysis_id}.json"
|
|
44
|
+
if not path.is_file():
|
|
45
|
+
raise ProposalError(f"no analysis {analysis_id}")
|
|
46
|
+
return _read(path)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _read(path: Path) -> dict[str, Any]:
|
|
50
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
51
|
+
if not isinstance(data, dict):
|
|
52
|
+
raise ValueError(f"{path}: not a JSON object")
|
|
53
|
+
return data
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def list_records(root: Path, workflow: str) -> list[dict[str, Any]]:
|
|
57
|
+
"""Every readable record of the workflow; a file that cannot be read is skipped."""
|
|
58
|
+
out: list[dict[str, Any]] = []
|
|
59
|
+
d = analyses_dir(root)
|
|
60
|
+
if not d.is_dir():
|
|
61
|
+
return out
|
|
62
|
+
for p in sorted(d.glob("*.json")):
|
|
63
|
+
try:
|
|
64
|
+
rec = _read(p)
|
|
65
|
+
except Exception:
|
|
66
|
+
continue
|
|
67
|
+
if rec.get("workflow") == workflow and "analysis_id" in rec:
|
|
68
|
+
out.append(rec)
|
|
69
|
+
return out
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def newest(root: Path, workflow: str, cluster_id: str) -> dict[str, Any] | None:
|
|
73
|
+
"""The record of the cluster with the latest `at`, then the greater `analysis_id`."""
|
|
74
|
+
mine = [r for r in list_records(root, workflow) if r.get("cluster_id") == cluster_id]
|
|
75
|
+
if not mine:
|
|
76
|
+
return None
|
|
77
|
+
return max(mine, key=lambda r: (str(r.get("at", "")), str(r["analysis_id"])))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def summary(rec: Mapping[str, Any] | None) -> dict[str, Any] | None:
|
|
81
|
+
if rec is None:
|
|
82
|
+
return None
|
|
83
|
+
return {"analysis_id": rec["analysis_id"], "state": rec["state"]}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
PLACE_WORDS = ("engine", "environment", "request")
|
|
87
|
+
CLASSES = frozenset(SIDE) | frozenset(PLACE_WORDS) # PRP-B14's change classes and the three place words (CAN-B18)
|
|
88
|
+
_KEYS = frozenset({"cause", "place", "remedy_class", "evidence", "candidates", "confidence"})
|
|
89
|
+
_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class Reply:
|
|
94
|
+
"""A readable analysis reply (CAN-B29): sentences whitespace-joined."""
|
|
95
|
+
|
|
96
|
+
cause: str
|
|
97
|
+
place: str
|
|
98
|
+
remedy_class: str
|
|
99
|
+
evidence: list[str]
|
|
100
|
+
candidates: list[dict[str, Any]]
|
|
101
|
+
confidence: float
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True)
|
|
105
|
+
class NoCause:
|
|
106
|
+
"""A reply that says no cause was found (CAN-B15)."""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _sentence(v: Any) -> str | None:
|
|
110
|
+
if not isinstance(v, str):
|
|
111
|
+
return None
|
|
112
|
+
s = " ".join(v.split())
|
|
113
|
+
return s or None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def read_reply(text: str) -> Reply | NoCause | None:
|
|
117
|
+
"""CAN-B16, CAN-B29, CAN-B18: the last fenced JSON block of a reply, or None when it cannot be read."""
|
|
118
|
+
blocks = FENCE.findall(text)
|
|
119
|
+
if not blocks:
|
|
120
|
+
return None
|
|
121
|
+
try:
|
|
122
|
+
d = json.loads(blocks[-1])
|
|
123
|
+
except ValueError:
|
|
124
|
+
return None
|
|
125
|
+
if not isinstance(d, dict):
|
|
126
|
+
return None
|
|
127
|
+
if d == {"no_cause_found": True}:
|
|
128
|
+
return NoCause()
|
|
129
|
+
if set(d) != _KEYS:
|
|
130
|
+
return None
|
|
131
|
+
cause, place, cls = _sentence(d["cause"]), _sentence(d["place"]), d["remedy_class"]
|
|
132
|
+
conf, ev, cands = d["confidence"], d["evidence"], d["candidates"]
|
|
133
|
+
if cause is None or place is None or not isinstance(cls, str):
|
|
134
|
+
return None
|
|
135
|
+
if place in PLACE_WORDS:
|
|
136
|
+
if cls != place:
|
|
137
|
+
return None
|
|
138
|
+
elif cls not in CLASSES or cls in PLACE_WORDS:
|
|
139
|
+
return None
|
|
140
|
+
if isinstance(conf, bool) or not isinstance(conf, (int, float)) or not 0 <= conf <= 1:
|
|
141
|
+
return None
|
|
142
|
+
if not isinstance(ev, list) or not all(isinstance(e, str) for e in ev):
|
|
143
|
+
return None
|
|
144
|
+
if not isinstance(cands, list):
|
|
145
|
+
return None
|
|
146
|
+
out: list[dict[str, Any]] = []
|
|
147
|
+
for c in cands:
|
|
148
|
+
if not isinstance(c, dict) or set(c) != {"files", "change", "test"}:
|
|
149
|
+
return None
|
|
150
|
+
files, change, test = c["files"], _sentence(c["change"]), _sentence(c["test"])
|
|
151
|
+
if not isinstance(files, list) or not all(isinstance(f, str) for f in files) or change is None or test is None:
|
|
152
|
+
return None
|
|
153
|
+
out.append({"files": list(files), "change": change, "test": test})
|
|
154
|
+
return Reply(cause=cause, place=place, remedy_class=cls, evidence=list(ev), candidates=out,
|
|
155
|
+
confidence=float(conf))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _engine_side(cluster: Mapping[str, Any]) -> bool:
|
|
159
|
+
side = str(cluster.get("side") or "")
|
|
160
|
+
return side == "engine" or side.startswith("executor:")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _line_ok(root: Path, rel: str, line: int) -> bool:
|
|
164
|
+
try:
|
|
165
|
+
base = root.resolve()
|
|
166
|
+
path = (base / rel).resolve()
|
|
167
|
+
path.relative_to(base)
|
|
168
|
+
if not path.is_file():
|
|
169
|
+
return False
|
|
170
|
+
return line >= 1 and len(path.read_text(encoding="utf-8").splitlines()) >= line
|
|
171
|
+
except (OSError, ValueError, UnicodeDecodeError):
|
|
172
|
+
return False
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def check_citations(ids: Sequence[str], cluster: Mapping[str, Any], member_runs: Sequence[str], package_dir: Path,
|
|
176
|
+
engine_source: Path | None) -> list[str]:
|
|
177
|
+
"""CAN-B8, CAN-B9, CAN-B20: the ids that fail, as written and in order; no model is called."""
|
|
178
|
+
findings = {str(x) for x in cluster.get("findings") or ()}
|
|
179
|
+
roots = [package_dir] + ([engine_source] if engine_source is not None and _engine_side(cluster) else [])
|
|
180
|
+
bad: list[str] = []
|
|
181
|
+
for i in ids:
|
|
182
|
+
kind, _, rest = i.partition(":")
|
|
183
|
+
ok = False
|
|
184
|
+
if kind == "finding":
|
|
185
|
+
ok = rest in findings
|
|
186
|
+
elif kind == "run":
|
|
187
|
+
ok = rest in member_runs
|
|
188
|
+
elif kind == "file":
|
|
189
|
+
rel, _, n = rest.rpartition(":")
|
|
190
|
+
ok = bool(rel) and n.isdigit() and any(_line_ok(r, rel, int(n)) for r in roots)
|
|
191
|
+
if not ok:
|
|
192
|
+
bad.append(i)
|
|
193
|
+
return bad
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _outside(path: str) -> bool:
|
|
197
|
+
return path.startswith("/") or ".." in Path(path).parts
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def judge_reply(reply: Reply | NoCause, *, root: Path, workflow: str, cluster: Mapping[str, Any],
|
|
201
|
+
member_runs: Sequence[str], package_dir: Path, engine_source: Path | None) -> dict[str, Any]:
|
|
202
|
+
"""CAN-B14: the record body of a reply, with at most one refusal, the first of the fixed order."""
|
|
203
|
+
if isinstance(reply, NoCause):
|
|
204
|
+
return {"state": "no_cause_found", "refusal": None, "cause": None, "place": None, "remedy_class": None,
|
|
205
|
+
"evidence": [], "candidates": [], "confidence": None}
|
|
206
|
+
body: dict[str, Any] = {"cause": reply.cause, "place": reply.place, "remedy_class": reply.remedy_class,
|
|
207
|
+
"evidence": list(reply.evidence), "candidates": [dict(c) for c in reply.candidates],
|
|
208
|
+
"confidence": reply.confidence}
|
|
209
|
+
file_place = reply.place not in PLACE_WORDS
|
|
210
|
+
refusal: str | None = None
|
|
211
|
+
missing: list[str] = []
|
|
212
|
+
if not 1 <= len(reply.candidates) <= 3:
|
|
213
|
+
refusal = "candidates"
|
|
214
|
+
elif not reply.evidence or (file_place and any(not c["files"] for c in reply.candidates)):
|
|
215
|
+
refusal = "uncited"
|
|
216
|
+
else:
|
|
217
|
+
missing = check_citations(reply.evidence, cluster, member_runs, package_dir, engine_source)
|
|
218
|
+
if missing:
|
|
219
|
+
refusal = "citation_missing"
|
|
220
|
+
elif (file_place and _outside(reply.place)) or any(_outside(f) for c in reply.candidates for f in c["files"]):
|
|
221
|
+
refusal = "outside_package"
|
|
222
|
+
else:
|
|
223
|
+
sentences = [reply.cause, *(s for c in reply.candidates for s in (c["change"], c["test"]))]
|
|
224
|
+
shingles = _request_shingles(root, workflow, [f"{workflow}/{r}" for r in member_runs])
|
|
225
|
+
added = [Added(file="reply", text=s, ranges=((0, len(s)),)) for s in sentences]
|
|
226
|
+
if literal_hits(added, shingles):
|
|
227
|
+
refusal = "literal"
|
|
228
|
+
if refusal is None:
|
|
229
|
+
return {"state": "recorded", "refusal": None, **body}
|
|
230
|
+
out = {"state": "refused", "refusal": refusal, **body}
|
|
231
|
+
if refusal == "citation_missing":
|
|
232
|
+
out["missing"] = missing
|
|
233
|
+
return out
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class AnalysisRefused(ValueError):
|
|
237
|
+
"""The verb refuses before any session or write: an unknown cluster, no package folder, a zero cap."""
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
REASK_SUFFIX = "End with the JSON block only."
|
|
241
|
+
reask_suffix = REASK_SUFFIX # CAN-B16: appended to the prompt of the one re-ask
|
|
242
|
+
READ_TOOLS = ("read", "search", "list") # CAN-B5: no tool that writes or runs a command
|
|
243
|
+
_REPLY_SHAPE = (
|
|
244
|
+
'{"cause": "<one sentence>", "place": "<a package path, or engine, environment or request>", '
|
|
245
|
+
'"remedy_class": "<a change class of the package files, or the place word>", '
|
|
246
|
+
'"evidence": ["finding:<fingerprint>", "run:<run>", "file:<path>:<line>"], '
|
|
247
|
+
'"candidates": [{"files": ["<package path>"], "change": "<one sentence>", "test": "<one sentence>"}], '
|
|
248
|
+
'"confidence": <0 to 1>}'
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def build_prompt(cluster: Mapping[str, Any], findings: Sequence[Mapping[str, Any]], member_runs: Sequence[str],
|
|
253
|
+
observations: str, citable: Sequence[str]) -> str:
|
|
254
|
+
"""CAN-B7: the cluster's facts, each member finding and run, the kept observations (datamarked), the citable ids."""
|
|
255
|
+
facts = (f"- cause: {cluster.get('cause')}\n- unit: {cluster.get('unit')}\n- side: {cluster.get('side')}\n"
|
|
256
|
+
f"- runs: {cluster.get('runs')}, distinct requests: {cluster.get('distinct_requests')}\n"
|
|
257
|
+
f"- findings: {len(findings)}\n")
|
|
258
|
+
lines = "\n".join(json.dumps(dict(f), sort_keys=True, default=str) for f in findings)
|
|
259
|
+
return (
|
|
260
|
+
"You find the cause of one cluster of findings the engine recorded across runs of a workflow. Your folder is "
|
|
261
|
+
"the workflow package; you may read, search and list files, and nothing else. Do not change any file.\n\n"
|
|
262
|
+
f"## Cluster\n{facts}\n## Member findings\n{lines}\n\n## Member runs\n" + "\n".join(member_runs) + "\n"
|
|
263
|
+
+ observations
|
|
264
|
+
+ "\n## Evidence you may cite\n" + "\n".join(citable)
|
|
265
|
+
+ "\nand `file:<path>:<line>` for a line of a file you read (a path inside the package; for a cluster of the "
|
|
266
|
+
"engine or an executor, a line of the engine's source folder). Every id is checked by the engine.\n\n"
|
|
267
|
+
"## Reply\nName one cause, where it lies, and one to three candidate changes (never a ticket id, URL, number or "
|
|
268
|
+
"quotation from a run). Cite at least one id. End with one fenced JSON block (three backticks, `json`) of this "
|
|
269
|
+
f"shape:\n{_REPLY_SHAPE}\nor, when no cause can be shown, {{\"no_cause_found\": true}}. Only the last "
|
|
270
|
+
"fenced block is read.\n")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _covered(package: Path) -> list[Path]:
|
|
274
|
+
"""The files `package_digest` covers, as paths relative to the package."""
|
|
275
|
+
out: list[Path] = []
|
|
276
|
+
for p in sorted(package.rglob("*")):
|
|
277
|
+
rel = p.relative_to(package)
|
|
278
|
+
if p.is_file() and rel.parts[0] not in ("evals", ".git") and "__pycache__" not in rel.parts:
|
|
279
|
+
out.append(rel)
|
|
280
|
+
return out
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _guarded(package_dir: Path, session_dir: Path, run: Callable[[], Any]) -> tuple[Any, Exception | None, bool]:
|
|
284
|
+
"""CAN-B6, CAN-B30: run a session with a copy of the covered files kept; whatever happens, restore them (a changed
|
|
285
|
+
file rewritten, a created one removed), and report whether the digest differed."""
|
|
286
|
+
from tempergraph.improve.proposals import package_digest
|
|
287
|
+
|
|
288
|
+
before = session_dir / "before"
|
|
289
|
+
digest = package_digest(package_dir)
|
|
290
|
+
kept = _covered(package_dir)
|
|
291
|
+
for rel in kept:
|
|
292
|
+
(before / rel).parent.mkdir(parents=True, exist_ok=True)
|
|
293
|
+
(before / rel).write_bytes((package_dir / rel).read_bytes())
|
|
294
|
+
res: Any = None
|
|
295
|
+
err: Exception | None = None
|
|
296
|
+
changed = False
|
|
297
|
+
try:
|
|
298
|
+
try:
|
|
299
|
+
res = run()
|
|
300
|
+
except Exception as exc: # noqa: BLE001 - a failed session is a record, and the package is restored below
|
|
301
|
+
err = exc
|
|
302
|
+
changed = package_digest(package_dir) != digest
|
|
303
|
+
finally:
|
|
304
|
+
keep = set(kept)
|
|
305
|
+
for rel in _covered(package_dir):
|
|
306
|
+
if rel not in keep:
|
|
307
|
+
(package_dir / rel).unlink()
|
|
308
|
+
for parent in (package_dir / rel).parents:
|
|
309
|
+
if parent == package_dir or any(parent.iterdir()):
|
|
310
|
+
break
|
|
311
|
+
parent.rmdir()
|
|
312
|
+
for rel in kept:
|
|
313
|
+
want = (before / rel).read_bytes()
|
|
314
|
+
target = package_dir / rel
|
|
315
|
+
if not target.is_file() or target.read_bytes() != want:
|
|
316
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
317
|
+
target.write_bytes(want)
|
|
318
|
+
shutil.rmtree(before, ignore_errors=True)
|
|
319
|
+
return res, err, changed
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@dataclass
|
|
323
|
+
class Asked:
|
|
324
|
+
"""What `ask` saw: the readable reply (or none), the failure, the spend, and whether the package changed."""
|
|
325
|
+
|
|
326
|
+
reply: Reply | NoCause | None
|
|
327
|
+
failure: dict[str, Any] | None
|
|
328
|
+
spend: dict[str, Any]
|
|
329
|
+
changed: bool
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def ask(*, executor: Any, prompt: str, package_dir: Path, session_root: Path, analysis_id: str, cap: float,
|
|
333
|
+
read_roots: tuple[Path, ...]) -> Asked:
|
|
334
|
+
"""CAN-B16, CAN-B25, CAN-B27, CAN-B31: at most two sessions; each gets what the cap leaves."""
|
|
335
|
+
from tempergraph.contracts import EventSink, SessionOptions, SessionRequest
|
|
336
|
+
from tempergraph.improve.review import ALIAS, EFFORT, TIMEOUT_S, _failure_class
|
|
337
|
+
from tempergraph.run.log import estimate
|
|
338
|
+
|
|
339
|
+
spend: dict[str, Any] = {"sessions": 0, "reported_cost_usd": 0.0, "estimated_cost_usd": 0.0}
|
|
340
|
+
takes_cap = "cost_cap_usd" in executor.capabilities().session_options
|
|
341
|
+
failure: dict[str, Any] | None = None
|
|
342
|
+
for n in (1, 2):
|
|
343
|
+
left = cap - spend["reported_cost_usd"] - spend["estimated_cost_usd"]
|
|
344
|
+
if left <= 1e-9:
|
|
345
|
+
return Asked(None, {"error_class": "cap_reached"}, spend, False)
|
|
346
|
+
sdir = session_root / f"{analysis_id}.{n}"
|
|
347
|
+
sdir.mkdir(parents=True, exist_ok=True)
|
|
348
|
+
req = SessionRequest(
|
|
349
|
+
kind="step", prompt=prompt if n == 1 else f"{prompt}\n\n{REASK_SUFFIX}", workdir=package_dir,
|
|
350
|
+
alias=ALIAS, session_key=f"analyse.{analysis_id}.{n}.step", tools=READ_TOOLS, timeout_s=TIMEOUT_S,
|
|
351
|
+
session_dir=sdir, enforce_tools=True, read_roots=read_roots,
|
|
352
|
+
options=SessionOptions(effort=EFFORT, cost_cap_usd=left if takes_cap else None)) # type: ignore[arg-type]
|
|
353
|
+
def session(r: SessionRequest = req) -> Any:
|
|
354
|
+
return executor.run_step(r, EventSink())
|
|
355
|
+
|
|
356
|
+
res, err, changed = _guarded(package_dir, sdir, session)
|
|
357
|
+
spend["sessions"] += 1
|
|
358
|
+
if res is not None:
|
|
359
|
+
if res.usage.reported_cost_usd is not None:
|
|
360
|
+
spend["reported_cost_usd"] += float(res.usage.reported_cost_usd)
|
|
361
|
+
else:
|
|
362
|
+
spend["estimated_cost_usd"] += float(res.usage.estimated_cost_usd or estimate(res.usage, res.model) or 0.0)
|
|
363
|
+
if changed:
|
|
364
|
+
return Asked(None, None, spend, True)
|
|
365
|
+
if err is not None or res is None:
|
|
366
|
+
return Asked(None, {"error_class": "error"}, spend, False)
|
|
367
|
+
if not res.ok:
|
|
368
|
+
return Asked(None, {"error_class": _failure_class(res)}, spend, False)
|
|
369
|
+
reply = read_reply(res.text or "")
|
|
370
|
+
if reply is not None:
|
|
371
|
+
return Asked(reply, None, spend, False)
|
|
372
|
+
failure = {"error_class": "unparsed"}
|
|
373
|
+
return Asked(None, failure, spend, False)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _empty_body() -> dict[str, Any]:
|
|
377
|
+
return {"cause": None, "place": None, "remedy_class": None, "evidence": [], "candidates": [], "confidence": None}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def analyse(root: Path, spec: Any, cluster_id: str, executor: Any, engine_source: Path | None = None) -> dict[str, Any]:
|
|
381
|
+
"""CAN-B1 to CAN-B31: one read-only session on one cluster and the checked record, written under `improve/analyses/`.
|
|
382
|
+
No code host is called; nothing outside the record and its session folder is written."""
|
|
383
|
+
from tempergraph.constants import EXECUTOR_NAMES
|
|
384
|
+
from tempergraph.improve import params
|
|
385
|
+
from tempergraph.improve import proposals as prp
|
|
386
|
+
|
|
387
|
+
wf = spec.name
|
|
388
|
+
ex_name = getattr(executor, "name", None)
|
|
389
|
+
if ex_name not in EXECUTOR_NAMES:
|
|
390
|
+
raise AnalysisRefused(f"improve analyse: unknown executor {ex_name!r}")
|
|
391
|
+
try:
|
|
392
|
+
cl = prp.cluster(root, wf, cluster_id)
|
|
393
|
+
except ProposalError as exc:
|
|
394
|
+
raise AnalysisRefused(str(exc)) from exc
|
|
395
|
+
pkg = spec.package_root
|
|
396
|
+
if pkg is None or not Path(pkg).is_dir():
|
|
397
|
+
raise AnalysisRefused(f"improve analyse: {wf} has no package folder")
|
|
398
|
+
pkg = Path(pkg)
|
|
399
|
+
cap = float(params.value("analysis.cap_usd"))
|
|
400
|
+
if cap <= 0:
|
|
401
|
+
raise AnalysisRefused("improve analyse: analysis.cap_usd is 0, so no session starts")
|
|
402
|
+
listed = next((c for c in prp.clusters(root, wf) if cluster_id in (c["cluster_id"], c.get("twin_of"))), cl)
|
|
403
|
+
fps = {str(x) for x in cl.get("findings") or ()}
|
|
404
|
+
findings = [f for f in prp._findings(root, wf) if str(f.get("fingerprint")) in fps]
|
|
405
|
+
runs = prp._member_runs(root, wf, cl)
|
|
406
|
+
citable = [f"finding:{fp}" for fp in sorted(fps)] + [f"run:{r}" for r in runs]
|
|
407
|
+
engine_side = _engine_side(cl)
|
|
408
|
+
src: Path | None = None
|
|
409
|
+
if engine_side:
|
|
410
|
+
src = Path(engine_source) if engine_source is not None else Path(__file__).resolve().parents[1]
|
|
411
|
+
prompt = build_prompt(cl, findings, runs, prp._observations_block(root, wf, cl), citable)
|
|
412
|
+
aid = new_analysis_id()
|
|
413
|
+
got = ask(executor=executor, prompt=prompt, package_dir=pkg, session_root=analyses_dir(root) / "sessions",
|
|
414
|
+
analysis_id=aid, cap=cap, read_roots=(src,) if src is not None else ())
|
|
415
|
+
head = {"analysis_id": aid, "workflow": wf, "cluster_id": listed["cluster_id"], "base_version": spec.version,
|
|
416
|
+
"author": "person", "spend": got.spend}
|
|
417
|
+
if got.changed:
|
|
418
|
+
rec = base_record(state="refused", refusal="changed_package", **head, **_empty_body())
|
|
419
|
+
elif got.reply is not None:
|
|
420
|
+
body = judge_reply(got.reply, root=root, workflow=wf, cluster=cl, member_runs=runs, package_dir=pkg,
|
|
421
|
+
engine_source=src)
|
|
422
|
+
rec = base_record(**head, **body)
|
|
423
|
+
elif got.failure is not None and got.failure["error_class"] == "unparsed":
|
|
424
|
+
rec = base_record(state="refused", refusal="unparsed", **head, **_empty_body())
|
|
425
|
+
else:
|
|
426
|
+
rec = base_record(state="refused", refusal="session_failed", error_class=(got.failure or {}).get("error_class"),
|
|
427
|
+
**head, **_empty_body())
|
|
428
|
+
return write_record(root, rec)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def base_record(*, analysis_id: str, workflow: str, cluster_id: str | None, base_version: str, author: str,
|
|
432
|
+
state: str, refusal: str | None, spend: Mapping[str, Any],
|
|
433
|
+
**extra: Any) -> dict[str, Any]:
|
|
434
|
+
"""The body every record holds, whatever its state (CAN-B17); `extra` adds the state's own fields."""
|
|
435
|
+
return {"analysis_id": analysis_id, "workflow": workflow, "cluster_id": cluster_id,
|
|
436
|
+
"base_version": base_version, "author": author, "at": now_iso(), "state": state,
|
|
437
|
+
"refusal": refusal, "spend": dict(spend), **extra}
|