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,797 @@
|
|
|
1
|
+
"""Supervision cost (SCO): the journal hosts write, attribution of a supervising session's spend to threads,
|
|
2
|
+
closing a thread's figures, and the `supervision hook|log|close|show` verbs.
|
|
3
|
+
|
|
4
|
+
The journal is `~/.tempergraph/supervision/<host>/<host_session>.jsonl`: numbers, names from fixed lists, ids and
|
|
5
|
+
times only (SCO-B10, SCO-B11, SCO-B17). It is written by the plugin's Claude Code hooks through `supervision hook <event>`
|
|
6
|
+
and by `supervision log`; read-only verbs never write it (OVR-B15, ADR `a-supervision-journal-written-by-the-host-not-by-read-only-verbs`). A hook never changes, delays
|
|
7
|
+
past 2 s or refuses the host call it observed (OVR-B4), and writes nothing inside the engine's own sessions
|
|
8
|
+
(`TEMPERGRAPH_SESSION_KEY`, SCO-B6). Two figures per thread, never summed: marginal and turn (ADR `attribute-supervision-spend-by-marginal-tokens-beside-turn-totals`). Unmeasured
|
|
9
|
+
is never zero.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shlex
|
|
20
|
+
import time
|
|
21
|
+
import uuid
|
|
22
|
+
from collections import defaultdict
|
|
23
|
+
from collections.abc import Iterable, Mapping
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from datetime import UTC, datetime
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from tempergraph.contracts import Usage
|
|
30
|
+
from tempergraph.run.log import estimate
|
|
31
|
+
from tempergraph.store.layout import home_path, now_iso
|
|
32
|
+
|
|
33
|
+
HOSTS = ("claude-code", "agent-sdk", "messages-api", "antigravity", "unknown")
|
|
34
|
+
ID = re.compile(r"^[A-Za-z0-9_.:@-]{1,128}$")
|
|
35
|
+
TARGET = re.compile(r"^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*/[A-Za-z0-9_][A-Za-z0-9_.:~-]*|workflow:[A-Za-z0-9_.-]{1,64}|orchestration:[A-Za-z0-9_.-]{1,64})$")
|
|
36
|
+
MODEL = re.compile(r"^[A-Za-z0-9_.:@/\[\]-]{1,80}$")
|
|
37
|
+
SHIM = ("tempergraph", "tempergraph.exe", "tempergraph.cmd")
|
|
38
|
+
WAKE_IDLE_S = 300.0
|
|
39
|
+
CLOSE_AFTER_S = 24 * 3600.0
|
|
40
|
+
TOKENS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens")
|
|
41
|
+
CATEGORY = {
|
|
42
|
+
"run": "start", "run --check": "start", "rerun": "start", "batch": "start", "orchestrate start": "start",
|
|
43
|
+
"status": "watch", "events": "watch", "facts": "watch", "wait": "watch", "attention": "watch",
|
|
44
|
+
"orchestrate status": "watch", "orchestrate wait": "watch",
|
|
45
|
+
"logs": "diagnose", "status --detail": "diagnose", "audit": "diagnose", "report": "diagnose",
|
|
46
|
+
"executors": "diagnose", "supervision show": "diagnose",
|
|
47
|
+
"resume": "decide", "orchestrate answer": "decide", "label": "decide",
|
|
48
|
+
"stop": "steer", "rerun --check": "steer", "config": "steer", "orchestrate edit": "steer",
|
|
49
|
+
"resume --settings": "steer",
|
|
50
|
+
}
|
|
51
|
+
VERBS = (*CATEGORY, "stats", "self-check", "list", "validate", "store", "other")
|
|
52
|
+
CATEGORIES = ("start", "watch", "diagnose", "decide", "steer", "relay", "rewake")
|
|
53
|
+
MUTATING = {"run", "rerun", "batch", "resume", "resume --settings", "label", "stop", "orchestrate start",
|
|
54
|
+
"orchestrate answer", "orchestrate edit"}
|
|
55
|
+
SELECTOR_VERBS = {"status", "status --detail", "events", "facts", "wait", "logs", "stop", "label", "audit"}
|
|
56
|
+
FIELDS: dict[str, dict[str, str]] = {
|
|
57
|
+
"session": {"at": "time", "host": "host", "host_session": "id", "host_version": "id?", "model": "model?",
|
|
58
|
+
"caller_app": "id?"},
|
|
59
|
+
"engine_call": {"at": "time", "tool_use_id": "id?", "agent_id": "id?", "verb": "verb", "targets": "targets",
|
|
60
|
+
"mutating": "bool", "background": "bool", "exit_code": "int?", "duration_s": "num?",
|
|
61
|
+
"output_bytes": "int?", "call_id": "id?"},
|
|
62
|
+
"person_turn": {"at": "time", "prompt_id": "id?", "names": "words"},
|
|
63
|
+
"usage": {"at": "time", "message_id": "id?", "agent_id": "id?", "model": "model?", "input_tokens": "int?",
|
|
64
|
+
"output_tokens": "int?", "cache_read_tokens": "int?", "cache_write_tokens": "int?",
|
|
65
|
+
"tool_use_ids": "ids", "skipped_lines": "int?"},
|
|
66
|
+
"reported": {"at": "time", "reported_cost_usd": "num", "source": "source"},
|
|
67
|
+
"end": {"at": "time", "reason": "word?"},
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class EntryRefused(ValueError):
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# -- journal ---------------------------------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def journal_path(home: Path, host: str, session: str) -> Path:
|
|
79
|
+
from tempergraph.provenance import journal_path as jp
|
|
80
|
+
|
|
81
|
+
return jp(home, host, session)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _time(v: Any) -> bool:
|
|
85
|
+
try:
|
|
86
|
+
datetime.fromisoformat(str(v).replace("Z", "+00:00"))
|
|
87
|
+
return True
|
|
88
|
+
except ValueError:
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _check(kind: str, value: Any, rule: str) -> bool:
|
|
93
|
+
optional = rule.endswith("?")
|
|
94
|
+
rule = rule.rstrip("?")
|
|
95
|
+
if value is None:
|
|
96
|
+
return optional or rule in ("ids", "words", "targets")
|
|
97
|
+
if rule == "time":
|
|
98
|
+
return isinstance(value, str) and _time(value)
|
|
99
|
+
if rule == "id":
|
|
100
|
+
return isinstance(value, str) and bool(ID.match(value))
|
|
101
|
+
if rule == "host":
|
|
102
|
+
return value in HOSTS
|
|
103
|
+
if rule == "model":
|
|
104
|
+
return isinstance(value, str) and bool(MODEL.match(value))
|
|
105
|
+
if rule == "verb":
|
|
106
|
+
return value in VERBS
|
|
107
|
+
if rule == "targets":
|
|
108
|
+
return isinstance(value, list) and len(value) <= 64 and all(isinstance(t, str) and TARGET.match(t) for t in value)
|
|
109
|
+
if rule == "ids":
|
|
110
|
+
return isinstance(value, list) and len(value) <= 256 and all(isinstance(t, str) and ID.match(t) for t in value)
|
|
111
|
+
if rule == "words":
|
|
112
|
+
return isinstance(value, list) and len(value) <= 32 and all(
|
|
113
|
+
isinstance(t, str) and re.match(r"^[a-z0-9_:-]{1,40}$", t) for t in value)
|
|
114
|
+
if rule == "bool":
|
|
115
|
+
return isinstance(value, bool)
|
|
116
|
+
if rule == "int":
|
|
117
|
+
return isinstance(value, int) and not isinstance(value, bool) and 0 <= value < 10**12
|
|
118
|
+
if rule == "num":
|
|
119
|
+
return isinstance(value, int | float) and not isinstance(value, bool) and 0 <= value < 10**9
|
|
120
|
+
if rule == "source":
|
|
121
|
+
return value in ("statusline", "sdk_result")
|
|
122
|
+
if rule == "word":
|
|
123
|
+
return isinstance(value, str) and bool(re.match(r"^[a-z0-9_-]{1,40}$", value))
|
|
124
|
+
return False
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def validate(entry: Mapping[str, Any]) -> dict[str, Any]:
|
|
128
|
+
"""Fixed fields, numbers in range, no free text beyond ids (SCO-B16, SCO-B11, SCO-B10); raises EntryRefused."""
|
|
129
|
+
kind = entry.get("entry")
|
|
130
|
+
if kind not in FIELDS:
|
|
131
|
+
raise EntryRefused(f"unknown entry {kind!r}")
|
|
132
|
+
extra = set(entry) - set(FIELDS[str(kind)]) - {"entry"}
|
|
133
|
+
if extra:
|
|
134
|
+
raise EntryRefused(f"{kind}: fields outside the schema: {', '.join(sorted(extra))}")
|
|
135
|
+
for name, rule in FIELDS[str(kind)].items():
|
|
136
|
+
if not _check(str(kind), entry.get(name), rule):
|
|
137
|
+
raise EntryRefused(f"{kind}.{name}: not a {rule.rstrip('?')}")
|
|
138
|
+
return {"entry": kind, **{k: entry.get(k) for k in FIELDS[str(kind)] if k in entry}}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def disabled(env: Mapping[str, str] | None = None) -> bool:
|
|
142
|
+
"""SCO-B6 and `observe.supervision = off` (the user config's defaults, RST)."""
|
|
143
|
+
env = os.environ if env is None else env
|
|
144
|
+
if env.get("TEMPERGRAPH_SESSION_KEY"):
|
|
145
|
+
return True
|
|
146
|
+
try:
|
|
147
|
+
doc = json.loads((home_path() / "config" / "settings.json").read_text(encoding="utf-8"))
|
|
148
|
+
return (doc.get("defaults") or {}).get("observe.supervision") == "off"
|
|
149
|
+
except (OSError, ValueError, AttributeError):
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def append(home: Path, host: str, session: str, entries: Iterable[Mapping[str, Any]]) -> int:
|
|
154
|
+
"""Checks every entry first and appends all or nothing; owner-only, append-only."""
|
|
155
|
+
from tempergraph.docs import append_jsonl
|
|
156
|
+
|
|
157
|
+
if host not in HOSTS or not ID.match(session):
|
|
158
|
+
raise EntryRefused("host or session is not an id")
|
|
159
|
+
checked = [validate(e) for e in entries]
|
|
160
|
+
path = journal_path(home, host, session)
|
|
161
|
+
if checked and not path.exists() and checked[0]["entry"] != "session":
|
|
162
|
+
checked.insert(0, {"entry": "session", "at": checked[0]["at"], "host": host, "host_session": session})
|
|
163
|
+
for e in checked:
|
|
164
|
+
append_jsonl(path, e)
|
|
165
|
+
return len(checked)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def read(path: Path) -> list[dict[str, Any]]:
|
|
169
|
+
out: list[dict[str, Any]] = []
|
|
170
|
+
try:
|
|
171
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
172
|
+
except OSError:
|
|
173
|
+
return out
|
|
174
|
+
for ln in lines:
|
|
175
|
+
with contextlib.suppress(ValueError):
|
|
176
|
+
e = json.loads(ln)
|
|
177
|
+
if isinstance(e, dict):
|
|
178
|
+
out.append(e)
|
|
179
|
+
return out
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def last_record(log: Path, kind: str) -> dict[str, Any] | None:
|
|
183
|
+
from tempergraph.run.events import records
|
|
184
|
+
|
|
185
|
+
return next((r for r in reversed(records(log)) if r.get("kind") == kind), None)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def journals(home: Path) -> list[tuple[str, str, Path]]:
|
|
189
|
+
base = home / "supervision"
|
|
190
|
+
if not base.is_dir():
|
|
191
|
+
return []
|
|
192
|
+
return [(p.parent.name, p.stem, p) for p in sorted(base.glob("*/*.jsonl"))]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
JOURNAL_DAYS = 90 # journals are kept as long as evidence (LOS)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _last_at(path: Path) -> float | None:
|
|
199
|
+
"""The time of the journal's last entry that carries one; None for a journal with none."""
|
|
200
|
+
try:
|
|
201
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
202
|
+
except (OSError, UnicodeDecodeError):
|
|
203
|
+
return None
|
|
204
|
+
for line in reversed(lines):
|
|
205
|
+
try:
|
|
206
|
+
at = json.loads(line).get("at")
|
|
207
|
+
return datetime.fromisoformat(str(at).replace("Z", "+00:00")).timestamp()
|
|
208
|
+
except (ValueError, AttributeError, TypeError):
|
|
209
|
+
continue
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def prunable_journals(home: Path, now: float, days: float = JOURNAL_DAYS) -> list[Path]:
|
|
214
|
+
"""SCO-B17: each journal whose last entry is older than `days`, with its `.offsets.json`; a journal whose time
|
|
215
|
+
cannot be read is kept."""
|
|
216
|
+
out: list[Path] = []
|
|
217
|
+
for _host, _session, path in journals(home):
|
|
218
|
+
last = _last_at(path)
|
|
219
|
+
if last is not None and (now - last) / 86400 >= days:
|
|
220
|
+
out.append(path)
|
|
221
|
+
if (off := path.with_suffix(".offsets.json")).exists():
|
|
222
|
+
out.append(off)
|
|
223
|
+
return out
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# -- the Claude Code hooks (SHL-B14, SHL-B15) --------------------------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _verb(words: list[str]) -> str:
|
|
230
|
+
if not words:
|
|
231
|
+
return "other"
|
|
232
|
+
head = words[0]
|
|
233
|
+
if head == "orchestrate" and len(words) > 1:
|
|
234
|
+
v = f"orchestrate {words[1]}"
|
|
235
|
+
return v if v in VERBS else "other"
|
|
236
|
+
if head == "supervision" and len(words) > 1 and words[1] == "show":
|
|
237
|
+
return "supervision show"
|
|
238
|
+
if head in ("run", "rerun") and "--check" in words:
|
|
239
|
+
return f"{head} --check"
|
|
240
|
+
if head == "status" and "--detail" in words:
|
|
241
|
+
return "status --detail"
|
|
242
|
+
if head == "resume" and not any(w.startswith(("--decision", "--feedback", "--answer")) for w in words) \
|
|
243
|
+
and any(w.startswith(("--set", "--unset", "--profile", "--reload-settings")) for w in words):
|
|
244
|
+
return "resume --settings"
|
|
245
|
+
return head if head in VERBS else "other"
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _positionals(words: list[str]) -> list[str]:
|
|
249
|
+
out, skip = [], False
|
|
250
|
+
for w in words[1:]:
|
|
251
|
+
if skip:
|
|
252
|
+
skip = False
|
|
253
|
+
continue
|
|
254
|
+
if w.startswith("--"):
|
|
255
|
+
skip = "=" not in w and w not in ("--json", "--check", "--detail", "--follow", "--relayed", "--now",
|
|
256
|
+
"--all-roots", "--no-live", "--as-agent", "--background")
|
|
257
|
+
continue
|
|
258
|
+
out.append(w)
|
|
259
|
+
return out
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def targets(words: list[str], cwd: Path | None, printed: str = "") -> list[str]:
|
|
263
|
+
"""The threads a command is about, resolved as the verbs resolve a selector (an alias through the state
|
|
264
|
+
root's aliases); a run's new thread id comes from what the engine printed (read, never stored)."""
|
|
265
|
+
out: list[str] = []
|
|
266
|
+
verb = _verb(words)
|
|
267
|
+
pos = _positionals(words)
|
|
268
|
+
root = _root(cwd)
|
|
269
|
+
|
|
270
|
+
def sel(v: str) -> None:
|
|
271
|
+
if "/" in v and TARGET.match(v):
|
|
272
|
+
out.append(v)
|
|
273
|
+
elif root is not None:
|
|
274
|
+
from tempergraph.durability.alias import resolve
|
|
275
|
+
|
|
276
|
+
tid = resolve(root, v, lambda _t: True)
|
|
277
|
+
out.append(tid if tid and TARGET.match(tid) else f"workflow:{v}" if re.match(r"^[A-Za-z0-9_.-]{1,64}$", v) else "")
|
|
278
|
+
if verb in SELECTOR_VERBS and pos:
|
|
279
|
+
sel(pos[0])
|
|
280
|
+
elif verb.startswith(("resume", "rerun")) and len(pos) >= 2:
|
|
281
|
+
sel(f"{pos[0]}/{pos[1].split('/')[-1]}")
|
|
282
|
+
elif verb.startswith("run") and pos:
|
|
283
|
+
task = next((words[i + 1] for i, w in enumerate(words[:-1]) if w == "--task-id"), None)
|
|
284
|
+
if task:
|
|
285
|
+
sel(f"{pos[0]}/{task}")
|
|
286
|
+
for m in re.finditer(r'"thread_id":\s*"([^"\\]{1,200})"', printed or ""):
|
|
287
|
+
if TARGET.match(m.group(1)):
|
|
288
|
+
out.append(m.group(1))
|
|
289
|
+
return sorted({t for t in out if t})
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _root(cwd: Path | None) -> Path | None:
|
|
293
|
+
if cwd is None:
|
|
294
|
+
return None
|
|
295
|
+
from tempergraph.store.layout import state_root_path
|
|
296
|
+
|
|
297
|
+
try:
|
|
298
|
+
root = state_root_path(cwd)
|
|
299
|
+
except Exception: # noqa: BLE001
|
|
300
|
+
return None
|
|
301
|
+
return root if root.is_dir() else None
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _engine_words(command: str) -> list[str] | None:
|
|
305
|
+
"""The engine's argv when the Bash command starts with the shim name; None for any other command."""
|
|
306
|
+
try:
|
|
307
|
+
words = shlex.split(command, posix=True)
|
|
308
|
+
except ValueError:
|
|
309
|
+
return None
|
|
310
|
+
if not words:
|
|
311
|
+
return None
|
|
312
|
+
first = words[0].rsplit("/", 1)[-1]
|
|
313
|
+
return words[1:] if first in SHIM else None
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _names(prompt: str, root: Path | None) -> list[str]:
|
|
317
|
+
"""PRV-B15: the decision words of open pauses that occur as whole words in the prompt; no text kept."""
|
|
318
|
+
if root is None or not prompt:
|
|
319
|
+
return []
|
|
320
|
+
words: set[str] = set()
|
|
321
|
+
runs = root / "runs"
|
|
322
|
+
for log in sorted(runs.glob("*/*/run.jsonl")) if runs.is_dir() else []:
|
|
323
|
+
with contextlib.suppress(Exception):
|
|
324
|
+
exit_ = json.loads((log.parent / "exit.json").read_text(encoding="utf-8"))
|
|
325
|
+
if exit_.get("exit_code") != 3:
|
|
326
|
+
continue
|
|
327
|
+
p = last_record(log, "pause") or {}
|
|
328
|
+
for d in p.get("decisions") or []:
|
|
329
|
+
words.add(str(d).split(":")[0])
|
|
330
|
+
found = {w for w in words if re.search(rf"(?<![\w-]){re.escape(w)}(?![\w-])", prompt.lower())}
|
|
331
|
+
return sorted(w for w in found if re.match(r"^[a-z0-9_:-]{1,40}$", w))
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _transcript_usage(path: Path, offset: int) -> tuple[list[dict[str, Any]], int, int]:
|
|
335
|
+
"""Usage entries of assistant lines past `offset`: numbers and ids only; returns (entries, offset, skipped)."""
|
|
336
|
+
out: list[dict[str, Any]] = []
|
|
337
|
+
skipped = 0
|
|
338
|
+
try:
|
|
339
|
+
size = path.stat().st_size
|
|
340
|
+
if size < offset:
|
|
341
|
+
offset = 0
|
|
342
|
+
with open(path, "rb") as fh:
|
|
343
|
+
fh.seek(offset)
|
|
344
|
+
data = fh.read(min(size - offset, 64 * 1024 * 1024))
|
|
345
|
+
except OSError:
|
|
346
|
+
return out, offset, 0
|
|
347
|
+
cut = data.rfind(b"\n") + 1
|
|
348
|
+
seen: set[str] = set()
|
|
349
|
+
for raw in data[:cut].splitlines():
|
|
350
|
+
try:
|
|
351
|
+
line = json.loads(raw)
|
|
352
|
+
except ValueError:
|
|
353
|
+
skipped += 1
|
|
354
|
+
continue
|
|
355
|
+
msg = line.get("message") if isinstance(line, dict) else None
|
|
356
|
+
if not isinstance(msg, dict) or line.get("type") != "assistant" or not isinstance(msg.get("usage"), dict):
|
|
357
|
+
continue
|
|
358
|
+
mid = str(msg.get("id") or "")
|
|
359
|
+
u = msg["usage"]
|
|
360
|
+
tools = [str(b.get("id")) for b in msg.get("content") or [] if isinstance(b, dict) and b.get("type") == "tool_use"
|
|
361
|
+
and ID.match(str(b.get("id") or ""))]
|
|
362
|
+
if mid in seen: # one message streamed as several lines: keep its last usage and every tool use
|
|
363
|
+
prev = next(e for e in out if e["message_id"] == mid)
|
|
364
|
+
prev["tool_use_ids"] = sorted(set(prev["tool_use_ids"]) | set(tools))
|
|
365
|
+
for k, src in (("input_tokens", "input_tokens"), ("output_tokens", "output_tokens"),
|
|
366
|
+
("cache_read_tokens", "cache_read_input_tokens"),
|
|
367
|
+
("cache_write_tokens", "cache_creation_input_tokens")):
|
|
368
|
+
if isinstance(u.get(src), int):
|
|
369
|
+
prev[k] = u[src]
|
|
370
|
+
continue
|
|
371
|
+
seen.add(mid)
|
|
372
|
+
model = str(msg.get("model") or "")
|
|
373
|
+
agent = line.get("agentId") if isinstance(line.get("agentId"), str) and ID.match(line["agentId"]) else None
|
|
374
|
+
at = str(line.get("timestamp") or now_iso())
|
|
375
|
+
out.append({"entry": "usage", "at": at if _time(at) else now_iso(),
|
|
376
|
+
"message_id": mid if ID.match(mid) else None, "agent_id": agent,
|
|
377
|
+
"model": model if MODEL.match(model) else None,
|
|
378
|
+
"input_tokens": u.get("input_tokens") if isinstance(u.get("input_tokens"), int) else None,
|
|
379
|
+
"output_tokens": u.get("output_tokens") if isinstance(u.get("output_tokens"), int) else None,
|
|
380
|
+
"cache_read_tokens": u.get("cache_read_input_tokens")
|
|
381
|
+
if isinstance(u.get("cache_read_input_tokens"), int) else None,
|
|
382
|
+
"cache_write_tokens": u.get("cache_creation_input_tokens")
|
|
383
|
+
if isinstance(u.get("cache_creation_input_tokens"), int) else None,
|
|
384
|
+
"tool_use_ids": tools})
|
|
385
|
+
if out and skipped:
|
|
386
|
+
out[0]["skipped_lines"] = skipped
|
|
387
|
+
return out, offset + cut, skipped
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def hook(event: str, payload: Mapping[str, Any], env: Mapping[str, str] | None = None,
|
|
391
|
+
home: Path | None = None) -> int:
|
|
392
|
+
"""One Claude Code hook event; returns the entries written. Never raises (OVR-B4)."""
|
|
393
|
+
try:
|
|
394
|
+
return _hook(event, payload, env, home)
|
|
395
|
+
except Exception: # noqa: BLE001 - the host call is never changed by the journal
|
|
396
|
+
return 0
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _hook(event: str, payload: Mapping[str, Any], env: Mapping[str, str] | None, home: Path | None) -> int:
|
|
400
|
+
if disabled(env):
|
|
401
|
+
return 0
|
|
402
|
+
session = str(payload.get("session_id") or "")
|
|
403
|
+
if not ID.match(session):
|
|
404
|
+
return 0
|
|
405
|
+
from tempergraph.store.layout import ensure_home
|
|
406
|
+
|
|
407
|
+
home = home or ensure_home()
|
|
408
|
+
cwd = Path(str(payload["cwd"])) if payload.get("cwd") else None
|
|
409
|
+
at = now_iso()
|
|
410
|
+
entries: list[dict[str, Any]] = []
|
|
411
|
+
event = event.lower().replace("_", "-")
|
|
412
|
+
if event in ("sessionstart", "session-start"):
|
|
413
|
+
model = payload.get("model")
|
|
414
|
+
model = model.get("id") if isinstance(model, dict) else model
|
|
415
|
+
entries.append({"entry": "session", "at": at, "host": "claude-code", "host_session": session,
|
|
416
|
+
"model": model if isinstance(model, str) and MODEL.match(model) else None})
|
|
417
|
+
elif event in ("userpromptsubmit", "user-prompt-submit"):
|
|
418
|
+
pid = payload.get("prompt_id")
|
|
419
|
+
entries.append({"entry": "person_turn", "at": at, "prompt_id": pid if isinstance(pid, str) and ID.match(pid)
|
|
420
|
+
else None, "names": _names(str(payload.get("prompt") or ""), _root(cwd))})
|
|
421
|
+
elif event in ("posttooluse", "post-tool-use"):
|
|
422
|
+
if payload.get("tool_name") != "Bash":
|
|
423
|
+
return 0
|
|
424
|
+
tin = payload.get("tool_input") or {}
|
|
425
|
+
words = _engine_words(str(tin.get("command") or ""))
|
|
426
|
+
if words is None:
|
|
427
|
+
return 0
|
|
428
|
+
res = payload.get("tool_response") or {}
|
|
429
|
+
res = res if isinstance(res, dict) else {"stdout": str(res)}
|
|
430
|
+
printed = str(res.get("stdout") or "")
|
|
431
|
+
verb = _verb(words)
|
|
432
|
+
code = res.get("exit_code", res.get("exitCode"))
|
|
433
|
+
call = re.search(r'"call_id":\s*"([0-9a-f]{32})"', printed)
|
|
434
|
+
tuid, agent = payload.get("tool_use_id"), payload.get("agent_id")
|
|
435
|
+
entries.append({"entry": "engine_call", "at": at,
|
|
436
|
+
"tool_use_id": tuid if isinstance(tuid, str) and ID.match(tuid) else None,
|
|
437
|
+
"agent_id": agent if isinstance(agent, str) and ID.match(agent) else None,
|
|
438
|
+
"verb": verb, "targets": targets(words, cwd, printed), "mutating": verb in MUTATING,
|
|
439
|
+
"background": bool(tin.get("run_in_background")),
|
|
440
|
+
"exit_code": code if isinstance(code, int) and 0 <= code < 256 else None,
|
|
441
|
+
"duration_s": None,
|
|
442
|
+
"output_bytes": len(printed.encode()) + len(str(res.get("stderr") or "").encode()),
|
|
443
|
+
"call_id": call.group(1) if call else None})
|
|
444
|
+
elif event in ("stop", "subagentstop", "subagent-stop"):
|
|
445
|
+
tp = payload.get("agent_transcript_path") or payload.get("transcript_path")
|
|
446
|
+
if not tp:
|
|
447
|
+
return 0
|
|
448
|
+
tpath = Path(str(tp))
|
|
449
|
+
state = journal_path(home, "claude-code", session).with_suffix(".offsets.json")
|
|
450
|
+
offsets: dict[str, int] = {}
|
|
451
|
+
with contextlib.suppress(OSError, ValueError):
|
|
452
|
+
offsets = dict(json.loads(state.read_text(encoding="utf-8")))
|
|
453
|
+
found, offsets[str(tpath)], _ = _transcript_usage(tpath, int(offsets.get(str(tpath)) or 0))
|
|
454
|
+
entries += found
|
|
455
|
+
from tempergraph.docs import write_json
|
|
456
|
+
|
|
457
|
+
write_json(state, offsets)
|
|
458
|
+
elif event in ("sessionend", "session-end"):
|
|
459
|
+
reason = str(payload.get("reason") or "other").lower().replace(" ", "_")
|
|
460
|
+
entries.append({"entry": "end", "at": at, "reason": reason if re.match(r"^[a-z0-9_-]{1,40}$", reason) else "other"})
|
|
461
|
+
else:
|
|
462
|
+
return 0
|
|
463
|
+
n = append(home, "claude-code", session, entries)
|
|
464
|
+
if event in ("sessionend", "session-end"):
|
|
465
|
+
with contextlib.suppress(Exception):
|
|
466
|
+
close(home, session=session)
|
|
467
|
+
return n
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
# -- attribution (SCO-B13, SCO-B14) ------------------------------------------------------------------------------------
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _ts(v: Any) -> float:
|
|
474
|
+
try:
|
|
475
|
+
return datetime.fromisoformat(str(v).replace("Z", "+00:00")).timestamp()
|
|
476
|
+
except ValueError:
|
|
477
|
+
return 0.0
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
@dataclass
|
|
481
|
+
class Figure:
|
|
482
|
+
tokens: dict[str, int] = field(default_factory=lambda: dict.fromkeys(TOKENS, 0))
|
|
483
|
+
usd: float = 0.0
|
|
484
|
+
priced: bool = True
|
|
485
|
+
|
|
486
|
+
def add(self, u: Mapping[str, Any], model: str | None, part: Mapping[str, int] | None = None) -> None:
|
|
487
|
+
got = {k: int((part if part is not None else u).get(k) or 0) for k in TOKENS}
|
|
488
|
+
for k, v in got.items():
|
|
489
|
+
self.tokens[k] += v
|
|
490
|
+
if not any(got.values()):
|
|
491
|
+
return
|
|
492
|
+
cost = estimate(Usage(input_tokens=got["input_tokens"], output_tokens=got["output_tokens"],
|
|
493
|
+
cache_read_tokens=got["cache_read_tokens"], cache_write_tokens=got["cache_write_tokens"]),
|
|
494
|
+
model)
|
|
495
|
+
if cost is None:
|
|
496
|
+
self.priced = False
|
|
497
|
+
else:
|
|
498
|
+
self.usd += cost
|
|
499
|
+
|
|
500
|
+
def to_json(self) -> dict[str, Any]:
|
|
501
|
+
return {"tokens": dict(self.tokens), "estimated_usd": round(self.usd, 6) if self.priced else None}
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
@dataclass
|
|
505
|
+
class ThreadCost:
|
|
506
|
+
marginal: dict[str, Figure] = field(default_factory=lambda: defaultdict(Figure))
|
|
507
|
+
turn: dict[str, Figure] = field(default_factory=lambda: defaultdict(Figure))
|
|
508
|
+
calls: dict[str, int] = field(default_factory=lambda: defaultdict(int))
|
|
509
|
+
sessions: set[tuple[str, str]] = field(default_factory=set)
|
|
510
|
+
counted: set[tuple[tuple[str, str], str]] = field(default_factory=set) # (session, message) once per thread
|
|
511
|
+
estimated: bool = False
|
|
512
|
+
unmeasured: bool = False
|
|
513
|
+
last_call_at: float = 0.0
|
|
514
|
+
|
|
515
|
+
def total(self, which: dict[str, Figure]) -> dict[str, Any]:
|
|
516
|
+
f = Figure()
|
|
517
|
+
for x in which.values():
|
|
518
|
+
for k, v in x.tokens.items():
|
|
519
|
+
f.tokens[k] += v
|
|
520
|
+
f.usd += x.usd
|
|
521
|
+
f.priced = f.priced and x.priced
|
|
522
|
+
return f.to_json()
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def attribute(sessions: Mapping[tuple[str, str], list[dict[str, Any]]], wake_idle_s: float = WAKE_IDLE_S
|
|
526
|
+
) -> tuple[dict[str, ThreadCost], dict[tuple[str, str], dict[str, Any]]]:
|
|
527
|
+
"""The one attribution function (SCO-AC1): per thread its categories and figures, per session its `other`."""
|
|
528
|
+
threads: dict[str, ThreadCost] = defaultdict(ThreadCost)
|
|
529
|
+
per_session: dict[tuple[str, str], dict[str, Any]] = {}
|
|
530
|
+
for key, entries in sessions.items():
|
|
531
|
+
msgs = sorted((e for e in entries if e.get("entry") == "usage"), key=lambda e: _ts(e.get("at")))
|
|
532
|
+
calls = sorted((e for e in entries if e.get("entry") == "engine_call"), key=lambda e: _ts(e.get("at")))
|
|
533
|
+
turns = [e for e in entries if e.get("entry") == "person_turn"]
|
|
534
|
+
model = next((e.get("model") for e in entries if e.get("entry") == "session" and e.get("model")), None)
|
|
535
|
+
used: set[str] = set()
|
|
536
|
+
reported = [e for e in entries if e.get("entry") == "reported"]
|
|
537
|
+
skipped = any(e.get("skipped_lines") for e in msgs)
|
|
538
|
+
|
|
539
|
+
def mkey(m: dict[str, Any]) -> str:
|
|
540
|
+
return str(m.get("message_id") or f"@{m.get('at')}")
|
|
541
|
+
|
|
542
|
+
for c in calls:
|
|
543
|
+
cat = CATEGORY.get(str(c.get("verb")))
|
|
544
|
+
tids = [t for t in c.get("targets") or [] if "/" in t and not t.startswith(("workflow:", "orchestration:"))]
|
|
545
|
+
if cat is None or not tids:
|
|
546
|
+
continue
|
|
547
|
+
at = _ts(c.get("at"))
|
|
548
|
+
issuer = next((m for m in msgs if c.get("tool_use_id") and c["tool_use_id"] in (m.get("tool_use_ids") or [])),
|
|
549
|
+
None)
|
|
550
|
+
nxt = next((m for m in msgs if _ts(m.get("at")) >= at and m.get("agent_id") == c.get("agent_id")
|
|
551
|
+
and m is not issuer), None)
|
|
552
|
+
share = 1.0 / len(tids)
|
|
553
|
+
for tid in tids:
|
|
554
|
+
tc = threads[tid]
|
|
555
|
+
tc.sessions.add(key)
|
|
556
|
+
tc.calls[cat] += 1
|
|
557
|
+
tc.last_call_at = max(tc.last_call_at, at)
|
|
558
|
+
if skipped:
|
|
559
|
+
tc.estimated = True
|
|
560
|
+
if not msgs:
|
|
561
|
+
tc.unmeasured = True
|
|
562
|
+
continue
|
|
563
|
+
out_part = 0
|
|
564
|
+
if issuer is not None:
|
|
565
|
+
n_calls = max(1, len(issuer.get("tool_use_ids") or []))
|
|
566
|
+
out_part = int(math.floor((issuer.get("output_tokens") or 0) / n_calls * share))
|
|
567
|
+
in_part = 0
|
|
568
|
+
if nxt is not None:
|
|
569
|
+
in_part = min(int(math.ceil((c.get("output_bytes") or 0) / 4 * share)), int(nxt.get("input_tokens") or 0))
|
|
570
|
+
if not c.get("output_bytes"):
|
|
571
|
+
tc.estimated = True
|
|
572
|
+
tc.marginal[cat].add({}, model, {"output_tokens": out_part, "input_tokens": in_part})
|
|
573
|
+
for m in (issuer, nxt):
|
|
574
|
+
if m is not None and (key, mkey(m)) not in tc.counted:
|
|
575
|
+
tc.counted.add((key, mkey(m)))
|
|
576
|
+
tc.turn[cat].add(m, m.get("model") or model)
|
|
577
|
+
used.add(mkey(m))
|
|
578
|
+
if c.get("agent_id"): # SCO-B8: the helper's whole usage is on the thread's turn figure
|
|
579
|
+
for m in msgs:
|
|
580
|
+
if m.get("agent_id") == c["agent_id"] and (key, mkey(m)) not in tc.counted:
|
|
581
|
+
tc.counted.add((key, mkey(m)))
|
|
582
|
+
tc.turn[cat].add(m, m.get("model") or model)
|
|
583
|
+
used.add(mkey(m))
|
|
584
|
+
# rewake: the first message after an idle gap that follows a background call's end (SCO-B13, SCO-B14)
|
|
585
|
+
bg = [c for c in calls if c.get("background")]
|
|
586
|
+
for prev, m in zip(msgs, msgs[1:], strict=False):
|
|
587
|
+
gap = _ts(m.get("at")) - _ts(prev.get("at"))
|
|
588
|
+
if gap < wake_idle_s:
|
|
589
|
+
continue
|
|
590
|
+
woke = [c for c in bg if _ts(prev.get("at")) <= _ts(c.get("at")) <= _ts(m.get("at"))] or \
|
|
591
|
+
[c for c in bg if _ts(c.get("at")) <= _ts(m.get("at"))][-1:]
|
|
592
|
+
for c in woke:
|
|
593
|
+
for tid in [t for t in c.get("targets") or [] if "/" in t]:
|
|
594
|
+
tc = threads[tid]
|
|
595
|
+
tc.marginal["rewake"].add({}, m.get("model") or model, {"cache_write_tokens": int(m.get("cache_write_tokens") or 0)})
|
|
596
|
+
used.add(mkey(m))
|
|
597
|
+
# relay: messages between a read of the thread and the decide call that answered, with a person turn between
|
|
598
|
+
for c in calls:
|
|
599
|
+
if CATEGORY.get(str(c.get("verb"))) != "decide":
|
|
600
|
+
continue
|
|
601
|
+
for tid in [t for t in c.get("targets") or [] if "/" in t]:
|
|
602
|
+
before = [x for x in calls if x is not c and tid in (x.get("targets") or []) and _ts(x.get("at")) < _ts(c.get("at"))
|
|
603
|
+
and CATEGORY.get(str(x.get("verb"))) != "decide"]
|
|
604
|
+
if not before:
|
|
605
|
+
continue
|
|
606
|
+
start, end = _ts(before[-1].get("at")), _ts(c.get("at"))
|
|
607
|
+
if not any(start < _ts(t.get("at")) < end for t in turns):
|
|
608
|
+
continue
|
|
609
|
+
tc = threads[tid]
|
|
610
|
+
for m in msgs:
|
|
611
|
+
if start < _ts(m.get("at")) < end and (key, mkey(m)) not in tc.counted:
|
|
612
|
+
tc.counted.add((key, mkey(m)))
|
|
613
|
+
tc.turn["relay"].add(m, m.get("model") or model)
|
|
614
|
+
tc.calls["relay"] += 1
|
|
615
|
+
used.add(mkey(m))
|
|
616
|
+
other = Figure()
|
|
617
|
+
for m in msgs:
|
|
618
|
+
if mkey(m) not in used:
|
|
619
|
+
other.add(m, m.get("model") or model)
|
|
620
|
+
per_session[key] = {"host": key[0], "messages": len(msgs), "calls": len(calls), "person_turns": len(turns),
|
|
621
|
+
"other": other.to_json(),
|
|
622
|
+
"reported_cost_usd": reported[-1].get("reported_cost_usd") if reported else None,
|
|
623
|
+
"ended": any(e.get("entry") == "end" for e in entries),
|
|
624
|
+
"last_at": max((_ts(e.get("at")) for e in entries), default=0.0)}
|
|
625
|
+
return threads, per_session
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _hash(text: str) -> str:
|
|
629
|
+
import hashlib
|
|
630
|
+
|
|
631
|
+
return hashlib.sha256(text.encode()).hexdigest()[:16]
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def figures(tc: ThreadCost | None, sessions: Mapping[tuple[str, str], dict[str, Any]]) -> dict[str, Any]:
|
|
635
|
+
"""SCO-B15's cost fields of one thread."""
|
|
636
|
+
if tc is None or not tc.sessions:
|
|
637
|
+
return {"marginal": None, "turn": None, "sessions": [], "completeness": "none_known", "calls": {},
|
|
638
|
+
"observations": None}
|
|
639
|
+
complete = "incomplete" if tc.unmeasured else "estimated" if tc.estimated else "complete"
|
|
640
|
+
return {
|
|
641
|
+
"marginal": {"by_category": {k: v.to_json() for k, v in sorted(tc.marginal.items())},
|
|
642
|
+
"total": tc.total(tc.marginal)} if not tc.unmeasured else None,
|
|
643
|
+
"turn": {"by_category": {k: v.to_json() for k, v in sorted(tc.turn.items())},
|
|
644
|
+
"total": tc.total(tc.turn)} if not tc.unmeasured else None,
|
|
645
|
+
"sessions": [{"host": h, "session_hash": _hash(f"{h}:{s}"),
|
|
646
|
+
"reported_cost_usd": (sessions.get((h, s)) or {}).get("reported_cost_usd")}
|
|
647
|
+
for h, s in sorted(tc.sessions)],
|
|
648
|
+
"completeness": complete, "calls": dict(sorted(tc.calls.items())),
|
|
649
|
+
"observations": tc.calls.get("watch", 0) + tc.calls.get("diagnose", 0),
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def load(home: Path, session: str | None = None) -> dict[tuple[str, str], list[dict[str, Any]]]:
|
|
654
|
+
return {(h, s): read(p) for h, s, p in journals(home) if session is None or s == session}
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
# -- closing (SCO-B15) ----------------------------------------------------------------------------------------
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def _find_thread(home: Path, tid: str) -> Path | None:
|
|
661
|
+
from tempergraph.observe.rows import read_index
|
|
662
|
+
|
|
663
|
+
wf, _, task = tid.partition("/")
|
|
664
|
+
for entry in read_index(home):
|
|
665
|
+
root = Path(str(entry.get("path")))
|
|
666
|
+
if (root / "runs" / wf / task / "run.jsonl").exists():
|
|
667
|
+
return root
|
|
668
|
+
return None
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _closed(root: Path) -> dict[str, dict[str, Any]]:
|
|
672
|
+
out: dict[str, dict[str, Any]] = {}
|
|
673
|
+
try:
|
|
674
|
+
lines = (root / "ledger.jsonl").read_text(encoding="utf-8").splitlines()
|
|
675
|
+
except OSError:
|
|
676
|
+
return out
|
|
677
|
+
for ln in lines:
|
|
678
|
+
with contextlib.suppress(ValueError):
|
|
679
|
+
r = json.loads(ln)
|
|
680
|
+
if isinstance(r, dict) and r.get("kind") == "supervision" and r.get("thread_id"):
|
|
681
|
+
out[str(r["thread_id"])] = r
|
|
682
|
+
return out
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def close(home: Path | None = None, *, session: str | None = None, now: float | None = None) -> dict[str, Any]:
|
|
686
|
+
"""Closes every thread whose supervising sessions have ended or been quiet 24 h after its last exit."""
|
|
687
|
+
from tempergraph.docs import append_jsonl
|
|
688
|
+
from tempergraph.durability.lock import is_held
|
|
689
|
+
from tempergraph.store.layout import lock_path, run_dir
|
|
690
|
+
|
|
691
|
+
home = home or home_path()
|
|
692
|
+
now = time.time() if now is None else now
|
|
693
|
+
sessions = load(home)
|
|
694
|
+
threads, per = attribute(sessions)
|
|
695
|
+
closed: list[str] = []
|
|
696
|
+
for tid, tc in sorted(threads.items()):
|
|
697
|
+
if session is not None and not any(s == session for _, s in tc.sessions):
|
|
698
|
+
continue
|
|
699
|
+
root = _find_thread(home, tid)
|
|
700
|
+
if root is None: # SCO-B16, SCO-B11, SCO-B10: kept, attributed if the thread appears later
|
|
701
|
+
continue
|
|
702
|
+
wf, _, task = tid.partition("/")
|
|
703
|
+
if is_held(lock_path(root, wf, task)):
|
|
704
|
+
continue
|
|
705
|
+
exit_ = last_record(run_dir(root, wf, task) / "run.jsonl", "run_exit")
|
|
706
|
+
if exit_ is None:
|
|
707
|
+
continue
|
|
708
|
+
quiet = all((per.get(k) or {}).get("ended") or now - tc.last_call_at >= CLOSE_AFTER_S for k in tc.sessions)
|
|
709
|
+
if not quiet:
|
|
710
|
+
continue
|
|
711
|
+
prev = _closed(root).get(tid)
|
|
712
|
+
if prev and _ts(prev.get("last_call_at")) >= tc.last_call_at:
|
|
713
|
+
continue
|
|
714
|
+
line = {"kind": "supervision", "schema_version": 1, "id": uuid.uuid4().hex, "thread_id": tid,
|
|
715
|
+
"workflow": wf, "closed_at": now_iso(),
|
|
716
|
+
"last_call_at": datetime.fromtimestamp(tc.last_call_at, UTC).isoformat(),
|
|
717
|
+
**({"replaces": prev.get("id")} if prev else {}), **figures(tc, per)}
|
|
718
|
+
append_jsonl(root / "ledger.jsonl", line)
|
|
719
|
+
_enqueue(home, root, line)
|
|
720
|
+
closed.append(tid)
|
|
721
|
+
return {"schema_version": 1, "closed": closed}
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def _enqueue(home: Path, root: Path, line: dict[str, Any]) -> None:
|
|
725
|
+
"""The `supervision` row for each sink that takes it (CST-B9): kept locally, referenced from the outbox."""
|
|
726
|
+
from tempergraph.docs import append_jsonl
|
|
727
|
+
from tempergraph.observe import sinks
|
|
728
|
+
|
|
729
|
+
month = str(line["closed_at"])[:7]
|
|
730
|
+
row = {k: line.get(k) for k in ("id", "thread_id", "workflow", "closed_at", "marginal", "turn", "completeness")}
|
|
731
|
+
row["sessions"] = [{k: s.get(k) for k in ("host", "session_hash", "reported_cost_usd")} for s in line.get("sessions") or []]
|
|
732
|
+
row["row_id"] = line["id"]
|
|
733
|
+
row["kind"] = "supervision"
|
|
734
|
+
row["schema_version"] = 1
|
|
735
|
+
row["state_root"] = str(root)
|
|
736
|
+
row["machine_id"] = sinks._machine(home).get("machine_id")
|
|
737
|
+
append_jsonl(home / "supervision" / "rows" / f"{month}.jsonl", row)
|
|
738
|
+
with contextlib.suppress(sinks.SinkConfigError):
|
|
739
|
+
for s in sinks.load(home, root):
|
|
740
|
+
if s.takes("supervision"):
|
|
741
|
+
append_jsonl(sinks.outbox(home, s.name), {"row_id": row["row_id"], "kind": "supervision",
|
|
742
|
+
"month": month, "state_root": str(root)})
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def closed_for(root: Path) -> dict[str, dict[str, Any]]:
|
|
746
|
+
"""The latest closed figures per thread, for `report --supervision` and the detail document."""
|
|
747
|
+
return _closed(root)
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
# -- show (SCO-B16) -------------------------------------------------------------------------------------------
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def show(home: Path, *, thread: str | None = None, session: str | None = None) -> dict[str, Any]:
|
|
754
|
+
sessions = load(home, session)
|
|
755
|
+
threads, per = attribute(sessions)
|
|
756
|
+
if thread is not None:
|
|
757
|
+
tc = threads.get(thread)
|
|
758
|
+
return {"schema_version": 1, "thread_id": thread, "open": bool(tc and not all(
|
|
759
|
+
(per.get(k) or {}).get("ended") for k in tc.sessions)), **figures(tc, per)}
|
|
760
|
+
listed = [{"host": k[0], "session": k[1], **v} for k, v in sorted(per.items())]
|
|
761
|
+
by_thread = {tid: figures(tc, per) for tid, tc in sorted(threads.items())}
|
|
762
|
+
out: dict[str, Any] = {"schema_version": 1, "session": session, "sessions": listed, "threads": by_thread}
|
|
763
|
+
pairs: dict[str, set[str]] = defaultdict(set)
|
|
764
|
+
for h, s in sessions:
|
|
765
|
+
pairs[s].add(h)
|
|
766
|
+
out["shared_session_ids"] = sorted(s for s, hs in pairs.items() if len(hs) > 1) # SCO-B16, SCO-B11, SCO-B10
|
|
767
|
+
return out
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def _fig(f: Mapping[str, Any] | None) -> str:
|
|
771
|
+
if not f:
|
|
772
|
+
return "not measured"
|
|
773
|
+
t = f["total"]
|
|
774
|
+
usd = "unpriced" if t.get("estimated_usd") is None else f"${t['estimated_usd']:.2f} est"
|
|
775
|
+
return f"{sum(t['tokens'].values()):,} tokens · {usd}"
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def text(doc: Mapping[str, Any]) -> str:
|
|
779
|
+
def block(name: str, f: Mapping[str, Any]) -> list[str]:
|
|
780
|
+
out = [f"{name}: {f['completeness']} · marginal {_fig(f.get('marginal'))} · turn {_fig(f.get('turn'))}"]
|
|
781
|
+
cats = sorted(set((f.get("marginal") or {}).get("by_category") or {}) | set(f.get("calls") or {}))
|
|
782
|
+
for c in cats:
|
|
783
|
+
m = ((f.get("marginal") or {}).get("by_category") or {}).get(c)
|
|
784
|
+
out.append(f" {c}: {(f.get('calls') or {}).get(c, 0)} calls"
|
|
785
|
+
+ (f" · marginal {sum(m['tokens'].values()):,} tokens" if m else ""))
|
|
786
|
+
return out
|
|
787
|
+
|
|
788
|
+
if "thread_id" in doc:
|
|
789
|
+
lines = block(str(doc["thread_id"]) + (" (open)" if doc.get("open") else ""), doc)
|
|
790
|
+
else:
|
|
791
|
+
lines = [f"session {s['host']}/{s['session']}: {s['messages']} messages, {s['calls']} engine calls, "
|
|
792
|
+
f"{s['person_turns']} person turns · other "
|
|
793
|
+
f"{sum(s['other']['tokens'].values()):,} tokens" for s in doc.get("sessions") or []]
|
|
794
|
+
for tid, f in (doc.get("threads") or {}).items():
|
|
795
|
+
lines += block(tid, f)
|
|
796
|
+
lines = lines or ["no supervision journal entries"]
|
|
797
|
+
return "\n".join(lines) + "\n"
|