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
|
File without changes
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The engine code log (LOS-B13): JSON lines, one file per process per day, scrubbed.
|
|
2
|
+
|
|
3
|
+
Read-only verbs log only to standard error (OVR-B15): they never call :func:`attach`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import traceback
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from tempergraph.security.scrub import scrub
|
|
16
|
+
|
|
17
|
+
_context: dict[str, object] = {}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def set_context(**kv: object) -> None:
|
|
21
|
+
_context.update(kv)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class JsonLineHandler(logging.Handler):
|
|
25
|
+
def __init__(self, folder: Path, worker: str | None = None) -> None:
|
|
26
|
+
super().__init__()
|
|
27
|
+
self.folder = folder
|
|
28
|
+
self.worker = worker
|
|
29
|
+
|
|
30
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
31
|
+
try:
|
|
32
|
+
day = datetime.now(UTC).strftime("%Y-%m-%d")
|
|
33
|
+
path = self.folder / f"{day}-{os.getpid()}.jsonl"
|
|
34
|
+
line: dict[str, object] = {
|
|
35
|
+
"ts": datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
|
36
|
+
"level": record.levelname,
|
|
37
|
+
"logger": record.name,
|
|
38
|
+
"pid": os.getpid(),
|
|
39
|
+
"msg": scrub(record.getMessage()),
|
|
40
|
+
}
|
|
41
|
+
for k in ("thread_id", "seq"):
|
|
42
|
+
if k in _context:
|
|
43
|
+
line[k] = _context[k]
|
|
44
|
+
if self.worker:
|
|
45
|
+
line["worker"] = self.worker
|
|
46
|
+
if record.exc_info and record.exc_info[0] is not None:
|
|
47
|
+
line["exc_type"] = record.exc_info[0].__name__
|
|
48
|
+
line["traceback"] = scrub("".join(traceback.format_exception(*record.exc_info))[-4000:])
|
|
49
|
+
fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
50
|
+
try:
|
|
51
|
+
os.write(fd, (json.dumps(line) + "\n").encode())
|
|
52
|
+
finally:
|
|
53
|
+
os.close(fd)
|
|
54
|
+
except Exception: # best effort, OVR-B4
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def level() -> int:
|
|
59
|
+
name = os.environ.get("TEMPERGRAPH_LOG_LEVEL", "INFO").upper()
|
|
60
|
+
return getattr(logging, name, logging.INFO)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def attach(state_root: Path, worker: str | None = None) -> None:
|
|
64
|
+
"""Route the `tempergraph` logger to `<state root>/engine/`."""
|
|
65
|
+
folder = state_root / "engine"
|
|
66
|
+
folder.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
67
|
+
logger = logging.getLogger("tempergraph")
|
|
68
|
+
logger.setLevel(level())
|
|
69
|
+
for h in list(logger.handlers):
|
|
70
|
+
if isinstance(h, JsonLineHandler):
|
|
71
|
+
logger.removeHandler(h)
|
|
72
|
+
logger.addHandler(JsonLineHandler(folder, worker))
|
|
73
|
+
logger.propagate = False
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""State-root and home layouts with their manifests (LOS-B7, LOS-B8, LOS-B9, LOS-B10, LOS-B11; WSP-B8, WSP-B9, WSP-B11 OVR-B12).
|
|
2
|
+
|
|
3
|
+
Read-only callers use the ``*_path`` helpers, which create nothing (OVR-B15). Only
|
|
4
|
+
:func:`ensure_state_root` and :func:`ensure_home` create folders, owner-only.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import socket
|
|
11
|
+
import uuid
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from tempergraph import git
|
|
16
|
+
from tempergraph.constants import ENGINE_VERSION, STORE_LAYOUT
|
|
17
|
+
from tempergraph.docs import read_json, write_json
|
|
18
|
+
|
|
19
|
+
STATE_DIR = ".tempergraph"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class NotInRepository(Exception):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class LayoutNewer(Exception):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def now_iso() -> str:
|
|
31
|
+
return datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
ROOT_VAR = "TEMPERGRAPH_STATE_ROOT"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def state_root_path(start_dir: Path) -> Path:
|
|
38
|
+
"""`<main checkout>/.tempergraph/`, from git's common directory, whatever the start dir (WSP-AC1).
|
|
39
|
+
|
|
40
|
+
Outside git (WSP-B15 to WSP-B18): the declared root, else the nearest folder upward that holds a state root with a
|
|
41
|
+
manifest, else `<start dir>/.tempergraph/`. The home folder is never a state root.
|
|
42
|
+
"""
|
|
43
|
+
main = git.main_checkout(start_dir)
|
|
44
|
+
if main is not None:
|
|
45
|
+
return main / STATE_DIR
|
|
46
|
+
home = home_path().resolve()
|
|
47
|
+
declared = os.environ.get(ROOT_VAR)
|
|
48
|
+
if declared:
|
|
49
|
+
root = Path(declared).expanduser()
|
|
50
|
+
root = (root if root.is_absolute() else start_dir / root).resolve()
|
|
51
|
+
else:
|
|
52
|
+
here = start_dir.resolve()
|
|
53
|
+
found = next((d / STATE_DIR for d in (here, *here.parents)
|
|
54
|
+
if (d / STATE_DIR / "manifest.json").is_file() and (d / STATE_DIR).resolve() != home), None)
|
|
55
|
+
root = found or here / STATE_DIR
|
|
56
|
+
if root.resolve() == home:
|
|
57
|
+
raise NotInRepository(f"{root} is the engine's home folder; start in another folder or name a state root "
|
|
58
|
+
f"with --state-root or {ROOT_VAR}")
|
|
59
|
+
return root
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def outside_git(start_dir: Path) -> bool:
|
|
63
|
+
return git.main_checkout(start_dir) is None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def home_path() -> Path:
|
|
67
|
+
return Path(os.environ.get("TEMPERGRAPH_HOME") or Path.home() / STATE_DIR)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _manifest(kind: str) -> dict[str, object]:
|
|
71
|
+
return {
|
|
72
|
+
"schema_version": 1,
|
|
73
|
+
"kind": kind,
|
|
74
|
+
"layout": STORE_LAYOUT,
|
|
75
|
+
"engine_version": ENGINE_VERSION,
|
|
76
|
+
"created_at": now_iso(),
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _check_layout(manifest_path: Path) -> None:
|
|
81
|
+
if manifest_path.exists():
|
|
82
|
+
data = read_json(manifest_path, "store_manifest")
|
|
83
|
+
layout = data.get("layout")
|
|
84
|
+
if isinstance(layout, int) and layout > STORE_LAYOUT:
|
|
85
|
+
raise LayoutNewer(f"{manifest_path.parent} has layout {layout}; this engine writes {STORE_LAYOUT}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def ensure_state_root(root: Path) -> Path:
|
|
89
|
+
"""Create the state root (owner-only) with its manifest and its own .gitignore (LOS-B4)."""
|
|
90
|
+
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
91
|
+
os.chmod(root, 0o700)
|
|
92
|
+
manifest = root / "manifest.json"
|
|
93
|
+
_check_layout(manifest)
|
|
94
|
+
if not manifest.exists():
|
|
95
|
+
write_json(manifest, _manifest("state_root"))
|
|
96
|
+
else: # MIG-B9, MIG-B10, MIG-B5: the first writing verb of a newer engine moves the store forward
|
|
97
|
+
from tempergraph.store import migrate
|
|
98
|
+
|
|
99
|
+
migrate.migrate(root, target=STORE_LAYOUT, engine=ENGINE_VERSION, older_live=migrate.older_live)
|
|
100
|
+
ignore = root / ".gitignore"
|
|
101
|
+
if not ignore.exists():
|
|
102
|
+
ignore.write_text("*\n", encoding="utf-8")
|
|
103
|
+
os.chmod(ignore, 0o600)
|
|
104
|
+
for sub in ("config", "checkpoints", "locks", "runs", "engine", "scratch"):
|
|
105
|
+
(root / sub).mkdir(exist_ok=True, mode=0o700)
|
|
106
|
+
return root
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def ensure_home(home: Path | None = None) -> Path:
|
|
110
|
+
home = home or home_path()
|
|
111
|
+
home.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
112
|
+
manifest = home / "manifest.json"
|
|
113
|
+
_check_layout(manifest)
|
|
114
|
+
if not manifest.exists():
|
|
115
|
+
write_json(manifest, _manifest("home"))
|
|
116
|
+
machine = home / "machine.json"
|
|
117
|
+
if not machine.exists():
|
|
118
|
+
write_json(machine, {"schema_version": 1, "machine_id": str(uuid.uuid4()),
|
|
119
|
+
"label": socket.gethostname(), "created_at": now_iso()})
|
|
120
|
+
return home
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def run_dir(root: Path, workflow: str, task_id: str) -> Path:
|
|
124
|
+
return root / "runs" / workflow / task_id
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def session_dir(root: Path, workflow: str, task_id: str, session_key: str) -> Path:
|
|
128
|
+
return run_dir(root, workflow, task_id) / "sessions" / session_key
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def checkpoint_path(root: Path, workflow: str, fmt: int | None = None) -> Path:
|
|
132
|
+
"""The checkpoint database of one checkpoint format (MIG-B12, MIG-B13, MIG-B14): this engine's own unless `fmt` names
|
|
133
|
+
another. Format 1 keeps the plain name, so engines of two formats never share a file."""
|
|
134
|
+
if fmt is None:
|
|
135
|
+
from tempergraph.release import release
|
|
136
|
+
|
|
137
|
+
fmt = int(release().get("checkpoint_format") or 1)
|
|
138
|
+
return root / "checkpoints" / (f"{workflow}.sqlite" if fmt == 1 else f"{workflow}.f{fmt}.sqlite")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def lock_path(root: Path, workflow: str, task_id: str) -> Path:
|
|
142
|
+
return root / "locks" / workflow / f"{task_id}.lock"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
SHARED_STATE_ROOT_FILES = (
|
|
146
|
+
"ledger.jsonl", "filing-outbox.jsonl", "filing-bindings.json", "runs/aliases.json", "checkpoints/",
|
|
147
|
+
"locks/repository.lock", "locks/pull-request-read/", "tickets/", "engine/", "scratch/", "improve/",
|
|
148
|
+
)
|
|
149
|
+
"""What every thread's runs write in the state root outside the thread's run folder and lock files (LOS-B19), as paths
|
|
150
|
+
relative to the state root: an entry ending in `/` names a folder and everything under it."""
|
|
151
|
+
|
|
152
|
+
SHARED_HOME_FILES = (
|
|
153
|
+
"manifest.json", "machine.json", "request_key", "index.json", "stats/", "supervision/", "improve/tickets/",
|
|
154
|
+
"hooks/tickets/", "outbox/", "fleet/",
|
|
155
|
+
)
|
|
156
|
+
"""What every thread's runs write in the home folder (LOS-B20), as paths relative to the home folder."""
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _shared(rel: str, entries: tuple[str, ...]) -> bool:
|
|
160
|
+
rel = rel.replace("\\", "/")
|
|
161
|
+
parent, _, name = rel.rpartition("/")
|
|
162
|
+
for entry in entries:
|
|
163
|
+
if entry.endswith("/"):
|
|
164
|
+
if rel.startswith(entry):
|
|
165
|
+
return True
|
|
166
|
+
continue
|
|
167
|
+
if rel == entry:
|
|
168
|
+
return True
|
|
169
|
+
# the lock (`<stem>.lock`, as `with_suffix` names it) and the hidden temporary file (`.<name>.<random>`)
|
|
170
|
+
# that the atomic writes leave beside a listed file
|
|
171
|
+
e_parent, _, e_name = entry.rpartition("/")
|
|
172
|
+
stem, dot, _ = e_name.rpartition(".") # an entry with no suffix (`request_key`) has no lock name
|
|
173
|
+
if parent == e_parent and ((bool(dot) and name == stem + ".lock") or name.startswith(f".{e_name}.")):
|
|
174
|
+
return True
|
|
175
|
+
# the holder record that the run lock writes beside a listed lock (`<stem>.holder.json`) and its hidden
|
|
176
|
+
# temporary file
|
|
177
|
+
if parent == e_parent and e_name.endswith(".lock"):
|
|
178
|
+
holder = stem + ".holder.json"
|
|
179
|
+
if name == holder or name.startswith(f".{holder}."):
|
|
180
|
+
return True
|
|
181
|
+
return False
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def shared_file_in_state_root(rel: str) -> bool:
|
|
185
|
+
"""Whether `rel`, a path relative to the state root, is a file every thread's runs share (LOS-B19): a listed
|
|
186
|
+
entry, a path under a listed folder, or the lock or temporary file beside a listed file."""
|
|
187
|
+
return _shared(rel, SHARED_STATE_ROOT_FILES)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def shared_file_in_home(rel: str) -> bool:
|
|
191
|
+
"""Whether `rel`, a path relative to the home folder, is a file every thread's runs share (LOS-B20)."""
|
|
192
|
+
return _shared(rel, SHARED_HOME_FILES)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def session_key(unit: str, attempt: int, kind: str, item: str | None = None, n: int | None = None) -> str:
|
|
196
|
+
"""`<unit>[.<item>].<attempt>.<kind>[.<n>]` (EVT-B8, EVT-B9)."""
|
|
197
|
+
parts = [unit] + ([item] if item else []) + [str(attempt), kind] + ([str(n)] if n is not None else [])
|
|
198
|
+
return ".".join(parts)
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""The local store's verbs (LOS-B14, LOS-B15) and retention (LOS-B16): `logs`, `store usage|prune|export`.
|
|
2
|
+
|
|
3
|
+
`logs` and `store usage` read only (OVR-B15); `store prune --dry-run` reads only too. `store prune` removes
|
|
4
|
+
what the retention rule allows of finished threads and never touches a run log, a session's `meta.json`, a
|
|
5
|
+
checkpoint, the ledger or stats. `store export` packs one run after a scrub pass over every text file.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
import tarfile
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from tempergraph.constants import ExitCode
|
|
23
|
+
from tempergraph.durability.lock import is_held
|
|
24
|
+
from tempergraph.security.scrub import scrub
|
|
25
|
+
from tempergraph.store.layout import lock_path, run_dir
|
|
26
|
+
|
|
27
|
+
DAY = 86_400.0
|
|
28
|
+
KINDS = ("run", "raw", "activity", "stderr", "check", "hook", "engine")
|
|
29
|
+
|
|
30
|
+
#: LOS-B16: what `store prune` removes by default and after how many days.
|
|
31
|
+
SESSION_LOGS = ("raw.jsonl", "activity.jsonl", "stderr.log", "output")
|
|
32
|
+
LOG_DAYS = 30
|
|
33
|
+
EVIDENCE_DAYS = 90
|
|
34
|
+
ENGINE_DAYS = 14
|
|
35
|
+
WARN_BYTES = 2 * 1024**3
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _size(path: Path) -> int:
|
|
39
|
+
if path.is_file():
|
|
40
|
+
try:
|
|
41
|
+
return path.stat().st_size
|
|
42
|
+
except OSError:
|
|
43
|
+
return 0
|
|
44
|
+
total = 0
|
|
45
|
+
for dirpath, _dirs, files in os.walk(path):
|
|
46
|
+
for f in files:
|
|
47
|
+
with contextlib.suppress(OSError):
|
|
48
|
+
total += (Path(dirpath) / f).stat().st_size
|
|
49
|
+
return total
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def kind_of(rel: Path) -> str:
|
|
53
|
+
"""The LOS-B7, LOS-B8, LOS-B9 kind of a file under a run folder, by its place."""
|
|
54
|
+
parts = rel.parts
|
|
55
|
+
if parts[0] == "sessions" and len(parts) >= 3:
|
|
56
|
+
name = parts[2]
|
|
57
|
+
return {"raw.jsonl": "raw", "activity.jsonl": "activity", "stderr.log": "stderr", "output": "output",
|
|
58
|
+
"tools.jsonl": "tools", "meta.json": "meta", "live.json": "live"}.get(name, "session")
|
|
59
|
+
if parts[0] in ("checks", "hooks", "evidence"):
|
|
60
|
+
return parts[0].rstrip("s") if parts[0] != "evidence" else "evidence"
|
|
61
|
+
if rel.name == "run.jsonl":
|
|
62
|
+
return "run"
|
|
63
|
+
return "record"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, kw_only=True)
|
|
67
|
+
class Thread:
|
|
68
|
+
workflow: str
|
|
69
|
+
task_id: str
|
|
70
|
+
folder: Path
|
|
71
|
+
running: bool
|
|
72
|
+
exit_code: int | None
|
|
73
|
+
ended_at: float | None # epoch seconds of the last segment's end
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def thread_id(self) -> str:
|
|
77
|
+
return f"{self.workflow}/{self.task_id}"
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def finished(self) -> bool:
|
|
81
|
+
"""Ended and not resumable by a person's decision: finished, stopped or failed; never paused or live."""
|
|
82
|
+
return not self.running and self.exit_code is not None and self.exit_code != ExitCode.PAUSED
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def failed(self) -> bool:
|
|
86
|
+
return self.finished and self.exit_code != ExitCode.FINISHED
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def threads(root: Path) -> Iterator[Thread]:
|
|
90
|
+
"""Every run folder under the state root, whether or not its workflow is in the catalog."""
|
|
91
|
+
runs = root / "runs"
|
|
92
|
+
if not runs.is_dir():
|
|
93
|
+
return
|
|
94
|
+
for wf in sorted(p for p in runs.iterdir() if p.is_dir()):
|
|
95
|
+
for task in sorted(p for p in wf.iterdir() if p.is_dir()):
|
|
96
|
+
ex = task / "exit.json"
|
|
97
|
+
code: int | None = None
|
|
98
|
+
ended: float | None = None
|
|
99
|
+
if ex.exists():
|
|
100
|
+
try:
|
|
101
|
+
code = int(json.loads(ex.read_text(encoding="utf-8")).get("exit_code"))
|
|
102
|
+
ended = ex.stat().st_mtime
|
|
103
|
+
except (OSError, ValueError, TypeError):
|
|
104
|
+
code = None
|
|
105
|
+
yield Thread(workflow=wf.name, task_id=task.name, folder=task,
|
|
106
|
+
running=is_held(lock_path(root, wf.name, task.name)), exit_code=code, ended_at=ended)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# -- logs ------------------------------------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def run_files(t: Thread) -> list[dict[str, Any]]:
|
|
113
|
+
"""`logs <selector>` with no `--kind`: the run's files with their kinds and sizes."""
|
|
114
|
+
out = []
|
|
115
|
+
for path in sorted(p for p in t.folder.rglob("*") if p.is_file()):
|
|
116
|
+
rel = path.relative_to(t.folder)
|
|
117
|
+
out.append({"path": str(rel), "kind": kind_of(rel), "bytes": _size(path)})
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def log_path(root: Path, t: Thread, kind: str, session: str | None) -> list[Path]:
|
|
122
|
+
"""The file(s) one `--kind` names. `check` takes `--session <unit>[.<attempt>]`; `engine` filters by thread."""
|
|
123
|
+
if kind == "run":
|
|
124
|
+
return [t.folder / "run.jsonl"]
|
|
125
|
+
if kind in ("raw", "activity", "stderr"):
|
|
126
|
+
if not session:
|
|
127
|
+
raise LookupError(f"--kind {kind} needs --session <session_key>")
|
|
128
|
+
name = {"raw": "raw.jsonl", "activity": "activity.jsonl", "stderr": "stderr.log"}[kind]
|
|
129
|
+
return [t.folder / "sessions" / session / name]
|
|
130
|
+
if kind == "check":
|
|
131
|
+
base = t.folder / "checks"
|
|
132
|
+
if session:
|
|
133
|
+
unit, _, attempt = session.partition(".")
|
|
134
|
+
base = base / unit / attempt if attempt else base / unit
|
|
135
|
+
return sorted(p for p in base.rglob("*") if p.is_file()) if base.exists() else []
|
|
136
|
+
if kind == "hook":
|
|
137
|
+
base = t.folder / "hooks"
|
|
138
|
+
return sorted(base.glob("*.log")) if base.exists() else []
|
|
139
|
+
if kind == "engine":
|
|
140
|
+
return sorted((root / "engine").glob("*.jsonl")) if (root / "engine").exists() else []
|
|
141
|
+
raise LookupError(f"unknown --kind {kind!r}; one of {', '.join(KINDS)}")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def read_lines(paths: list[Path], kind: str, thread_id: str) -> Iterator[str]:
|
|
145
|
+
for path in paths:
|
|
146
|
+
try:
|
|
147
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
148
|
+
except OSError:
|
|
149
|
+
continue
|
|
150
|
+
for line in text.splitlines():
|
|
151
|
+
if kind == "engine":
|
|
152
|
+
try:
|
|
153
|
+
if json.loads(line).get("thread_id") != thread_id:
|
|
154
|
+
continue
|
|
155
|
+
except ValueError:
|
|
156
|
+
continue
|
|
157
|
+
yield line
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def follow(path: Path, live: Any, poll_s: float = 0.5, timeout_s: float | None = None) -> Iterator[str]:
|
|
161
|
+
"""New lines of one file while `live()` holds; stat first, read second (MADR `poll-files-and-read-only-verbs` of the monitor)."""
|
|
162
|
+
offset = 0
|
|
163
|
+
start = time.monotonic()
|
|
164
|
+
while True:
|
|
165
|
+
try:
|
|
166
|
+
size = path.stat().st_size
|
|
167
|
+
except OSError:
|
|
168
|
+
size = 0
|
|
169
|
+
if size < offset:
|
|
170
|
+
offset = 0
|
|
171
|
+
if size > offset:
|
|
172
|
+
with open(path, "rb") as fh:
|
|
173
|
+
fh.seek(offset)
|
|
174
|
+
chunk = fh.read(size - offset)
|
|
175
|
+
end = chunk.rfind(b"\n")
|
|
176
|
+
if end >= 0:
|
|
177
|
+
yield from chunk[: end + 1].decode("utf-8", errors="replace").splitlines()
|
|
178
|
+
offset += end + 1
|
|
179
|
+
if not live() or (timeout_s is not None and time.monotonic() - start > timeout_s):
|
|
180
|
+
return
|
|
181
|
+
time.sleep(poll_s)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# -- usage and prune -----------------------------------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@dataclass(kw_only=True)
|
|
188
|
+
class Plan:
|
|
189
|
+
"""What `store prune` removes (or would, with `--dry-run`), and what it refused."""
|
|
190
|
+
|
|
191
|
+
remove: list[Path] = field(default_factory=list)
|
|
192
|
+
refused: list[dict[str, str]] = field(default_factory=list)
|
|
193
|
+
kept_failed: list[str] = field(default_factory=list)
|
|
194
|
+
|
|
195
|
+
def bytes(self) -> int:
|
|
196
|
+
return sum(_size(p) for p in self.remove)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def prunable(t: Thread, now: float, older_than_days: float = LOG_DAYS, keep_failed: bool = True) -> list[Path]:
|
|
200
|
+
"""LOS-B16 for one thread: session logs, check output and hook logs past `older_than_days`, evidence past 90."""
|
|
201
|
+
if not t.finished or t.ended_at is None or (keep_failed and t.failed):
|
|
202
|
+
return []
|
|
203
|
+
age = (now - t.ended_at) / DAY
|
|
204
|
+
out: list[Path] = []
|
|
205
|
+
if age >= older_than_days:
|
|
206
|
+
sessions = t.folder / "sessions"
|
|
207
|
+
if sessions.is_dir():
|
|
208
|
+
for s in sorted(p for p in sessions.iterdir() if p.is_dir()):
|
|
209
|
+
out += [s / n for n in SESSION_LOGS if (s / n).exists()]
|
|
210
|
+
checks = t.folder / "checks"
|
|
211
|
+
if checks.is_dir():
|
|
212
|
+
out += sorted(p for p in checks.rglob("*") if p.is_file() and p.name != "result.json")
|
|
213
|
+
hooks = t.folder / "hooks"
|
|
214
|
+
if hooks.is_dir():
|
|
215
|
+
out += sorted(hooks.glob("*.log"))
|
|
216
|
+
if age >= max(EVIDENCE_DAYS, older_than_days) and (t.folder / "evidence").is_dir():
|
|
217
|
+
out.append(t.folder / "evidence")
|
|
218
|
+
return out
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def plan_prune(root: Path, now: float | None = None, older_than_days: float = LOG_DAYS,
|
|
222
|
+
keep_failed: bool = True) -> Plan:
|
|
223
|
+
now = time.time() if now is None else now
|
|
224
|
+
plan = Plan()
|
|
225
|
+
for t in threads(root):
|
|
226
|
+
if t.running:
|
|
227
|
+
plan.refused.append({"thread_id": t.thread_id, "reason": "running"})
|
|
228
|
+
continue
|
|
229
|
+
if keep_failed and t.failed and t.ended_at is not None and (now - t.ended_at) / DAY >= older_than_days:
|
|
230
|
+
plan.kept_failed.append(t.thread_id)
|
|
231
|
+
plan.remove += prunable(t, now, older_than_days, keep_failed)
|
|
232
|
+
engine = root / "engine"
|
|
233
|
+
if engine.is_dir():
|
|
234
|
+
for f in sorted(engine.glob("*.jsonl")):
|
|
235
|
+
try:
|
|
236
|
+
if (now - f.stat().st_mtime) / DAY >= ENGINE_DAYS:
|
|
237
|
+
plan.remove.append(f)
|
|
238
|
+
except OSError:
|
|
239
|
+
pass
|
|
240
|
+
return plan
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def apply(plan: Plan) -> list[str]:
|
|
244
|
+
"""Removes the plan's paths; a path that cannot be removed is reported, the others go on (OVR-B4)."""
|
|
245
|
+
failed = []
|
|
246
|
+
for p in plan.remove:
|
|
247
|
+
try:
|
|
248
|
+
if p.is_dir():
|
|
249
|
+
shutil.rmtree(p)
|
|
250
|
+
else:
|
|
251
|
+
p.unlink(missing_ok=True)
|
|
252
|
+
except OSError as exc:
|
|
253
|
+
failed.append(f"{p}: {type(exc).__name__}")
|
|
254
|
+
return failed
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def usage(root: Path, now: float | None = None) -> dict[str, Any]:
|
|
258
|
+
"""`store usage`: size per thread and per kind, the total, and the threads past the retention rule."""
|
|
259
|
+
now = time.time() if now is None else now
|
|
260
|
+
per_thread: list[dict[str, Any]] = []
|
|
261
|
+
by_kind: dict[str, int] = {}
|
|
262
|
+
for t in threads(root):
|
|
263
|
+
kinds: dict[str, int] = {}
|
|
264
|
+
for f in run_files(t):
|
|
265
|
+
kinds[f["kind"]] = kinds.get(f["kind"], 0) + f["bytes"]
|
|
266
|
+
for k, v in kinds.items():
|
|
267
|
+
by_kind[k] = by_kind.get(k, 0) + v
|
|
268
|
+
per_thread.append({"thread_id": t.thread_id, "bytes": sum(kinds.values()), "by_kind": kinds,
|
|
269
|
+
"past_retention": bool(prunable(t, now)),
|
|
270
|
+
"state": "running" if t.running else "ended" if t.exit_code is not None else "unknown"})
|
|
271
|
+
other = {name: _size(root / name) for name in ("checkpoints", "engine", "batches", "backups", "upgrades",
|
|
272
|
+
"authoring", "scratch") if (root / name).exists()}
|
|
273
|
+
ledger = root / "ledger.jsonl"
|
|
274
|
+
if ledger.exists():
|
|
275
|
+
other["ledger"] = _size(ledger)
|
|
276
|
+
total = sum(int(t["bytes"]) for t in per_thread) + sum(other.values())
|
|
277
|
+
warnings = []
|
|
278
|
+
if total > WARN_BYTES:
|
|
279
|
+
warnings.append(f"the state root holds {total / 1024**3:.1f} GB; `tempergraph store prune` lists what "
|
|
280
|
+
"the retention rule allows to remove")
|
|
281
|
+
return {"schema_version": 1, "state_root": str(root), "total_bytes": total, "by_kind": by_kind,
|
|
282
|
+
"other": other, "threads": per_thread, "warnings": warnings}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
# -- export -----------------------------------------------------------------------------------------------
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _is_text(data: bytes) -> bool:
|
|
289
|
+
return b"\0" not in data[:8192]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def export(t: Thread, target: Path) -> dict[str, Any]:
|
|
293
|
+
"""Packs one run's folder as `<workflow>/<task_id>/…` in a tar.gz, every text file scrubbed (LOS-AC3)."""
|
|
294
|
+
scrubbed = skipped = 0
|
|
295
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
296
|
+
with tarfile.open(target, "w:gz") as tar:
|
|
297
|
+
for path in sorted(p for p in t.folder.rglob("*") if p.is_file()):
|
|
298
|
+
rel = Path(t.workflow) / t.task_id / path.relative_to(t.folder)
|
|
299
|
+
try:
|
|
300
|
+
data = path.read_bytes()
|
|
301
|
+
except OSError:
|
|
302
|
+
skipped += 1
|
|
303
|
+
continue
|
|
304
|
+
if not _is_text(data):
|
|
305
|
+
skipped += 1 # binary files are left out: the scrub pass cannot read them
|
|
306
|
+
continue
|
|
307
|
+
clean = scrub(data.decode("utf-8", errors="replace")).encode("utf-8")
|
|
308
|
+
scrubbed += 1
|
|
309
|
+
info = tarfile.TarInfo(str(rel))
|
|
310
|
+
info.size = len(clean)
|
|
311
|
+
info.mode = 0o600
|
|
312
|
+
info.mtime = int(path.stat().st_mtime)
|
|
313
|
+
tar.addfile(info, io.BytesIO(clean))
|
|
314
|
+
os.chmod(target, 0o600)
|
|
315
|
+
return {"schema_version": 1, "thread_id": t.thread_id, "archive": str(target), "files": scrubbed,
|
|
316
|
+
"left_out": skipped}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def find(root: Path, thread_id: str) -> Thread:
|
|
320
|
+
wf, _, task = thread_id.partition("/")
|
|
321
|
+
folder = run_dir(root, wf, task)
|
|
322
|
+
for t in threads(root):
|
|
323
|
+
if t.folder == folder:
|
|
324
|
+
return t
|
|
325
|
+
raise LookupError(f"{thread_id} has no run folder")
|