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,125 @@
|
|
|
1
|
+
"""The supervision record of a run, built at every `run_exit` for the thread so far (SUP-B10, SUP-B11).
|
|
2
|
+
|
|
3
|
+
Read from the thread's intervention rows in the ledger and its `run_started` records. Cost fields and
|
|
4
|
+
`observations` come from the supervision journal (SCO-B15, T7.6) and stay null until then: unmeasured is
|
|
5
|
+
never zero.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import statistics
|
|
12
|
+
from collections.abc import Mapping, Sequence
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
DECIDERS = ("person", "agent", "unknown", "pipeline", "orchestrator", "scheduler", "engine")
|
|
17
|
+
CLASSES = ("designed", "rescue", "steer", "engine")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _rows(path: Path, kind: str, **match: Any) -> list[dict[str, Any]]:
|
|
21
|
+
out: list[dict[str, Any]] = []
|
|
22
|
+
try:
|
|
23
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
24
|
+
except OSError:
|
|
25
|
+
return out
|
|
26
|
+
for ln in lines:
|
|
27
|
+
try:
|
|
28
|
+
r = json.loads(ln)
|
|
29
|
+
except ValueError:
|
|
30
|
+
continue
|
|
31
|
+
if isinstance(r, dict) and r.get("kind") == kind and all(r.get(k) == v for k, v in match.items()):
|
|
32
|
+
out.append(r)
|
|
33
|
+
return out
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def build(ledger: Path, run_log: Path, thread: str, units_reached: Sequence[str]) -> dict[str, Any]:
|
|
37
|
+
rows = _rows(ledger, "intervention", thread_id=thread)
|
|
38
|
+
starts = _rows(run_log, "run_started")
|
|
39
|
+
touches = {c: {d: 0 for d in DECIDERS} for c in CLASSES}
|
|
40
|
+
rescue_by_pause: dict[str, int] = {}
|
|
41
|
+
relayed = {"turn_named": 0, "turn_only": 0, "claimed": 0}
|
|
42
|
+
waits: dict[str, float] = {}
|
|
43
|
+
per_pause: list[float] = []
|
|
44
|
+
undesigned_units: set[str] = set()
|
|
45
|
+
undesigned_by: set[str] = set()
|
|
46
|
+
designed_by: set[str] = set()
|
|
47
|
+
unknown = sum(1 for s in starts if (s.get("caller") or {}).get("kind") == "unknown")
|
|
48
|
+
sessions: set[tuple[str, str]] = set()
|
|
49
|
+
for s in starts:
|
|
50
|
+
c = s.get("caller") or {}
|
|
51
|
+
if c.get("host_session"):
|
|
52
|
+
sessions.add((str(c.get("host")), str(c["host_session"])))
|
|
53
|
+
for r in rows:
|
|
54
|
+
c = r.get("caller") or {}
|
|
55
|
+
by = str(c.get("decided_by") or c.get("kind") or "unknown")
|
|
56
|
+
by = by if by in DECIDERS else "unknown"
|
|
57
|
+
if c.get("kind") == "unknown":
|
|
58
|
+
unknown += 1
|
|
59
|
+
if c.get("relay") in relayed:
|
|
60
|
+
relayed[str(c["relay"])] += 1
|
|
61
|
+
if c.get("host_session"):
|
|
62
|
+
sessions.add((str(c.get("host")), str(c["host_session"])))
|
|
63
|
+
if r.get("wait_s") is not None:
|
|
64
|
+
waits[by] = round(waits.get(by, 0.0) + float(r["wait_s"]), 1)
|
|
65
|
+
per_pause.append(float(r["wait_s"]))
|
|
66
|
+
for t in r.get("touches") or []:
|
|
67
|
+
cls = str(t.get("class"))
|
|
68
|
+
if cls not in touches:
|
|
69
|
+
continue
|
|
70
|
+
touches[cls][by] += 1
|
|
71
|
+
if cls == "rescue":
|
|
72
|
+
kind = str(r.get("pause_kind") or "escalation")
|
|
73
|
+
rescue_by_pause[kind] = rescue_by_pause.get(kind, 0) + 1
|
|
74
|
+
if cls in ("rescue", "steer"):
|
|
75
|
+
undesigned_units.add(str(r.get("unit") or ""))
|
|
76
|
+
undesigned_by.add(by)
|
|
77
|
+
if cls == "designed":
|
|
78
|
+
designed_by.add(by)
|
|
79
|
+
total = {c: sum(v.values()) for c, v in touches.items()}
|
|
80
|
+
undesigned = total["rescue"] + total["steer"]
|
|
81
|
+
reached = [u for u in dict.fromkeys(units_reached) if u]
|
|
82
|
+
if reached and undesigned and len(undesigned_units & set(reached)) * 2 >= len(reached):
|
|
83
|
+
level = "operator"
|
|
84
|
+
elif total["steer"]:
|
|
85
|
+
level = "collaborator"
|
|
86
|
+
elif total["rescue"]:
|
|
87
|
+
level = "consultant"
|
|
88
|
+
elif total["designed"]:
|
|
89
|
+
level = "approver"
|
|
90
|
+
else:
|
|
91
|
+
level = "observer"
|
|
92
|
+
if level in ("observer", "approver"):
|
|
93
|
+
level_by = "none"
|
|
94
|
+
else:
|
|
95
|
+
level_by = next(iter(undesigned_by)) if len(undesigned_by) == 1 else "mixed"
|
|
96
|
+
rec: dict[str, Any] = {
|
|
97
|
+
"touches": {**touches, "rescue_by_pause": rescue_by_pause}, "undesigned": undesigned, "relayed": relayed,
|
|
98
|
+
"agent_own_rescues": touches["rescue"]["agent"], "wait_s": waits, "person_wait_s": waits.get("person", 0.0),
|
|
99
|
+
"latency_s": {"median": statistics.median(per_pause), "max": max(per_pause)} if per_pause else None,
|
|
100
|
+
"observations": None, "supervisors": {"sessions": len(sessions), "hosts": sorted({h for h, _ in sessions})},
|
|
101
|
+
"callers_unknown": unknown, "supervision_cost": None, "supervision_share": None,
|
|
102
|
+
"level": level, "level_by": level_by}
|
|
103
|
+
if level == "approver" and designed_by == {"agent"}:
|
|
104
|
+
rec["designed_by"] = "agent"
|
|
105
|
+
if starts and (starts[0].get("caller") or {}).get("kind") == "scheduler":
|
|
106
|
+
rec["start_cost"] = "measured_zero" # TCK-B24: a fire's start asks no one for anything; its supervision cost is zero
|
|
107
|
+
return rec
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def schedule_setup(log: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
|
|
111
|
+
"""TCK-B24 (SUP): the person's `add` and `edit` of one schedule are one `designed` setup touch, counted once and by
|
|
112
|
+
the decider of the `add`; a fire counts no touch (`started` events add nothing) and its start costs `measured_zero`."""
|
|
113
|
+
made = next((e for e in log if e.get("kind") == "created"), None)
|
|
114
|
+
c = (made or {}).get("caller") or {}
|
|
115
|
+
by = str(c.get("decided_by") or c.get("kind") or "unknown")
|
|
116
|
+
by = by if by in DECIDERS else "unknown"
|
|
117
|
+
designed = {d: 0 for d in DECIDERS}
|
|
118
|
+
if made is not None:
|
|
119
|
+
designed[by] = 1
|
|
120
|
+
return {"touches": {"designed": designed, "rescue": {d: 0 for d in DECIDERS}, "steer": {d: 0 for d in DECIDERS}},
|
|
121
|
+
"fire_touches": 0, "fires": sum(1 for e in log if e.get("kind") == "started"), "start_cost": "measured_zero"}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def path_units(values: Mapping[str, Any]) -> list[str]:
|
|
125
|
+
return list(((values.get("run") or {}).get("path") or {}).get("units") or [])
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Which tools an attempt could not reach, their refusal class and the grant that fixes each (RST-B28, RST-B29, RST-B30, TSA-B7).
|
|
2
|
+
|
|
3
|
+
A name the step did not declare is `undeclared_tool` and a declared name the session never started is
|
|
4
|
+
`missing_at_start`. Any other refused name is classed from the session's own call record (the first call of
|
|
5
|
+
that name that did not succeed): `outside_workspace` or `inside_workspace` for a path target, `command` for a
|
|
6
|
+
shell call with the longest declared prefix or `undeclared`, `unclassified` where the record cannot tell. An entry
|
|
7
|
+
holds `path_class` or `prefix`, never the path or the command line.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Sequence
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from tempergraph.contracts import Capabilities, StepSpec
|
|
17
|
+
from tempergraph.executors.capabilities import tool_names
|
|
18
|
+
from tempergraph.executors.summary import OUTSIDE
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def capability_of(caps: Capabilities, name: str) -> str | None:
|
|
22
|
+
"""The engine capability an executor tool name stands for, `mcp:<server>/<tool>` included."""
|
|
23
|
+
for cap, names in caps.tool_map.items():
|
|
24
|
+
if "*" not in cap and name in names:
|
|
25
|
+
return cap
|
|
26
|
+
for tmpl in caps.tool_map.get("mcp:*", ()):
|
|
27
|
+
pattern = re.escape(tmpl).replace(r"\{server\}", r"(?P<server>[^_/()]+)").replace(r"\{tool\}", r"(?P<tool>.+)")
|
|
28
|
+
m = re.fullmatch(pattern, name)
|
|
29
|
+
if m:
|
|
30
|
+
return f"mcp:{m.group('server')}/{m.group('tool')}"
|
|
31
|
+
if name in caps.tool_map.get("skill:*", ()):
|
|
32
|
+
return "skill:*"
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_PATH_CAPABILITIES = ("read", "edit", "write", "list") # a call of any other capability names no path
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _prefix_of(line: str, prefixes: Sequence[str]) -> str:
|
|
40
|
+
"""The longest declared prefix the command line starts with at whole words, else `undeclared`."""
|
|
41
|
+
words = line.split()
|
|
42
|
+
best = ""
|
|
43
|
+
for p in prefixes:
|
|
44
|
+
pw = p.split()
|
|
45
|
+
if pw and words[:len(pw)] == pw and len(p) > len(best):
|
|
46
|
+
best = p
|
|
47
|
+
return best or "undeclared"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _classed(name: str, cap: str | None, calls: Sequence[dict[str, Any]] | None,
|
|
51
|
+
prefixes: Sequence[str]) -> dict[str, Any]:
|
|
52
|
+
"""The class facts of a refused name from the first call of that name that did not succeed (HUM-B24, HUM-B25).
|
|
53
|
+
|
|
54
|
+
The entry holds a class, `path_class` or `prefix`, and never the path or the command line itself.
|
|
55
|
+
"""
|
|
56
|
+
call = next((c for c in calls or () if c.get("name") == name and c.get("ok") is not True), None)
|
|
57
|
+
unclassified: dict[str, Any] = {"class": "unclassified",
|
|
58
|
+
"fix": "retry with --feedback naming the permitted way, or stop"}
|
|
59
|
+
if call is None:
|
|
60
|
+
return unclassified
|
|
61
|
+
target, capability = call.get("target"), call.get("capability")
|
|
62
|
+
if capability == "shell" or cap == "shell":
|
|
63
|
+
prefix = _prefix_of(target, prefixes) if isinstance(target, str) and target.strip() else "undeclared"
|
|
64
|
+
fix = ("retry with --feedback to use a declared command, or stop" if prefix != "undeclared"
|
|
65
|
+
else "--decision retry --allow-command <unit>=<command prefix> (or retry with --feedback)")
|
|
66
|
+
return {"class": "command", "prefix": prefix, "fix": fix}
|
|
67
|
+
if capability not in _PATH_CAPABILITIES or not isinstance(target, str) or not target:
|
|
68
|
+
return unclassified
|
|
69
|
+
if capability == "list" and any(ch in target for ch in "*?["):
|
|
70
|
+
return unclassified
|
|
71
|
+
if target == OUTSIDE:
|
|
72
|
+
return {"class": "outside_workspace", "path_class": "outside",
|
|
73
|
+
"fix": "retry with --feedback naming a path inside the workspace, or stop"}
|
|
74
|
+
return {"class": "inside_workspace", "path_class": "inside",
|
|
75
|
+
"fix": "retry with --feedback naming the permitted way, or stop"}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def refused(unit: str, step: StepSpec, caps: Capabilities, denied: Sequence[str],
|
|
79
|
+
tools_at_start: Sequence[str], calls: Sequence[dict[str, Any]] | None = None,
|
|
80
|
+
prefixes: Sequence[str] = ()) -> list[dict[str, Any]]:
|
|
81
|
+
"""One entry per refused or missing name: `{name, capability, class, fix}` and `path_class` or `prefix`."""
|
|
82
|
+
out: list[dict[str, Any]] = []
|
|
83
|
+
declared = set(step.tools)
|
|
84
|
+
for name in dict.fromkeys(denied):
|
|
85
|
+
cap = capability_of(caps, name)
|
|
86
|
+
if cap is None or cap == "skill:*" or cap == "shell" or cap in declared:
|
|
87
|
+
out.append({"name": name, "capability": cap, **_classed(name, cap, calls, prefixes)})
|
|
88
|
+
else:
|
|
89
|
+
out.append({"name": name, "capability": cap, "class": "undeclared_tool",
|
|
90
|
+
"fix": f"--decision retry --grant {unit}={cap}"})
|
|
91
|
+
if tools_at_start:
|
|
92
|
+
start = set(tools_at_start)
|
|
93
|
+
for cap in step.tools:
|
|
94
|
+
names = tool_names(caps, cap)
|
|
95
|
+
if not names or cap.startswith("skill:") and "Skill" in start or set(names) & start:
|
|
96
|
+
continue
|
|
97
|
+
host = (f"configure the MCP server {cap[4:].split('/', 1)[0]!r} on this machine, then "
|
|
98
|
+
if cap.startswith("mcp:") else "")
|
|
99
|
+
out.append({"name": names[0], "capability": cap, "class": "missing_at_start",
|
|
100
|
+
"fix": f"{host}--decision retry"})
|
|
101
|
+
return out
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Schedules (SCH, release 3 phase R3-T5.1): rule model and slots, exact formats and the word grammar, the canonical
|
|
2
|
+
form and its echo, the schedule entry and fire log, and the fire-decision policies as pure functions.
|
|
3
|
+
|
|
4
|
+
Nothing in this package reads the clock on its own, starts a process or spends: a caller passes the clock, and the
|
|
5
|
+
tick of the next phase only calls the policies (TCK, R3-T5.2). The engine names no workflow here (ADR `the-engine-names-no-workflow`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from tempergraph.schedule.model import (
|
|
11
|
+
Clock,
|
|
12
|
+
Needs,
|
|
13
|
+
Reading,
|
|
14
|
+
Rule,
|
|
15
|
+
ScheduleError,
|
|
16
|
+
Slot,
|
|
17
|
+
When,
|
|
18
|
+
next_slots,
|
|
19
|
+
parse_rule,
|
|
20
|
+
slots_between,
|
|
21
|
+
system_clock,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = ["Clock", "Needs", "Reading", "Rule", "ScheduleError", "Slot", "When", "next_slots", "parse_rule",
|
|
25
|
+
"slots_between", "system_clock"]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Unattended credential kinds and the per-executor check (TCK-B18, TCK-B19, TCK-B5, TCK-B6).
|
|
2
|
+
|
|
3
|
+
A fire runs with nobody present, so each executor declares the kinds it can use unattended (`Capabilities.
|
|
4
|
+
unattended_credentials`) and the check resolves what the operator's credentials profile (`config/credentials/default`
|
|
5
|
+
under the home store) and the environment hold. Presence only: no value is kept, no network call and no model call is
|
|
6
|
+
made (C13). Four kinds: `api_key`, `cloud`, `oauth_token`, `interactive_login`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Mapping, Sequence
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from tempergraph.executors.capabilities import DECLARED
|
|
18
|
+
|
|
19
|
+
PROFILE = "default" # the credentials profile a fire reads (assumption recorded in research `rationale-carried-from-the-engine-specs` F50)
|
|
20
|
+
CLOUD_FLAGS = ("CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY")
|
|
21
|
+
ENV_NAMES: dict[str, dict[str, tuple[str, ...]]] = {
|
|
22
|
+
"claude": {"api_key": ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"), "cloud": CLOUD_FLAGS,
|
|
23
|
+
"oauth_token": ("CLAUDE_CODE_OAUTH_TOKEN",)},
|
|
24
|
+
"agent-sdk": {"api_key": ("ANTHROPIC_API_KEY",), "cloud": CLOUD_FLAGS},
|
|
25
|
+
"messages-api": {"api_key": ("ANTHROPIC_API_KEY",), "cloud": CLOUD_FLAGS},
|
|
26
|
+
"antigravity": {"api_key": ("GEMINI_API_KEY",)},
|
|
27
|
+
}
|
|
28
|
+
HELPER = "apiKeyHelper" # a command in the profile that prints an API key
|
|
29
|
+
LOGIN_FILES: dict[str, tuple[str, ...]] = {"claude": (".claude/.credentials.json",), "antigravity": (".gemini/oauth_creds.json",)}
|
|
30
|
+
CREDENTIAL_NAMES = frozenset(n for kinds in ENV_NAMES.values() for names in kinds.values() for n in names) | {
|
|
31
|
+
"CLAUDE_CODE_OAUTH_TOKEN"}
|
|
32
|
+
FIX = "an API key, an apiKeyHelper or cloud credentials (Bedrock, Vertex or Foundry) in the credentials profile"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Check:
|
|
37
|
+
checked: list[dict[str, Any]] = field(default_factory=list) # one row per executor and role: what `executors_checked` keeps
|
|
38
|
+
warnings: list[str] = field(default_factory=list)
|
|
39
|
+
refusal: tuple[str, str] | None = None # (code, message), the first refusal
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
WARNING_TEXT = {
|
|
43
|
+
"credential_may_expire": "a signed-in session can end; fires then refuse",
|
|
44
|
+
"credential_none": "no credential this check can see; every fire is refused `credential` until the profile or the "
|
|
45
|
+
"environment holds one",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def read_profile(home: Path | None = None, name: str = PROFILE) -> dict[str, str]:
|
|
50
|
+
"""`name=value` lines of the credentials profile (as the claude executor reads a judge's), or nothing."""
|
|
51
|
+
from tempergraph.store.layout import home_path
|
|
52
|
+
|
|
53
|
+
path = (home or home_path()) / "config" / "credentials" / name
|
|
54
|
+
out: dict[str, str] = {}
|
|
55
|
+
try:
|
|
56
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
57
|
+
except OSError:
|
|
58
|
+
return out
|
|
59
|
+
for line in lines:
|
|
60
|
+
if "=" in line and not line.lstrip().startswith("#"):
|
|
61
|
+
k, v = line.split("=", 1)
|
|
62
|
+
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", k.strip()):
|
|
63
|
+
out[k.strip()] = v.strip()
|
|
64
|
+
return out
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def profile_values(profile: Mapping[str, str]) -> dict[str, str]:
|
|
68
|
+
"""The names of the profile that carry credentials: what a fire's child receives, never kept in any entry."""
|
|
69
|
+
return {k: v for k, v in profile.items() if k in CREDENTIAL_NAMES or k == HELPER}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def resolve_kinds(executor: str, environment: Mapping[str, str], profile: Mapping[str, str], *,
|
|
73
|
+
login_present: bool = False) -> frozenset[str]:
|
|
74
|
+
"""Which kinds the environment and the profile hold for one executor (presence only)."""
|
|
75
|
+
names = ENV_NAMES.get(executor, {})
|
|
76
|
+
merged = {**profile, **environment}
|
|
77
|
+
kinds = {kind for kind, vars_ in names.items() if any(merged.get(v) for v in vars_)}
|
|
78
|
+
if executor == "claude" and profile.get(HELPER):
|
|
79
|
+
kinds.add("api_key")
|
|
80
|
+
if login_present and executor in LOGIN_FILES:
|
|
81
|
+
kinds.add("interactive_login")
|
|
82
|
+
return frozenset(kinds)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def login_cached(executor: str, user_home: Path | None = None, environment: Mapping[str, str] | None = None) -> bool:
|
|
86
|
+
"""A person's cached sign-in file of the product; the Keychain cannot be read model-free (P-SCH-2)."""
|
|
87
|
+
base = user_home or Path.home()
|
|
88
|
+
paths = [base / rel for rel in LOGIN_FILES.get(executor, ())]
|
|
89
|
+
if executor == "claude" and (environment or {}).get("CLAUDE_CONFIG_DIR"):
|
|
90
|
+
paths.append(Path(str((environment or {})["CLAUDE_CONFIG_DIR"])) / ".credentials.json")
|
|
91
|
+
return any(p.is_file() for p in paths)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def held_kinds(executors: Sequence[str], environment: Mapping[str, str], profile: Mapping[str, str],
|
|
95
|
+
user_home: Path | None = None) -> dict[str, frozenset[str]]:
|
|
96
|
+
return {ex: resolve_kinds(ex, environment, profile, login_present=login_cached(ex, user_home, environment))
|
|
97
|
+
for ex in dict.fromkeys(executors)}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def bare_judge(executor: str) -> bool:
|
|
101
|
+
"""A judge launched with `--bare` reads no sign-in, so it needs `api_key` or `cloud` (TCK-B6)."""
|
|
102
|
+
caps = DECLARED.get(executor)
|
|
103
|
+
return bool(executor == "claude" and caps is not None and caps.isolates_user_config)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def bindings_of(step_executors: Mapping[str, str], judges: Mapping[str, str]) -> list[dict[str, Any]]:
|
|
107
|
+
"""One binding per executor and role, from the preflight report's step and judge executors."""
|
|
108
|
+
out: list[dict[str, Any]] = []
|
|
109
|
+
for role, names in (("step", step_executors.values()), ("judge", judges.values())):
|
|
110
|
+
for name in dict.fromkeys(names):
|
|
111
|
+
out.append({"executor": name, "role": role, "bare": role == "judge" and bare_judge(name)})
|
|
112
|
+
return out
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def check_fire(entry: Mapping[str, Any], environment: Mapping[str, str], profile: Mapping[str, str],
|
|
116
|
+
user_home: Path | None = None) -> Check:
|
|
117
|
+
"""The check at a fire (TCK-B19, TCK-B5): the executors and judges recorded in the entry at `add` and `edit`,
|
|
118
|
+
resolved in the tick's own environment; a binding with no credential is the `credential` refusal."""
|
|
119
|
+
bindings = [{"executor": c["executor"], "role": c.get("role") or "step",
|
|
120
|
+
"bare": c.get("role") == "judge" and bare_judge(str(c["executor"]))}
|
|
121
|
+
for c in entry.get("executors_checked") or []]
|
|
122
|
+
held = held_kinds([str(b["executor"]) for b in bindings], environment, profile, user_home)
|
|
123
|
+
return check(bindings, held, at_fire=True)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def check(bindings: Sequence[Mapping[str, Any]], held: Mapping[str, frozenset[str]], *, at_fire: bool = False) -> Check:
|
|
127
|
+
"""TCK-B19: accept the kinds each executor declares; `credential_unattended` for any other kind held,
|
|
128
|
+
`judge_credential` for a `--bare` judge with neither `api_key` nor `cloud`, and at a fire `credential` when nothing
|
|
129
|
+
is held (TCK-B5). A weaker `interactive_login` is a `credential_may_expire` warning. Never a model call."""
|
|
130
|
+
out = Check()
|
|
131
|
+
seen: set[tuple[str, str]] = set()
|
|
132
|
+
for b in bindings:
|
|
133
|
+
executor, role = str(b["executor"]), str(b.get("role") or "step")
|
|
134
|
+
if (executor, role) in seen:
|
|
135
|
+
continue
|
|
136
|
+
seen.add((executor, role))
|
|
137
|
+
kinds = held.get(executor, frozenset())
|
|
138
|
+
caps = DECLARED.get(executor)
|
|
139
|
+
row: dict[str, Any] = {"executor": executor, "role": role, "kinds": sorted(kinds), "result": "ok",
|
|
140
|
+
"may_expire": False}
|
|
141
|
+
out.checked.append(row)
|
|
142
|
+
if caps is None or not caps.unattended_credentials:
|
|
143
|
+
row["result"] = "not_checked"
|
|
144
|
+
continue
|
|
145
|
+
usable = kinds & caps.unattended_credentials
|
|
146
|
+
problem: tuple[str, str] | None = None
|
|
147
|
+
if not kinds:
|
|
148
|
+
row["result"] = "none"
|
|
149
|
+
if at_fire:
|
|
150
|
+
problem = ("credential", f"{executor}: no credential in the profile or the environment; add {FIX}")
|
|
151
|
+
elif "credential_none" not in out.warnings: # saved all the same; every fire refuses until one is added
|
|
152
|
+
out.warnings.append("credential_none")
|
|
153
|
+
elif not usable:
|
|
154
|
+
problem = ("credential_unattended", f"{executor}: {', '.join(sorted(kinds))} cannot be used unattended; "
|
|
155
|
+
f"it takes {', '.join(sorted(caps.unattended_credentials))}")
|
|
156
|
+
elif role == "judge" and b.get("bare") and not usable & {"api_key", "cloud"}:
|
|
157
|
+
problem = ("judge_credential", f"{executor}: a judge launched with --bare needs {FIX}; "
|
|
158
|
+
f"{', '.join(sorted(kinds))} alone does not reach it")
|
|
159
|
+
elif usable == {"interactive_login"}:
|
|
160
|
+
row["may_expire"] = True
|
|
161
|
+
if "credential_may_expire" not in out.warnings:
|
|
162
|
+
out.warnings.append("credential_may_expire")
|
|
163
|
+
if problem is not None:
|
|
164
|
+
row["result"] = "refused"
|
|
165
|
+
row["reason"] = problem[0]
|
|
166
|
+
out.refusal = out.refusal or problem
|
|
167
|
+
return out
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""The echo: a sentence rendered from the canonical form only (SCH-B18, SCH-B20, SCH-B2; ADR `exact-formats-first-and-an-optional-word-grammar-echoed-back`).
|
|
2
|
+
|
|
3
|
+
Never rendered from the phrase the person typed: the same stored rule gives the same sentence, and the `rule:`,
|
|
4
|
+
`starts:`, `zone:` and `at:` lines of the text re-parse (through the exact formats) to the stored form.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from tempergraph.schedule.model import (
|
|
15
|
+
Rule,
|
|
16
|
+
Slot,
|
|
17
|
+
When,
|
|
18
|
+
floor_minute,
|
|
19
|
+
next_slots,
|
|
20
|
+
parse_rule,
|
|
21
|
+
utc_offset,
|
|
22
|
+
zone_of,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
NAMES = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
|
|
26
|
+
ORDINALS = {1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", -1: "last"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _join(items: Sequence[str]) -> str:
|
|
30
|
+
return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _nums(values: Sequence[int]) -> str:
|
|
34
|
+
return ", ".join(str(v) for v in sorted(values))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _ordinal(n: int) -> str:
|
|
38
|
+
return ORDINALS.get(n, f"{-n}th from last" if n < 0 else f"{n}th")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _weekdays(days: Sequence[int]) -> str:
|
|
42
|
+
days = sorted(set(days))
|
|
43
|
+
if days == [0, 1, 2, 3, 4]:
|
|
44
|
+
return "Monday to Friday"
|
|
45
|
+
if len(days) == 7:
|
|
46
|
+
return "every day"
|
|
47
|
+
return _join([NAMES[d] for d in days])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _monthdays(rule: Rule, default: int | None = None) -> str:
|
|
51
|
+
vals = sorted(rule.bymonthday) if rule.bymonthday else [default or 1]
|
|
52
|
+
return "on " + _join([f"day {v}" if v > 0 else "the last day" for v in vals]) + " of the month"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _times(rule: Rule, dt0: datetime) -> str:
|
|
56
|
+
minutes = rule.byminute or (dt0.minute,)
|
|
57
|
+
if rule.freq == "HOURLY":
|
|
58
|
+
text = f"At minute {_nums(minutes)}"
|
|
59
|
+
if rule.byhour:
|
|
60
|
+
text += f" past hour {_nums(rule.byhour)}"
|
|
61
|
+
return text + (f", every {rule.interval} hours" if rule.interval > 1 else "")
|
|
62
|
+
return text + (" of every hour" if rule.interval == 1 else f" of every {rule.interval} hours")
|
|
63
|
+
hours = rule.byhour or (dt0.hour,)
|
|
64
|
+
times = [f"{h:02d}:{m:02d}" for h in sorted(hours) for m in sorted(minutes)]
|
|
65
|
+
return "At " + _join(times) if len(times) <= 6 else f"At minute {_nums(minutes)} past hour {_nums(hours)}"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _days(rule: Rule, dt0: datetime) -> str:
|
|
69
|
+
plain = [w for n, w in rule.byday if n == 0]
|
|
70
|
+
nth = [(n, w) for n, w in rule.byday if n != 0]
|
|
71
|
+
k = rule.interval
|
|
72
|
+
if rule.freq == "MONTHLY":
|
|
73
|
+
if nth:
|
|
74
|
+
day = "on the " + _join([f"{_ordinal(n)} {NAMES[w]}" for n, w in nth]) + " of the month"
|
|
75
|
+
elif plain:
|
|
76
|
+
day = "on every " + _join([NAMES[w] for w in sorted(set(plain))]) + " of the month"
|
|
77
|
+
if rule.bymonthday:
|
|
78
|
+
day += " " + _monthdays(rule)
|
|
79
|
+
else:
|
|
80
|
+
day = _monthdays(rule, dt0.day)
|
|
81
|
+
return day + (f", every {k} months" if k > 1 else "")
|
|
82
|
+
names = plain or ([] if rule.bymonthday else [dt0.weekday()])
|
|
83
|
+
parts = ([_weekdays(names)] if names and (rule.freq == "WEEKLY" or plain) else []) + (
|
|
84
|
+
[_monthdays(rule)] if rule.bymonthday else [])
|
|
85
|
+
if rule.freq == "WEEKLY":
|
|
86
|
+
return " ".join(parts) + (f", every {k} weeks" if k > 1 else "")
|
|
87
|
+
day = " ".join(parts) or "every day" # DAILY and HOURLY
|
|
88
|
+
if rule.freq == "DAILY" and k > 1:
|
|
89
|
+
return f"every {k} days" if not parts else f"{day}, every {k} days"
|
|
90
|
+
return day
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def sentence(when: When) -> str:
|
|
94
|
+
"""The echo's sentence, a fixed template over the canonical form (SCH-B18's "At 08:00, Monday to Friday.")."""
|
|
95
|
+
zone = zone_of(when.zone)
|
|
96
|
+
if when.kind == "once":
|
|
97
|
+
at = datetime.fromisoformat(str(when.at))
|
|
98
|
+
return f"Once, on {at:%Y-%m-%d} at {at:%H:%M}."
|
|
99
|
+
rule = parse_rule(str(when.rule))
|
|
100
|
+
dt0 = datetime.fromisoformat(str(when.starts))
|
|
101
|
+
if rule.is_interval:
|
|
102
|
+
if rule.freq == "HOURLY":
|
|
103
|
+
base = "Every hour" if rule.interval == 1 else f"Every {rule.interval} hours"
|
|
104
|
+
else:
|
|
105
|
+
base = f"Every {rule.interval} minutes"
|
|
106
|
+
base += f", from {dt0:%Y-%m-%d %H:%M}"
|
|
107
|
+
else:
|
|
108
|
+
base = f"{_times(rule, dt0)}, {_days(rule, dt0)}"
|
|
109
|
+
if rule.until is not None:
|
|
110
|
+
base += f", until {rule.until.astimezone(zone):%Y-%m-%d %H:%M}"
|
|
111
|
+
if rule.count is not None:
|
|
112
|
+
base += f", for {rule.count} times"
|
|
113
|
+
return base + "."
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _note(s: Slot, zone_name: str) -> str:
|
|
117
|
+
if s.note == "gap":
|
|
118
|
+
return (f"{s.wall:%Y-%m-%d %H:%M} does not exist in {zone_name}; the offset from before the gap makes it "
|
|
119
|
+
f"{s.local:%H:%M}")
|
|
120
|
+
if s.note == "overlap":
|
|
121
|
+
return f"{s.wall:%Y-%m-%d %H:%M} happens twice in {zone_name}; the first occurrence is used"
|
|
122
|
+
return ""
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass
|
|
126
|
+
class Echo:
|
|
127
|
+
sentence: str
|
|
128
|
+
doc: dict[str, Any]
|
|
129
|
+
|
|
130
|
+
def to_doc(self) -> dict[str, Any]:
|
|
131
|
+
return self.doc
|
|
132
|
+
|
|
133
|
+
def text(self) -> str:
|
|
134
|
+
d = self.doc
|
|
135
|
+
lines = [d["sentence"]]
|
|
136
|
+
if d["kind"] == "once":
|
|
137
|
+
lines.append(f"at: {d['at']}")
|
|
138
|
+
else:
|
|
139
|
+
lines += [f"rule: {d['rule']}", f"starts: {d['starts']}"]
|
|
140
|
+
lines.append(f"zone: {d['zone']} (UTC{d['utc_offset']})")
|
|
141
|
+
if not d["slots"]:
|
|
142
|
+
lines.append("next slots: none")
|
|
143
|
+
else:
|
|
144
|
+
lines.append("next slot:" if d["kind"] == "once" else f"next {len(d['slots'])} slots:")
|
|
145
|
+
for s in d["slots"]:
|
|
146
|
+
lines.append(f" {s['local']} local = {s['utc'].replace('T', ' ').replace('Z', '')} UTC")
|
|
147
|
+
lines += [f" note: {n}" for n in d["notes"]]
|
|
148
|
+
lines += [f"assumed: {a}" for a in d["assumptions"]]
|
|
149
|
+
return "\n".join(lines) + "\n"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def build_echo(when: When, assumptions: Sequence[str], now: datetime, n: int = 3) -> Echo:
|
|
153
|
+
"""The echo of a canonical When: the sentence, the zone with its current UTC offset, the next `n` slots (one for
|
|
154
|
+
a `once`) in local and UTC time, any gap or overlap on a listed slot, and each assumption."""
|
|
155
|
+
zone = zone_of(when.zone)
|
|
156
|
+
start = floor_minute(now)
|
|
157
|
+
slots = next_slots(when, start, 1 if when.kind == "once" else n)
|
|
158
|
+
doc: dict[str, Any] = {
|
|
159
|
+
"sentence": sentence(when), "kind": when.kind, "zone": when.zone, "utc_offset": utc_offset(zone, start),
|
|
160
|
+
"slots": [{"local": s.local.strftime("%Y-%m-%d %H:%M"), "utc": s.utc.strftime("%Y-%m-%dT%H:%MZ"), "note": s.note}
|
|
161
|
+
for s in slots],
|
|
162
|
+
"notes": [t for t in (_note(s, when.zone) for s in slots) if t], "assumptions": list(assumptions),
|
|
163
|
+
"canonical": when.to_doc(),
|
|
164
|
+
}
|
|
165
|
+
if when.kind == "once":
|
|
166
|
+
doc["at"] = when.at
|
|
167
|
+
else:
|
|
168
|
+
doc.update(rule=when.rule, starts=when.starts)
|
|
169
|
+
return Echo(sentence=str(doc["sentence"]), doc=doc)
|