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,1090 @@
|
|
|
1
|
+
"""`tempergraph schedule` (SCH-B1, SCH-B8, SCH-B10, SCH-B12, SCH-B13, SCH-B22, SCH-B24, SCH-B25, SCH-B27, SCH-B33; TCK-B1 to
|
|
2
|
+
TCK-B24).
|
|
3
|
+
|
|
4
|
+
Release 3: `parse`, `add` (a workflow target), `list`, `show`, `history`, `edit`, `pause`, `resume`, `skip`, `remove`
|
|
5
|
+
(R3-T5.1) and `fire`, `runs`, `tick`, `loop`, `trigger` and `export` (R3-T5.2). `parse`, `list`, `show`, `history`, `runs`,
|
|
6
|
+
`export` and `trigger status` write nothing and start no process. `add`, `edit`, `resume` and `fire` need a person
|
|
7
|
+
(TCK-B22); `fire` and `tick` are the only verbs that spend, and the tick starts only the engine's own `run`. Only
|
|
8
|
+
`add --orchestration` is refused `not_in_release` (SCH-B33, ADR `release-three-composes-runs-in-parallel-and-grades-in-the-pipeline`: orchestration is release 4). Every refusal exits 2
|
|
9
|
+
with its reason code; a `needs` (an ambiguous phrase, a confirmation, a missing request) exits 3 with the choices as JSON
|
|
10
|
+
on stdout.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
from datetime import UTC, date, datetime, time, timedelta
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from tempergraph.constants import ExitCode
|
|
24
|
+
from tempergraph.schedule import credentials, ledger, policies, store, token
|
|
25
|
+
from tempergraph.schedule.echo import Echo, build_echo
|
|
26
|
+
from tempergraph.schedule.exact import ISO_MINUTE, Parsed, build_recur, parse_exact, parse_wall, with_bounds
|
|
27
|
+
from tempergraph.schedule.model import (
|
|
28
|
+
Clock,
|
|
29
|
+
Needs,
|
|
30
|
+
ScheduleError,
|
|
31
|
+
When,
|
|
32
|
+
floor_minute,
|
|
33
|
+
machine_zone,
|
|
34
|
+
next_slots,
|
|
35
|
+
parse_rule,
|
|
36
|
+
slots_between,
|
|
37
|
+
system_clock,
|
|
38
|
+
wall_to_utc,
|
|
39
|
+
zone_of,
|
|
40
|
+
)
|
|
41
|
+
from tempergraph.schedule.words import parse_words
|
|
42
|
+
from tempergraph.security.scrub import scrub
|
|
43
|
+
|
|
44
|
+
CLOCK: Clock = system_clock # tests replace it: the pure modules take the clock, only this module reads it
|
|
45
|
+
CATCH_UP = ("latest", "none", "all")
|
|
46
|
+
OVERLAP = ("skip", "queue", "parallel")
|
|
47
|
+
SCHEMA = 1
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _Stop(Exception):
|
|
51
|
+
"""End the verb with a document on stdout and an exit code (a `needs` or a check's own refusal)."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, code: int, doc: dict[str, Any]) -> None:
|
|
54
|
+
super().__init__(str(doc.get("status")))
|
|
55
|
+
self.code, self.doc = code, doc
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def add_parsers(sub: Any) -> None:
|
|
59
|
+
from tempergraph.cli.main import WORKSPACES, _caller_options, _settings_options, _spellings
|
|
60
|
+
|
|
61
|
+
p = sub.add_parser("schedule", help="schedule a workflow once or on a recurrence (SCH)")
|
|
62
|
+
s = p.add_subparsers(dest="action", parser_class=type(p))
|
|
63
|
+
|
|
64
|
+
def timing(q: argparse.ArgumentParser) -> None:
|
|
65
|
+
q.add_argument("--when", help="a phrase such as 'every weekday at 8:00'")
|
|
66
|
+
q.add_argument("--at", help="ISO 8601 local, or with an offset or Z: once")
|
|
67
|
+
q.add_argument("--rrule", help="an RFC 5545 RECUR of the stored subset")
|
|
68
|
+
q.add_argument("--every", help="an ISO 8601 duration of at least PT15M")
|
|
69
|
+
q.add_argument("--cron", help="five fields, read in the schedule's zone")
|
|
70
|
+
q.add_argument("--tz", help="an IANA zone name")
|
|
71
|
+
q.add_argument("--starts")
|
|
72
|
+
q.add_argument("--until")
|
|
73
|
+
q.add_argument("--count", type=int)
|
|
74
|
+
q.add_argument("--choose", type=int, help="the reading of an ambiguous phrase")
|
|
75
|
+
|
|
76
|
+
def run_options(q: argparse.ArgumentParser) -> None:
|
|
77
|
+
_spellings(q)
|
|
78
|
+
_settings_options(q)
|
|
79
|
+
ws = q.add_mutually_exclusive_group()
|
|
80
|
+
ws.add_argument("--workspace", choices=WORKSPACES)
|
|
81
|
+
ws.add_argument("--worktree", dest="workspace", action="store_const", const="worktree")
|
|
82
|
+
ws.add_argument("--in-place", dest="workspace", action="store_const", const="in_place")
|
|
83
|
+
|
|
84
|
+
def policy(q: argparse.ArgumentParser) -> None:
|
|
85
|
+
q.add_argument("--budget", metavar="PERIOD:USD", help="day, week or month, and the cap over that period")
|
|
86
|
+
q.add_argument("--catch-up", dest="catch_up", choices=CATCH_UP)
|
|
87
|
+
q.add_argument("--overlap", choices=OVERLAP)
|
|
88
|
+
q.add_argument("--max-live", dest="max_live", type=int)
|
|
89
|
+
q.add_argument("--pause-after-failures", dest="pause_after_failures", type=int)
|
|
90
|
+
|
|
91
|
+
pa = s.add_parser("parse", help="the echo of a timing, or its question or refusal; writes nothing")
|
|
92
|
+
pa.add_argument("phrase", nargs="?", help="a phrase (or use --when or an exact format)")
|
|
93
|
+
timing(pa)
|
|
94
|
+
pa.add_argument("--json", action="store_true")
|
|
95
|
+
|
|
96
|
+
ad = s.add_parser("add", help="schedule a workflow")
|
|
97
|
+
ad.add_argument("workflow", nargs="?")
|
|
98
|
+
ad.add_argument("request", nargs="*")
|
|
99
|
+
timing(ad)
|
|
100
|
+
run_options(ad)
|
|
101
|
+
policy(ad)
|
|
102
|
+
ad.add_argument("--name")
|
|
103
|
+
ad.add_argument("--input", action="append", default=[], metavar="K=V")
|
|
104
|
+
ad.add_argument("--orchestration", metavar="FILE", help="not in this release")
|
|
105
|
+
ad.add_argument("--arg", action="append", default=[], metavar="K=V")
|
|
106
|
+
ad.add_argument("--program", nargs="?", const="*", help="reserved")
|
|
107
|
+
ad.add_argument("--check", action="store_true", help="parse and check; save nothing")
|
|
108
|
+
ad.add_argument("--yes", action="store_true")
|
|
109
|
+
ad.add_argument("--json", action="store_true")
|
|
110
|
+
_caller_options(ad)
|
|
111
|
+
|
|
112
|
+
ls = s.add_parser("list", help="every schedule on this machine")
|
|
113
|
+
ls.add_argument("--all", action="store_true", dest="show_all")
|
|
114
|
+
ls.add_argument("--json", action="store_true")
|
|
115
|
+
sh = s.add_parser("show", help="one schedule: entry, echo, next ten slots, last 20 fires")
|
|
116
|
+
sh.add_argument("id")
|
|
117
|
+
sh.add_argument("--json", action="store_true")
|
|
118
|
+
hi = s.add_parser("history", help="a schedule's fire log")
|
|
119
|
+
hi.add_argument("id")
|
|
120
|
+
hi.add_argument("--since", metavar="DATE")
|
|
121
|
+
hi.add_argument("--json", action="store_true")
|
|
122
|
+
|
|
123
|
+
ed = s.add_parser("edit", help="change a schedule's timing or options (its target is fixed)")
|
|
124
|
+
ed.add_argument("id")
|
|
125
|
+
ed.add_argument("phrase", nargs="?")
|
|
126
|
+
timing(ed)
|
|
127
|
+
run_options(ed)
|
|
128
|
+
policy(ed)
|
|
129
|
+
ed.add_argument("--workflow")
|
|
130
|
+
ed.add_argument("--repo")
|
|
131
|
+
ed.add_argument("--orchestration")
|
|
132
|
+
ed.add_argument("--program", nargs="?", const="*")
|
|
133
|
+
ed.add_argument("--yes", action="store_true")
|
|
134
|
+
ed.add_argument("--json", action="store_true")
|
|
135
|
+
_caller_options(ed)
|
|
136
|
+
|
|
137
|
+
pu = s.add_parser("pause", help="stop firing a schedule")
|
|
138
|
+
pu.add_argument("id")
|
|
139
|
+
pu.add_argument("--reason")
|
|
140
|
+
pu.add_argument("--json", action="store_true")
|
|
141
|
+
_caller_options(pu)
|
|
142
|
+
re_ = s.add_parser("resume", help="start a paused schedule again")
|
|
143
|
+
re_.add_argument("id")
|
|
144
|
+
re_.add_argument("--catch-up", dest="catch_up", action="store_true", help="the slots passed while paused may still fire")
|
|
145
|
+
re_.add_argument("--json", action="store_true")
|
|
146
|
+
_caller_options(re_)
|
|
147
|
+
sk = s.add_parser("skip", help="skip the next slot, or every slot until a date")
|
|
148
|
+
sk.add_argument("id")
|
|
149
|
+
sk.add_argument("--next", action="store_true", dest="next_")
|
|
150
|
+
sk.add_argument("--until", metavar="DATE")
|
|
151
|
+
sk.add_argument("--json", action="store_true")
|
|
152
|
+
_caller_options(sk)
|
|
153
|
+
rm = s.add_parser("remove", help="remove a schedule; its history stays")
|
|
154
|
+
rm.add_argument("id")
|
|
155
|
+
rm.add_argument("--yes", action="store_true")
|
|
156
|
+
rm.add_argument("--json", action="store_true")
|
|
157
|
+
_caller_options(rm)
|
|
158
|
+
|
|
159
|
+
rn = s.add_parser("runs", help="every scheduled run on this machine, from any directory (TCK-B13)")
|
|
160
|
+
rn.add_argument("--schedule")
|
|
161
|
+
rn.add_argument("--repo")
|
|
162
|
+
rn.add_argument("--workflow")
|
|
163
|
+
rn.add_argument("--since", metavar="DATE")
|
|
164
|
+
rn.add_argument("--outcome", choices=ledger.OUTCOMES)
|
|
165
|
+
rn.add_argument("--detail", action="store_true", help="each run's live status through its state root")
|
|
166
|
+
rn.add_argument("--json", action="store_true")
|
|
167
|
+
|
|
168
|
+
fi = s.add_parser("fire", help="start one fire now through the tick's path; it spends (SCH-B26)")
|
|
169
|
+
fi.add_argument("id")
|
|
170
|
+
fi.add_argument("--yes", action="store_true")
|
|
171
|
+
fi.add_argument("--json", action="store_true")
|
|
172
|
+
_caller_options(fi)
|
|
173
|
+
|
|
174
|
+
tr = s.add_parser("trigger", help="the `os` adapter: install, status and remove the per-user autostart entry (TCK-B15)")
|
|
175
|
+
trs = tr.add_subparsers(dest="trigger_action", parser_class=type(tr))
|
|
176
|
+
ti = trs.add_parser("install", help="write one per-user entry that starts the loop at login; idempotent")
|
|
177
|
+
ti.add_argument("--os", action="store_true", dest="os_adapter", help="the `os` adapter")
|
|
178
|
+
ti.add_argument("--json", action="store_true")
|
|
179
|
+
ts = trs.add_parser("status", help="every trigger seen, with its last error; writes nothing")
|
|
180
|
+
ts.add_argument("--json", action="store_true")
|
|
181
|
+
tm = trs.add_parser("remove", help="delete what `install` wrote")
|
|
182
|
+
tm.add_argument("--json", action="store_true")
|
|
183
|
+
|
|
184
|
+
lp = s.add_parser("loop", help="the portable trigger: tick, sleep to the next slot or 60 s, repeat (TCK-B14)")
|
|
185
|
+
mode = lp.add_mutually_exclusive_group()
|
|
186
|
+
mode.add_argument("--detach", action="store_true", help="start the loop in the background; a running one is reported")
|
|
187
|
+
mode.add_argument("--stop", action="store_true", help="end the running loop")
|
|
188
|
+
mode.add_argument("--if-autostart", action="store_true", dest="if_autostart", help=argparse.SUPPRESS)
|
|
189
|
+
|
|
190
|
+
tk = s.add_parser("tick", help="decide what is due and start it: the one call every trigger makes (TCK-B16)")
|
|
191
|
+
tk.add_argument("--json", action="store_true")
|
|
192
|
+
|
|
193
|
+
xp = s.add_parser("export", help="print a snippet for a pipeline system; keeps nothing (TCK-B20)")
|
|
194
|
+
xp.add_argument("id")
|
|
195
|
+
xp.add_argument("--for", dest="target", required=True, choices=("github-actions", "gitlab-ci", "crontab"))
|
|
196
|
+
xp.add_argument("--pin-offset", action="store_true", dest="pin_offset",
|
|
197
|
+
help="for a zone with daylight saving: pin today's UTC offset")
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# --- output ------------------------------------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _emit(env: Any, doc: Any) -> None:
|
|
204
|
+
env.out.write(json.dumps(doc, indent=2, default=str) + "\n")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _refuse(env: Any, a: argparse.Namespace, exc: ScheduleError) -> int:
|
|
208
|
+
env.err.write(f"tempergraph: schedule {a.action}: {exc.code}: {exc.message}\n")
|
|
209
|
+
if getattr(a, "json", False):
|
|
210
|
+
_emit(env, {"schema_version": SCHEMA, "status": "error", "refusals": [{"code": exc.code, "message": exc.message}]})
|
|
211
|
+
return exc.exit_code
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _needs(env: Any, ask: Needs) -> int:
|
|
215
|
+
_emit(env, {"schema_version": SCHEMA, "status": "needs",
|
|
216
|
+
"questions": [{"name": "when", "question": ask.question, "choices": [r.label for r in ask.readings]}],
|
|
217
|
+
"readings": [{"choose": i, "label": r.label, "phrase": r.phrase}
|
|
218
|
+
for i, r in enumerate(ask.readings, start=1)]})
|
|
219
|
+
return int(ExitCode.PAUSED)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _tty(env: Any) -> bool:
|
|
223
|
+
return bool(env.signals[1]) if env.signals else bool(sys.stdin.isatty() and sys.stdout.isatty())
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _confirm(env: Any, a: argparse.Namespace, echo: Echo | None, what: str) -> None:
|
|
227
|
+
"""A yes from `--yes` or from a person at a terminal; else exit 3 with the echo as the `needs`, saving nothing."""
|
|
228
|
+
if getattr(a, "yes", False):
|
|
229
|
+
return
|
|
230
|
+
if _tty(env):
|
|
231
|
+
env.err.write((echo.text() if echo else "") + f"{what} [y/N] ")
|
|
232
|
+
env.err.flush()
|
|
233
|
+
try:
|
|
234
|
+
if sys.stdin.readline().strip().lower() in ("y", "yes"):
|
|
235
|
+
return
|
|
236
|
+
except (OSError, ValueError):
|
|
237
|
+
pass
|
|
238
|
+
doc: dict[str, Any] = {"schema_version": SCHEMA, "status": "needs", "questions": [
|
|
239
|
+
{"name": "confirm", "question": f"{what} {echo.sentence if echo else ''}".strip(), "choices": ["yes"]}]}
|
|
240
|
+
if echo:
|
|
241
|
+
doc["echo"] = echo.to_doc()
|
|
242
|
+
raise _Stop(int(ExitCode.PAUSED), doc)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _now() -> datetime:
|
|
246
|
+
return CLOCK()
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
LOOP_START_WAIT_S = 5.0 # TCK-B1: how long `loop --detach` waits for its child to take the lock
|
|
250
|
+
PERSON_WINDOW = timedelta(minutes=10) # TCK-B22: a person turn this recent carries an agent's `--relayed` call
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _person(env: Any, a: argparse.Namespace, now: datetime, block: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
254
|
+
"""TCK-B22: `add`, `edit`, `resume` and `fire` need `decided_by: person`, a person at a terminal or an agent with
|
|
255
|
+
`--relayed` after a person turn within 10 minutes (`turn_only` suffices). Returns the caller block with its decider."""
|
|
256
|
+
from tempergraph import provenance
|
|
257
|
+
from tempergraph.store.layout import home_path
|
|
258
|
+
|
|
259
|
+
decided = provenance.decide(block or env.caller(a), relayed=bool(getattr(a, "relayed", False)), words=("schedule",),
|
|
260
|
+
since=_stamp(now - PERSON_WINDOW), home=home_path())
|
|
261
|
+
if decided.get("decided_by") != "person":
|
|
262
|
+
raise ScheduleError("schedule_not_by_person", f"schedule {a.action} needs a person: run it at a terminal, or as an "
|
|
263
|
+
"agent with --relayed after the person's own turn in the last 10 minutes")
|
|
264
|
+
return decided
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _known_caller(env: Any, a: argparse.Namespace) -> dict[str, Any]:
|
|
268
|
+
"""TCK-B22: `pause`, `skip` and `remove` only lower spend, so any caller but `unknown` may make them."""
|
|
269
|
+
caller = env.caller(a)
|
|
270
|
+
if caller.get("kind") == "unknown":
|
|
271
|
+
raise ScheduleError("caller_unknown", f"schedule {a.action} is refused from an unknown caller: run it at a terminal "
|
|
272
|
+
"or declare --caller")
|
|
273
|
+
return caller
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# --- timing ------------------------------------------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _ends(when: When) -> tuple[str | None, int | None]:
|
|
280
|
+
if when.kind != "recur":
|
|
281
|
+
return None, None
|
|
282
|
+
rule = parse_rule(str(when.rule))
|
|
283
|
+
ends = rule.until.astimezone(zone_of(when.zone)).strftime(ISO_MINUTE) if rule.until else None
|
|
284
|
+
return ends, rule.count
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _apply_bounds(parsed: Parsed, a: argparse.Namespace, now: datetime) -> Parsed:
|
|
288
|
+
"""`--starts`, `--until` and `--count` beside a phrase bound the recurrence it gave."""
|
|
289
|
+
if a.starts is None and a.until is None and a.count is None:
|
|
290
|
+
return parsed
|
|
291
|
+
when = parsed.when
|
|
292
|
+
if when.kind != "recur":
|
|
293
|
+
raise ScheduleError("when_malformed", "--starts, --until and --count belong to a recurrence, not to a single time")
|
|
294
|
+
notes = list(parsed.assumptions)
|
|
295
|
+
rule = with_bounds(parse_rule(str(when.rule)), a.until, a.count, when.zone, notes)
|
|
296
|
+
starts = parse_wall(a.starts, when.zone, "--starts", notes, need_time=False)[0] if a.starts else datetime.fromisoformat(
|
|
297
|
+
str(when.starts))
|
|
298
|
+
again = build_recur(rule, when.zone, starts, now, notes)
|
|
299
|
+
again.phrase, again.given = parsed.phrase, parsed.given
|
|
300
|
+
return again
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _timing(a: argparse.Namespace, now: datetime, *, phrase: str | None = None) -> Parsed:
|
|
304
|
+
exact = {"at": a.at, "rrule": a.rrule, "every": a.every, "cron": a.cron}
|
|
305
|
+
given = [k for k, v in exact.items() if v is not None]
|
|
306
|
+
phrase = phrase or getattr(a, "phrase", None) or a.when
|
|
307
|
+
if given and phrase:
|
|
308
|
+
raise ScheduleError("when_malformed", "give the timing once: a phrase or one exact format, not both")
|
|
309
|
+
machine = machine_zone()
|
|
310
|
+
if given:
|
|
311
|
+
if a.choose is not None:
|
|
312
|
+
raise ScheduleError("choose_invalid", "--choose answers a phrase; an exact format has one reading")
|
|
313
|
+
return parse_exact(**exact, tz=a.tz, starts=a.starts, until=a.until, count=a.count, now=now, machine=machine)
|
|
314
|
+
if phrase:
|
|
315
|
+
return _apply_bounds(parse_words(phrase, now=now, tz=a.tz, machine=machine, choose=a.choose), a, now)
|
|
316
|
+
raise ScheduleError("when_malformed", "timing is needed: a phrase (--when) or --at, --rrule, --every or --cron")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _when_doc(parsed: Parsed) -> dict[str, Any]:
|
|
320
|
+
ends, count = _ends(parsed.when)
|
|
321
|
+
return {"input": parsed.given or {"format": "--when", "value": parsed.phrase}, "phrase": parsed.phrase,
|
|
322
|
+
**parsed.when.to_doc(), "ends": ends, "count": count}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _echo_doc(env: Any, a: argparse.Namespace, echo: Echo) -> None:
|
|
326
|
+
if getattr(a, "json", False):
|
|
327
|
+
_emit(env, {"schema_version": SCHEMA, "status": "ok", "echo": echo.to_doc(), **echo.to_doc()})
|
|
328
|
+
else:
|
|
329
|
+
env.out.write(echo.text())
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def cmd_parse(env: Any, a: argparse.Namespace) -> int:
|
|
333
|
+
now = _now()
|
|
334
|
+
parsed = _timing(a, now)
|
|
335
|
+
_echo_doc(env, a, build_echo(parsed.when, parsed.assumptions, now))
|
|
336
|
+
return 0
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
# --- reading the store -------------------------------------------------------------------------------------------
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _select(ident: str) -> dict[str, Any]:
|
|
343
|
+
entries = store.list_entries()
|
|
344
|
+
exact = [e for e in entries if e.get("schedule_id") == ident]
|
|
345
|
+
if exact:
|
|
346
|
+
return exact[0]
|
|
347
|
+
named = [e for e in entries if e.get("name") == ident]
|
|
348
|
+
pool = [e for e in named if e.get("state") != "removed"] or named
|
|
349
|
+
if len(pool) == 1:
|
|
350
|
+
return pool[0]
|
|
351
|
+
if not pool:
|
|
352
|
+
raise ScheduleError("schedule_unknown", f"no schedule {ident!r}; `tempergraph schedule list --all` shows them")
|
|
353
|
+
raise ScheduleError("schedule_ambiguous", f"{ident!r} names {len(pool)} schedules ({', '.join(e['schedule_id'] for e in pool)}); "
|
|
354
|
+
"give the id")
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _row(entry: dict[str, Any], log: list[dict[str, Any]], now: datetime, machine: str) -> dict[str, Any]:
|
|
358
|
+
when = When.from_doc(entry["when"])
|
|
359
|
+
nxt = next_slots(when, floor_minute(now), 1) if entry.get("state") == "active" else []
|
|
360
|
+
ended = {e.get("fire_id") for e in log if e.get("kind") == "ended"}
|
|
361
|
+
started = [e for e in log if e.get("kind") == "started"]
|
|
362
|
+
return {
|
|
363
|
+
"schedule_id": entry["schedule_id"], "name": entry["name"],
|
|
364
|
+
"target": entry["target"].get("workflow") or entry["target"].get("orchestration_file"),
|
|
365
|
+
"sentence": build_echo(when, [], now).sentence, "zone": when.zone, "zone_differs": when.zone != machine,
|
|
366
|
+
"state": entry["state"], "next_slot": nxt[0].utc.strftime("%Y-%m-%dT%H:%M:%SZ") if nxt else None,
|
|
367
|
+
"last_fire": started[-1].get("slot") if started else None,
|
|
368
|
+
"live_runs": sum(1 for e in started if e.get("fire_id") not in ended), "failures": policies.failure_count(log),
|
|
369
|
+
"period_spend": policies.period_spend(entry, log, now) if entry.get("budget") else None}
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def cmd_list(env: Any, a: argparse.Namespace) -> int:
|
|
373
|
+
now, machine = _now(), machine_zone()[0]
|
|
374
|
+
rows = [_row(e, store.read_log(e["schedule_id"]), now, machine) for e in store.list_entries()
|
|
375
|
+
if a.show_all or e.get("state") in ("active", "paused")]
|
|
376
|
+
from tempergraph.observe.attention import stale_line, trigger_stale
|
|
377
|
+
|
|
378
|
+
stale = trigger_stale(None, now.timestamp()) # TCK-B7: shown only for a heartbeat older than three intervals
|
|
379
|
+
if a.json:
|
|
380
|
+
_emit(env, {"schema_version": SCHEMA, "machine_zone": machine, "schedules": rows,
|
|
381
|
+
**({"trigger_stale": stale} if stale else {})})
|
|
382
|
+
return 0
|
|
383
|
+
for r in rows:
|
|
384
|
+
mark = " (differs from this machine)" if r["zone_differs"] else ""
|
|
385
|
+
env.out.write(f"{r['schedule_id']}\t{r['name']}\t{r['target']}\t{r['sentence']}\t{r['zone']}{mark}\t{r['state']}\t"
|
|
386
|
+
f"next {r['next_slot'] or '-'}\tlast {r['last_fire'] or 'none'}\tlive {r['live_runs']}\t"
|
|
387
|
+
f"failures {r['failures']}\tspend {'-' if r['period_spend'] is None else r['period_spend']}\n")
|
|
388
|
+
if not rows:
|
|
389
|
+
env.out.write("no schedules\n")
|
|
390
|
+
if stale:
|
|
391
|
+
env.out.write(stale_line(stale) + "\n")
|
|
392
|
+
return 0
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def cmd_show(env: Any, a: argparse.Namespace) -> int:
|
|
396
|
+
entry, now = _select(a.id), _now()
|
|
397
|
+
when = When.from_doc(entry["when"])
|
|
398
|
+
echo = build_echo(when, [], now, n=10)
|
|
399
|
+
log = store.read_log(entry["schedule_id"])[-20:]
|
|
400
|
+
if a.json:
|
|
401
|
+
_emit(env, {"schema_version": SCHEMA, "entry": entry, "echo": echo.to_doc(), "fires": log})
|
|
402
|
+
return 0
|
|
403
|
+
env.out.write(f"{entry['schedule_id']} ({entry['state']}) -> {entry['target'].get('workflow')}\n{echo.text()}")
|
|
404
|
+
env.out.write("last fires:\n" + "".join(f" {e.get('at')} {e.get('kind')} {e.get('slot') or ''}\n" for e in log))
|
|
405
|
+
return 0
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def cmd_history(env: Any, a: argparse.Namespace) -> int:
|
|
409
|
+
entry = _select(a.id)
|
|
410
|
+
log = store.read_log(entry["schedule_id"])
|
|
411
|
+
if a.since:
|
|
412
|
+
try:
|
|
413
|
+
cut = datetime.combine(date.fromisoformat(a.since), time(0), tzinfo=UTC)
|
|
414
|
+
except ValueError:
|
|
415
|
+
raise ScheduleError("when_malformed", f"--since {a.since!r}: an ISO date such as 2026-11-01 is needed") from None
|
|
416
|
+
log = [e for e in log if e.get("at") and datetime.fromisoformat(str(e["at"]).replace("Z", "+00:00")) >= cut]
|
|
417
|
+
if a.json:
|
|
418
|
+
_emit(env, {"schema_version": SCHEMA, "schedule_id": entry["schedule_id"], "fires": log})
|
|
419
|
+
else:
|
|
420
|
+
env.out.write("".join(f"{e.get('seq')}\t{e.get('at')}\t{e.get('kind')}\t{e.get('slot') or ''}\n" for e in log))
|
|
421
|
+
return 0
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _repo_env(env: Any, entry: dict[str, Any]) -> Any:
|
|
425
|
+
"""The same environment, working in the schedule's target repository (the tick runs from anywhere)."""
|
|
426
|
+
import dataclasses
|
|
427
|
+
|
|
428
|
+
return dataclasses.replace(env, cwd=Path(str(entry["target"]["repo"])))
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _state_root(entry: dict[str, Any]) -> Path:
|
|
432
|
+
"""`<repo>/.tempergraph`: where `add` found the repository's state root, read with no git process (TCK-AC3)."""
|
|
433
|
+
from tempergraph.store.layout import STATE_DIR
|
|
434
|
+
|
|
435
|
+
return Path(str(entry["target"]["repo"])) / STATE_DIR
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _tick_edges(env: Any, home: Path) -> Any:
|
|
439
|
+
"""The tick's real edges: the one clock, the detached `run` launcher, the credentials of its own environment, the
|
|
440
|
+
thread status of the target repository's state root and the preflight of `run --check`."""
|
|
441
|
+
from tempergraph.durability import status
|
|
442
|
+
from tempergraph.schedule import launch, tick
|
|
443
|
+
|
|
444
|
+
def status_of(entry: dict[str, Any], thread: str) -> dict[str, Any] | None:
|
|
445
|
+
root = _state_root(entry)
|
|
446
|
+
if not root.is_dir():
|
|
447
|
+
return None
|
|
448
|
+
try:
|
|
449
|
+
row = status.row(root, _spec(env, str(entry["target"]["workflow"])), thread)
|
|
450
|
+
except Exception: # noqa: BLE001 - a root of another engine or a removed workflow leaves the fire to settle later
|
|
451
|
+
return None
|
|
452
|
+
return {"state": row.get("state"), "exit_code": row.get("exit_code"), "cost": row.get("cost"), "alive": row.get("alive")}
|
|
453
|
+
|
|
454
|
+
def preflight(entry: dict[str, Any]) -> tuple[str, str] | None:
|
|
455
|
+
t, options = entry["target"], entry.get("options") or {}
|
|
456
|
+
try:
|
|
457
|
+
_check_run(_repo_env(env, entry), _spec(env, str(t["workflow"])), str(t.get("request") or ""),
|
|
458
|
+
dict(t.get("inputs") or {}), _flags_of(options), options.get("profiles"), str(entry.get("overlap")),
|
|
459
|
+
Path(str(t["repo"])))
|
|
460
|
+
except ScheduleError as exc:
|
|
461
|
+
return exc.code, exc.message
|
|
462
|
+
except _Stop as stop:
|
|
463
|
+
return str(stop.doc.get("status") or "preflight"), json.dumps(stop.doc.get("refusals") or stop.doc.get("questions") or "")
|
|
464
|
+
return None
|
|
465
|
+
|
|
466
|
+
def on_hook(event: str, entry: dict[str, Any], facts: dict[str, Any]) -> None:
|
|
467
|
+
from tempergraph.observe import hooks
|
|
468
|
+
|
|
469
|
+
hooks.on_schedule_event(_state_root(entry), event, str(entry["target"]["workflow"]), str(entry["schedule_id"]), facts)
|
|
470
|
+
|
|
471
|
+
return tick.Edges(clock=_now, launcher=lambda entry, start: launch.launch_run(entry, start, home=home),
|
|
472
|
+
resolver=tick.entry_resolver(os.environ, credentials.read_profile(home)), status_of=status_of,
|
|
473
|
+
state_root_of=_state_root, preflight=preflight, on_hook=on_hook)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def cmd_tick(env: Any, a: argparse.Namespace) -> int:
|
|
477
|
+
"""TCK-B16: one tick. Exit 0 unless the home store is unwritable; a held lock is exit 0 reading nothing."""
|
|
478
|
+
from tempergraph.schedule import tick
|
|
479
|
+
from tempergraph.store.layout import home_path
|
|
480
|
+
|
|
481
|
+
home = home_path()
|
|
482
|
+
result = tick.run_tick(home, _tick_edges(env, home), trigger="external") # the loop calls the tick itself, as `loop`
|
|
483
|
+
if a.json:
|
|
484
|
+
_emit(env, result.to_doc())
|
|
485
|
+
else:
|
|
486
|
+
env.out.write(result.summary() + "\n")
|
|
487
|
+
return result.exit_code
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _trigger_status(now: datetime) -> dict[str, Any]:
|
|
491
|
+
"""TCK-B15: every trigger seen (the loop, the hook, each `os` entry, external ticks from the heartbeat) with its last
|
|
492
|
+
error; reads only."""
|
|
493
|
+
from tempergraph import settings
|
|
494
|
+
from tempergraph.schedule import loop, tick, triggers
|
|
495
|
+
from tempergraph.store.layout import home_path
|
|
496
|
+
|
|
497
|
+
home = home_path()
|
|
498
|
+
beat = tick.read_heartbeat(home)
|
|
499
|
+
kind = (beat or {}).get("trigger")
|
|
500
|
+
err = (beat or {}).get("last_error")
|
|
501
|
+
age = None
|
|
502
|
+
if beat:
|
|
503
|
+
try:
|
|
504
|
+
age = round((now - datetime.fromisoformat(str(beat["last_tick_at"]).replace("Z", "+00:00"))).total_seconds(), 1)
|
|
505
|
+
except (KeyError, ValueError):
|
|
506
|
+
age = None
|
|
507
|
+
live = loop.running(home)
|
|
508
|
+
rows: list[dict[str, Any]] = [
|
|
509
|
+
{"trigger": "loop", "state": "running" if live is not None else "stopped", "pid": (live or {}).get("pid"),
|
|
510
|
+
"last_error": err if kind == "loop" else None},
|
|
511
|
+
{"trigger": "hook", "state": "on" if settings.schedule_settings(home)["loop_autostart"] else "off",
|
|
512
|
+
"last_error": err if kind == "host" else None}]
|
|
513
|
+
for r in triggers.status(home):
|
|
514
|
+
rows.append({**r, "last_error": "the shim it names is missing" if r["state"] == "broken" else None})
|
|
515
|
+
if kind == "external":
|
|
516
|
+
rows.append({"trigger": "external", "state": "seen", "last_error": err})
|
|
517
|
+
return {"schema_version": SCHEMA, "triggers": rows,
|
|
518
|
+
"heartbeat": {"trigger": kind, "last_tick_at": beat.get("last_tick_at"), "age_s": age,
|
|
519
|
+
"interval_s": beat.get("interval_s")} if beat else None}
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def cmd_export(env: Any, a: argparse.Namespace) -> int:
|
|
523
|
+
"""TCK-B20: print the snippet; read-only, nothing is kept."""
|
|
524
|
+
from tempergraph.schedule import export
|
|
525
|
+
|
|
526
|
+
env.out.write(export.render(_select(a.id), a.target, bool(a.pin_offset), _now()))
|
|
527
|
+
return 0
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def cmd_trigger(env: Any, a: argparse.Namespace) -> int:
|
|
531
|
+
from tempergraph.schedule import triggers
|
|
532
|
+
from tempergraph.store.layout import home_path
|
|
533
|
+
|
|
534
|
+
action = a.trigger_action
|
|
535
|
+
if action is None:
|
|
536
|
+
raise ScheduleError("when_malformed", "schedule trigger needs install, status or remove")
|
|
537
|
+
if action == "status":
|
|
538
|
+
doc = _trigger_status(_now())
|
|
539
|
+
if a.json:
|
|
540
|
+
_emit(env, doc)
|
|
541
|
+
else:
|
|
542
|
+
for r in doc["triggers"]:
|
|
543
|
+
env.out.write(f"{r['trigger']}\t{r['state']}\t{r.get('path') or r.get('pid') or '-'}\t{r.get('last_error') or '-'}\n")
|
|
544
|
+
hb = doc["heartbeat"]
|
|
545
|
+
tail = f" ({hb['age_s']}s ago, trigger {hb['trigger']})" if hb else ""
|
|
546
|
+
env.out.write(f"last tick: {hb['last_tick_at'] if hb else 'never'}{tail}\n")
|
|
547
|
+
return 0
|
|
548
|
+
if action == "remove":
|
|
549
|
+
gone = triggers.remove(home_path())
|
|
550
|
+
return _done(env, a, "os", removed=gone)
|
|
551
|
+
if not a.os_adapter:
|
|
552
|
+
raise ScheduleError("trigger_adapter_needed", "schedule trigger install needs --os, the only adapter it writes")
|
|
553
|
+
try:
|
|
554
|
+
got = triggers.install(home_path())
|
|
555
|
+
except triggers.NoOsScheduler as exc:
|
|
556
|
+
raise ScheduleError("no_os_scheduler", str(exc)) from None
|
|
557
|
+
except triggers.UnsafePath as exc:
|
|
558
|
+
raise ScheduleError("shim_path_unsafe", f"the shim's path {exc} cannot be written into a crontab line") from None
|
|
559
|
+
return _done(env, a, "os", **got)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def cmd_loop(env: Any, a: argparse.Namespace) -> int:
|
|
563
|
+
"""TCK-B14: `loop` runs the loop here; `--detach` starts it in the background (a running loop is reported, exit 0);
|
|
564
|
+
`--stop` ends it; `--if-autostart` is the `host` adapter's call, silent and always exit 0."""
|
|
565
|
+
import time
|
|
566
|
+
|
|
567
|
+
from tempergraph import detach
|
|
568
|
+
from tempergraph.install import shim
|
|
569
|
+
from tempergraph.schedule import loop, tick
|
|
570
|
+
from tempergraph.store.layout import home_path
|
|
571
|
+
|
|
572
|
+
home = home_path()
|
|
573
|
+
if a.stop:
|
|
574
|
+
env.out.write("stop requested\n" if loop.stop(home) else "no loop is running\n")
|
|
575
|
+
return 0
|
|
576
|
+
if a.if_autostart:
|
|
577
|
+
loop.autostart(home, lambda: detach.start_loop(home))
|
|
578
|
+
return 0
|
|
579
|
+
if a.detach:
|
|
580
|
+
found = loop.running(home)
|
|
581
|
+
if found is not None:
|
|
582
|
+
env.out.write(f"the loop is already running (pid {found.get('pid', 'unknown')})\n")
|
|
583
|
+
return 0
|
|
584
|
+
if not detach.start_loop(home):
|
|
585
|
+
raise ScheduleError("loop_not_started", "the loop could not be started")
|
|
586
|
+
# TCK-B1: wait until the child holds the lock, so a second call right after this one reports it instead of
|
|
587
|
+
# starting another child (found live: two quick calls both said "loop started")
|
|
588
|
+
deadline = time.monotonic() + LOOP_START_WAIT_S
|
|
589
|
+
while loop.running(home) is None and time.monotonic() < deadline:
|
|
590
|
+
time.sleep(0.1)
|
|
591
|
+
env.out.write("loop started\n")
|
|
592
|
+
return 0
|
|
593
|
+
edges = loop.Edges(clock=_now, monotonic=time.monotonic, sleeper=time.sleep,
|
|
594
|
+
tick=lambda: tick.run_tick(home, _tick_edges(env, home), trigger="loop"),
|
|
595
|
+
switched=lambda: loop.engine_switched(home),
|
|
596
|
+
reexec=lambda: detach.start_loop(home, shim.shim_path(home)))
|
|
597
|
+
return loop.run_loop(home, edges)
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def cmd_fire(env: Any, a: argparse.Namespace) -> int:
|
|
601
|
+
"""SCH-B26: one fire now through the tick's own path (the same preflight, credential check, `started` event, ledger
|
|
602
|
+
row and launch), with no catch-up. It spends, so it needs a person and a yes; with `tick` it is the only verb that does."""
|
|
603
|
+
from tempergraph.schedule import tick
|
|
604
|
+
from tempergraph.store.layout import home_path
|
|
605
|
+
|
|
606
|
+
entry = _select(a.id)
|
|
607
|
+
sid = str(entry["schedule_id"])
|
|
608
|
+
if entry.get("state") != "active":
|
|
609
|
+
raise ScheduleError("schedule_state", f"{sid} is {entry['state']}; only an active schedule is fired")
|
|
610
|
+
now = _now()
|
|
611
|
+
base = env.caller(a)
|
|
612
|
+
cap = float(entry.get("run_cost_cap_usd") or 0.0)
|
|
613
|
+
_confirm(env, a, build_echo(When.from_doc(entry["when"]), [], now), f"Fire {sid} now? It may spend up to {cap:g} USD.")
|
|
614
|
+
_person(env, a, now, base) # TCK-B22
|
|
615
|
+
home = home_path()
|
|
616
|
+
result, start = tick.fire_now(entry, _tick_edges(env, home), home)
|
|
617
|
+
if not start:
|
|
618
|
+
raise ScheduleError("schedule_busy", f"{sid} is being handled by a tick; try again in a moment")
|
|
619
|
+
if result.refused:
|
|
620
|
+
last = [e for e in store.read_log(sid) if e.get("kind") == "refused"][-1]
|
|
621
|
+
raise ScheduleError(str(last.get("reason") or "refused"), f"{sid}: the fire was refused: {last.get('message') or ''}".strip())
|
|
622
|
+
if not result.started:
|
|
623
|
+
raise ScheduleError("schedule_busy", f"{sid}: the fire was not started")
|
|
624
|
+
return _done(env, a, sid, status="started", fire_id=start["fire_id"], thread_id=start["thread"])
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def _detail(env: Any, row: dict[str, Any]) -> dict[str, Any] | None:
|
|
628
|
+
"""`--detail`: the run's live status through its state root, when the root and the workflow are still there."""
|
|
629
|
+
from tempergraph.durability import status
|
|
630
|
+
|
|
631
|
+
root, thread = row.get("state_root"), row.get("thread_id")
|
|
632
|
+
if not root or not thread or not Path(root).is_dir():
|
|
633
|
+
return None
|
|
634
|
+
try:
|
|
635
|
+
return status.row(Path(root), _spec(env, str((row.get("target") or {}).get("workflow"))), str(thread))
|
|
636
|
+
except Exception: # a state root of another engine or a removed workflow is not an error of this read
|
|
637
|
+
return None
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def cmd_runs(env: Any, a: argparse.Namespace) -> int:
|
|
641
|
+
"""TCK-B13: every fire on the machine, read-only, from any directory; `records_gone` marks a missing state root."""
|
|
642
|
+
since = None
|
|
643
|
+
if a.since:
|
|
644
|
+
try:
|
|
645
|
+
since = date.fromisoformat(a.since)
|
|
646
|
+
except ValueError:
|
|
647
|
+
raise ScheduleError("when_malformed", f"--since {a.since!r}: an ISO date such as 2026-11-01 is needed") from None
|
|
648
|
+
repo = str(Path(a.repo).expanduser().resolve()) if a.repo else None
|
|
649
|
+
rows = ledger.read(schedule=a.schedule, repo=repo, workflow=a.workflow, since=since, outcome=a.outcome)
|
|
650
|
+
for r in rows:
|
|
651
|
+
r["records_gone"] = bool(r.get("state_root")) and not Path(str(r["state_root"])).exists()
|
|
652
|
+
if a.detail:
|
|
653
|
+
r["detail"] = _detail(env, r)
|
|
654
|
+
if a.json:
|
|
655
|
+
_emit(env, {"schema_version": SCHEMA, "runs": rows})
|
|
656
|
+
return 0
|
|
657
|
+
for r in rows:
|
|
658
|
+
ended, t = r.get("ended") or {}, r.get("target") or {}
|
|
659
|
+
why = ":" + r["reason"] if r.get("reason") else ""
|
|
660
|
+
gone = "\trecords_gone" if r["records_gone"] else ""
|
|
661
|
+
env.out.write(f"{r['fired_at']}\t{r['schedule_id']}\t{t.get('repo_name') or '-'}\t{r['outcome']}{why}\t"
|
|
662
|
+
f"{r.get('thread_id') or '-'}\texit {ended.get('exit', '-')}\t"
|
|
663
|
+
f"{(ended.get('cost') or {}).get('estimated', '-')}{gone}\n")
|
|
664
|
+
if not rows:
|
|
665
|
+
env.out.write("no scheduled runs\n")
|
|
666
|
+
return 0
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
# --- the settings check and the caps (SCH-B24, SCH-B25, SCH-B10, SCH-B22) --------------------------------------------
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _spec(env: Any, name: str) -> Any:
|
|
673
|
+
from tempergraph.catalog import PackageNotLoaded
|
|
674
|
+
from tempergraph.cli.main import UsageError
|
|
675
|
+
from tempergraph.cli.main import _spec as resolve
|
|
676
|
+
|
|
677
|
+
try:
|
|
678
|
+
return resolve(env, name)
|
|
679
|
+
except (UsageError, PackageNotLoaded) as exc:
|
|
680
|
+
raise ScheduleError("workflow_unregistered", f"{name!r} is not a registered workflow ({exc}); "
|
|
681
|
+
"`tempergraph list` shows the catalog") from None
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def _caps(spec: Any, flags: dict[str, Any], notes: list[str]) -> float:
|
|
685
|
+
"""A cap is required: the workflow's own satisfies it, and the flag only lowers it (SCH-B24, SCH-B8)."""
|
|
686
|
+
key = "run.run_cost_cap_usd"
|
|
687
|
+
flag, own = flags.get(key), spec.run_cost_cap_usd
|
|
688
|
+
if flag is None and own is None:
|
|
689
|
+
raise ScheduleError("cost_cap_required", "a schedule spends unattended: give --run-cost-cap, or use a workflow "
|
|
690
|
+
"that declares run_cost_cap_usd")
|
|
691
|
+
if flag is not None and (isinstance(flag, bool) or not isinstance(flag, (int, float)) or flag <= 0):
|
|
692
|
+
raise ScheduleError("cost_cap_required", f"--run-cost-cap {flag!r}: a number above 0 is needed")
|
|
693
|
+
if flag is not None and own is not None and flag > own:
|
|
694
|
+
notes.append(f"run cost cap stays {own:g}: the workflow's own cap, which --run-cost-cap only lowers")
|
|
695
|
+
flags[key] = float(own)
|
|
696
|
+
return float(own)
|
|
697
|
+
cap = float(flag if flag is not None else own)
|
|
698
|
+
flags[key] = cap
|
|
699
|
+
return cap
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _check_run(env: Any, spec: Any, request: str, inputs: dict[str, str], flags: dict[str, Any],
|
|
703
|
+
profiles: list[str] | None, overlap: str, repo: Path) -> credentials.Check:
|
|
704
|
+
"""`run --check`'s own steps (resolve the request, settle the settings, preflight), refusing as it refuses, and the
|
|
705
|
+
credential check of each executor and judge binding of the run (TCK-B19): its rows are `executors_checked`."""
|
|
706
|
+
from tempergraph.catalog import resolve_request
|
|
707
|
+
from tempergraph.cli.main import CHECK_EXIT, _root_or_none
|
|
708
|
+
from tempergraph.executors.preflight import preflight
|
|
709
|
+
from tempergraph.run.runner import RunSettings, SettingsRefused, settle_start
|
|
710
|
+
from tempergraph.workspace import WorkspaceRefused, resolve_workspace
|
|
711
|
+
|
|
712
|
+
res = resolve_request(spec, request.split(), inputs, env.cwd, None)
|
|
713
|
+
doc: dict[str, Any] = {"schema_version": SCHEMA, "status": res.status, "workflow": spec.name}
|
|
714
|
+
if res.status == "needs":
|
|
715
|
+
doc["questions"] = [{"name": q.name, "question": q.question, "choices": list(q.choices or [])} for q in res.questions]
|
|
716
|
+
raise _Stop(int(ExitCode.PAUSED), doc) # SCH-B25: exit 3 on `needs`, 2 on `error`, saving nothing
|
|
717
|
+
if res.status != "ok":
|
|
718
|
+
doc["message"] = res.message
|
|
719
|
+
raise _Stop(int(CHECK_EXIT["error"]), doc)
|
|
720
|
+
try:
|
|
721
|
+
settled = settle_start(spec, RunSettings(flags=flags, profiles=tuple(profiles) if profiles else None,
|
|
722
|
+
origin="schedule", caller={}), _root_or_none(env))
|
|
723
|
+
except SettingsRefused as exc:
|
|
724
|
+
doc.update(status="error", refusals=[{"code": f.code, "unit": f.unit, "message": f.message} for f in exc.findings])
|
|
725
|
+
raise _Stop(int(CHECK_EXIT["error"]), doc) from None
|
|
726
|
+
rv = settled.run
|
|
727
|
+
rep = preflight(settled.spec, env.registry, enforce_tools=bool(rv["enforce_tools"]),
|
|
728
|
+
strict_permissions=bool(rv["strict_permissions"]))
|
|
729
|
+
if rep.refusals:
|
|
730
|
+
doc.update(status="error", refusals=[{"code": f.code, "unit": f.unit, "message": f.message} for f in rep.refusals])
|
|
731
|
+
raise _Stop(int(CHECK_EXIT["error"]), doc)
|
|
732
|
+
if overlap == "parallel": # SCH-B22: a parallel fire needs its own worktree
|
|
733
|
+
try:
|
|
734
|
+
plan = resolve_workspace(settled.spec, repo, rv.get("workspace"))
|
|
735
|
+
except WorkspaceRefused as exc:
|
|
736
|
+
raise ScheduleError(getattr(exc, "code", "workspace_refused"), str(exc)) from None
|
|
737
|
+
if plan.mode != "worktree":
|
|
738
|
+
raise ScheduleError("parallel_needs_worktree", "overlap parallel needs run.workspace to resolve to worktree; "
|
|
739
|
+
f"it resolves to {plan.mode}")
|
|
740
|
+
bindings = credentials.bindings_of(rep.step_executors, rep.judges)
|
|
741
|
+
verdict = credentials.check(bindings, credentials.held_kinds([b["executor"] for b in bindings], os.environ,
|
|
742
|
+
credentials.read_profile()))
|
|
743
|
+
if verdict.refusal is not None:
|
|
744
|
+
raise ScheduleError(*verdict.refusal)
|
|
745
|
+
return verdict
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _repo(env: Any) -> Path:
|
|
749
|
+
from tempergraph import git
|
|
750
|
+
from tempergraph.store.layout import NotInRepository, state_root_path
|
|
751
|
+
|
|
752
|
+
main = git.main_checkout(env.cwd)
|
|
753
|
+
if main is not None:
|
|
754
|
+
return Path(main)
|
|
755
|
+
try:
|
|
756
|
+
return state_root_path(env.cwd).parent
|
|
757
|
+
except NotInRepository as exc:
|
|
758
|
+
raise ScheduleError("repo_unusable", str(exc)) from None
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _budget(text: str | None) -> dict[str, Any] | None:
|
|
762
|
+
if text is None:
|
|
763
|
+
return None
|
|
764
|
+
period, sep, cap = text.partition(":")
|
|
765
|
+
try:
|
|
766
|
+
value = float(cap)
|
|
767
|
+
except ValueError:
|
|
768
|
+
value = 0.0
|
|
769
|
+
if not sep or period not in ("day", "week", "month") or value <= 0:
|
|
770
|
+
raise ScheduleError("budget_invalid", f"--budget {text!r}: day, week or month, a colon and a cap above 0, such as month:20")
|
|
771
|
+
return {"period": period, "cap_usd": value}
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def _limit(name: str, value: int | None, lo: int, hi: int, default: int) -> int:
|
|
775
|
+
if value is None:
|
|
776
|
+
return default
|
|
777
|
+
if not lo <= value <= hi:
|
|
778
|
+
raise ScheduleError("option_invalid", f"--{name.replace('_', '-')} {value}: {lo} to {hi}")
|
|
779
|
+
return value
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def _options(flags: dict[str, Any], profiles: list[str] | None) -> dict[str, Any]:
|
|
783
|
+
return {"flag": {k: {"value": v, "ref": f"--set {k}", "via": "schedule"} for k, v in flags.items()},
|
|
784
|
+
"profiles": list(profiles or [])}
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def _flags_of(options: dict[str, Any]) -> dict[str, Any]:
|
|
788
|
+
return {k: c["value"] for k, c in (options.get("flag") or {}).items()}
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def _guard_flags(env: Any, a: argparse.Namespace) -> dict[str, Any]:
|
|
792
|
+
from tempergraph.cli.main import _flags
|
|
793
|
+
from tempergraph.settings import is_widening
|
|
794
|
+
|
|
795
|
+
flags = _flags(env, a)
|
|
796
|
+
for key in flags:
|
|
797
|
+
if is_widening(key): # a grant is a person's decision for one run (SCH-B10)
|
|
798
|
+
raise ScheduleError("widening_in_schedule", f"{key}: a schedule cannot carry a grant; a person gives one to a "
|
|
799
|
+
"paused scheduled run on resume")
|
|
800
|
+
return flags
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
def _inputs(pairs: list[str]) -> dict[str, str]:
|
|
804
|
+
out: dict[str, str] = {}
|
|
805
|
+
for p in pairs:
|
|
806
|
+
k, sep, v = p.partition("=")
|
|
807
|
+
if not sep or not k:
|
|
808
|
+
raise ScheduleError("input_invalid", f"--input {p!r}: expected key=value")
|
|
809
|
+
out[k] = v
|
|
810
|
+
return out
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
# --- mutating verbs ----------------------------------------------------------------------------------------------
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def cmd_add(env: Any, a: argparse.Namespace) -> int:
|
|
817
|
+
if a.orchestration is not None: # SCH-B33: with orchestration, release 4 (ADR `release-three-composes-runs-in-parallel-and-grades-in-the-pipeline`)
|
|
818
|
+
raise ScheduleError("not_in_release", "schedule add --orchestration is not in this release: orchestration "
|
|
819
|
+
"comes in release 4 (ADR `release-three-composes-runs-in-parallel-and-grades-in-the-pipeline`)")
|
|
820
|
+
if a.program is not None:
|
|
821
|
+
raise ScheduleError("program_target_reserved", "schedule add --program is reserved until a package can declare programs")
|
|
822
|
+
if not a.workflow:
|
|
823
|
+
raise ScheduleError("workflow_unregistered", "schedule add needs a workflow and a request")
|
|
824
|
+
spec = _spec(env, a.workflow)
|
|
825
|
+
caller, now = env.caller(a), _now()
|
|
826
|
+
parsed = _timing(a, now)
|
|
827
|
+
flags = _guard_flags(env, a)
|
|
828
|
+
notes = list(parsed.assumptions)
|
|
829
|
+
cap = _caps(spec, flags, notes)
|
|
830
|
+
overlap = a.overlap or "skip"
|
|
831
|
+
request, inputs, repo = " ".join(a.request).strip(), _inputs(a.input), _repo(env)
|
|
832
|
+
verdict = _check_run(env, spec, request, inputs, flags, a.profile, overlap, repo)
|
|
833
|
+
budget = _budget(a.budget)
|
|
834
|
+
entries = store.list_entries()
|
|
835
|
+
if sum(1 for e in entries if e.get("state") != "removed") >= store.MAX_SCHEDULES:
|
|
836
|
+
raise ScheduleError("too_many_schedules", f"{store.MAX_SCHEDULES} schedules are the most on one machine")
|
|
837
|
+
sid = store.new_schedule_id(a.name or spec.name, {str(e["schedule_id"]) for e in entries})
|
|
838
|
+
echo = build_echo(parsed.when, notes, now)
|
|
839
|
+
if a.check:
|
|
840
|
+
_echo_doc(env, a, echo)
|
|
841
|
+
return 0
|
|
842
|
+
_confirm(env, a, echo, "Save this schedule?")
|
|
843
|
+
caller = _person(env, a, now, caller) # TCK-B22: after the confirmation, before anything is written
|
|
844
|
+
secret = token.make_token() # TCK-B17: the digest goes in the entry, the token in a private file beside it
|
|
845
|
+
when = _when_doc(parsed)
|
|
846
|
+
entry = store.build_entry(
|
|
847
|
+
schedule_id=sid, name=a.name or spec.name, target={"kind": "workflow", "workflow": spec.name, "repo": str(repo),
|
|
848
|
+
"request": request, "inputs": inputs},
|
|
849
|
+
when=when, options=_options(flags, a.profile), run_cost_cap_usd=cap, budget=budget,
|
|
850
|
+
catch_up=a.catch_up or "latest", catch_up_window_s=_window(when), overlap=overlap,
|
|
851
|
+
max_live=_limit("max_live", a.max_live, 1, 4, 1),
|
|
852
|
+
pause_after_failures=_limit("pause_after_failures", a.pause_after_failures, 1, 10, 3),
|
|
853
|
+
created={"at": _stamp(now), "caller": caller, "from": "schedule add"}, now=now,
|
|
854
|
+
token_digest=token.digest(secret), executors_checked=verdict.checked)
|
|
855
|
+
token.write_token(sid, secret)
|
|
856
|
+
store.write_entry(entry)
|
|
857
|
+
store.append_event(sid, "created", now=now, caller=caller, when=parsed.when.to_doc(), target=spec.name,
|
|
858
|
+
err=env.err)
|
|
859
|
+
for w in verdict.warnings:
|
|
860
|
+
env.err.write(f"tempergraph: schedule add: warning {w}: {credentials.WARNING_TEXT[w]}\n")
|
|
861
|
+
warning = _trigger_warning(now) # TCK-B15: saved all the same
|
|
862
|
+
if warning:
|
|
863
|
+
env.err.write(f"tempergraph: schedule add: warning trigger_none: {warning}\n")
|
|
864
|
+
if a.json:
|
|
865
|
+
_emit(env, {"schema_version": SCHEMA, "status": "saved", "schedule_id": sid, "echo": echo.to_doc(),
|
|
866
|
+
"warnings": verdict.warnings, **({"trigger_warning": warning} if warning else {})})
|
|
867
|
+
else:
|
|
868
|
+
env.out.write(echo.text() + f"saved {sid}\n")
|
|
869
|
+
return 0
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
def _trigger_warning(now: datetime) -> str | None:
|
|
873
|
+
"""TCK-B15: with no live trigger (no loop lock, no `os` entry, no heartbeat within three intervals) a saved schedule
|
|
874
|
+
will not fire: offer the loop and name the optional adapters once."""
|
|
875
|
+
from tempergraph.schedule import loop
|
|
876
|
+
from tempergraph.store.layout import home_path
|
|
877
|
+
|
|
878
|
+
if loop.trigger_alive(home_path(), now, _os_entry):
|
|
879
|
+
return None
|
|
880
|
+
return ("no trigger is running, so this schedule will not fire yet: run `tempergraph schedule loop --detach`. Optional "
|
|
881
|
+
"adapters: `tempergraph schedule trigger install --os` starts the loop at login, the plugin's session hook "
|
|
882
|
+
"starts it when `schedule.loop_autostart` is on, and any scheduler can call `tempergraph schedule tick`")
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def _os_entry() -> bool:
|
|
886
|
+
from tempergraph.schedule import triggers
|
|
887
|
+
from tempergraph.store.layout import home_path
|
|
888
|
+
|
|
889
|
+
return triggers.entries_present(home_path())
|
|
890
|
+
|
|
891
|
+
|
|
892
|
+
def _stamp(now: datetime) -> str:
|
|
893
|
+
return now.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def _window(when: dict[str, Any]) -> int:
|
|
897
|
+
return policies.default_window_s({"when": when})
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def cmd_edit(env: Any, a: argparse.Namespace) -> int:
|
|
901
|
+
entry = _select(a.id)
|
|
902
|
+
if a.orchestration is not None or a.program is not None:
|
|
903
|
+
raise ScheduleError("target_fixed", "a schedule's target kind is fixed; remove it and add another")
|
|
904
|
+
target = entry["target"]
|
|
905
|
+
if (a.workflow and a.workflow != target.get("workflow")) or (a.repo and Path(a.repo).resolve() != Path(target["repo"])):
|
|
906
|
+
raise ScheduleError("target_fixed", "a schedule's workflow, repo and target kind are fixed; remove it and add another")
|
|
907
|
+
if entry.get("state") in ("removed", "done"):
|
|
908
|
+
raise ScheduleError("schedule_state", f"{entry['schedule_id']} is {entry['state']}; it cannot be edited")
|
|
909
|
+
caller, now = env.caller(a), _now()
|
|
910
|
+
sid = str(entry["schedule_id"])
|
|
911
|
+
old = When.from_doc(entry["when"])
|
|
912
|
+
changed: list[str] = []
|
|
913
|
+
notes: list[str] = []
|
|
914
|
+
new_entry: dict[str, Any] = dict(entry)
|
|
915
|
+
timing_given = any(v is not None for v in (a.phrase, a.when, a.at, a.rrule, a.every, a.cron))
|
|
916
|
+
echo_when = old
|
|
917
|
+
if timing_given:
|
|
918
|
+
parsed = _timing(a, now)
|
|
919
|
+
echo_when, notes = parsed.when, list(parsed.assumptions)
|
|
920
|
+
new_entry["when"] = _when_doc(parsed)
|
|
921
|
+
if entry.get("catch_up_window_s") == _window(entry["when"]): # the default window follows the new recurrence
|
|
922
|
+
new_entry["catch_up_window_s"] = _window(new_entry["when"])
|
|
923
|
+
changed.append("when")
|
|
924
|
+
elif any(v is not None for v in (a.tz, a.starts, a.until, a.count)):
|
|
925
|
+
raise ScheduleError("when_malformed", "--tz, --starts, --until and --count change a timing: give it too")
|
|
926
|
+
flags_new = _guard_flags(env, a)
|
|
927
|
+
flags = {**_flags_of(entry["options"]), **flags_new}
|
|
928
|
+
profiles = a.profile if a.profile is not None else entry["options"].get("profiles")
|
|
929
|
+
spec = _spec(env, str(target["workflow"]))
|
|
930
|
+
cap = _caps(spec, flags, notes)
|
|
931
|
+
if flags_new or a.profile is not None:
|
|
932
|
+
new_entry["options"] = _options(flags, profiles)
|
|
933
|
+
changed.append("options")
|
|
934
|
+
if cap != entry["run_cost_cap_usd"]:
|
|
935
|
+
new_entry["run_cost_cap_usd"] = cap
|
|
936
|
+
changed.append("run_cost_cap_usd")
|
|
937
|
+
for key, value in (("catch_up", a.catch_up), ("overlap", a.overlap)):
|
|
938
|
+
if value is not None and value != entry.get(key):
|
|
939
|
+
new_entry[key] = value
|
|
940
|
+
changed.append(key)
|
|
941
|
+
for key, lo, hi in (("max_live", 1, 4), ("pause_after_failures", 1, 10)):
|
|
942
|
+
value = getattr(a, key)
|
|
943
|
+
if value is not None and value != entry.get(key):
|
|
944
|
+
new_entry[key] = _limit(key, value, lo, hi, entry[key])
|
|
945
|
+
changed.append(key)
|
|
946
|
+
if a.budget is not None:
|
|
947
|
+
new_entry["budget"] = _budget(a.budget)
|
|
948
|
+
changed.append("budget")
|
|
949
|
+
if not changed:
|
|
950
|
+
raise ScheduleError("nothing_to_edit", "give a new timing or an option to change")
|
|
951
|
+
verdict = _check_run(env, spec, str(target.get("request") or ""), dict(target.get("inputs") or {}), flags, profiles,
|
|
952
|
+
str(new_entry["overlap"]), Path(target["repo"]))
|
|
953
|
+
new_entry["executors_checked"] = verdict.checked
|
|
954
|
+
echo = build_echo(echo_when, notes, now)
|
|
955
|
+
_confirm(env, a, echo, "Save these changes?")
|
|
956
|
+
caller = _person(env, a, now, caller) # TCK-B22
|
|
957
|
+
new_entry["edited"] = {"at": _stamp(now), "caller": caller, "from": "schedule edit"}
|
|
958
|
+
first = next_slots(When.from_doc(new_entry["when"]), floor_minute(now), 1)
|
|
959
|
+
new_entry["next_slot"] = _stamp(first[0].utc) if first else None
|
|
960
|
+
store.write_entry(new_entry)
|
|
961
|
+
store.append_event(sid, "edited", now=now, caller=caller, changed=changed, old=old.to_doc(), new=echo_when.to_doc(),
|
|
962
|
+
err=env.err)
|
|
963
|
+
for w in verdict.warnings:
|
|
964
|
+
env.err.write(f"tempergraph: schedule edit: warning {w}: {credentials.WARNING_TEXT[w]}\n")
|
|
965
|
+
if a.json:
|
|
966
|
+
_emit(env, {"schema_version": SCHEMA, "status": "saved", "schedule_id": sid, "changed": changed,
|
|
967
|
+
"echo": echo.to_doc(), "warnings": verdict.warnings})
|
|
968
|
+
else:
|
|
969
|
+
env.out.write(echo.text() + f"saved {sid} (changed {', '.join(changed)})\n")
|
|
970
|
+
return 0
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def _set_state(env: Any, entry: dict[str, Any], state: str, now: datetime) -> None:
|
|
974
|
+
entry = dict(entry, state=state)
|
|
975
|
+
first = next_slots(When.from_doc(entry["when"]), floor_minute(now), 1) if state == "active" else []
|
|
976
|
+
entry["next_slot"] = _stamp(first[0].utc) if first else None
|
|
977
|
+
store.write_entry(entry)
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def _done(env: Any, a: argparse.Namespace, sid: str, **fields: Any) -> int:
|
|
981
|
+
if a.json:
|
|
982
|
+
_emit(env, {"schema_version": SCHEMA, "status": "ok", "schedule_id": sid, **fields})
|
|
983
|
+
else:
|
|
984
|
+
env.out.write(f"{sid}: " + ", ".join(f"{k} {v}" for k, v in fields.items()) + "\n")
|
|
985
|
+
return 0
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def cmd_pause(env: Any, a: argparse.Namespace) -> int:
|
|
989
|
+
entry = _select(a.id)
|
|
990
|
+
sid = str(entry["schedule_id"])
|
|
991
|
+
if entry["state"] == "paused":
|
|
992
|
+
return _done(env, a, sid, state="paused", changed=False)
|
|
993
|
+
if entry["state"] != "active":
|
|
994
|
+
raise ScheduleError("schedule_state", f"{sid} is {entry['state']}; only an active schedule is paused")
|
|
995
|
+
caller, now = _known_caller(env, a), _now()
|
|
996
|
+
_set_state(env, entry, "paused", now)
|
|
997
|
+
extra: dict[str, Any] = {"note": scrub(a.reason)[:200]} if a.reason else {}
|
|
998
|
+
store.append_event(sid, "paused", now=now, caller=caller, reason="person", err=env.err, **extra)
|
|
999
|
+
return _done(env, a, sid, state="paused", changed=True)
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def cmd_resume(env: Any, a: argparse.Namespace) -> int:
|
|
1003
|
+
entry = _select(a.id)
|
|
1004
|
+
sid = str(entry["schedule_id"])
|
|
1005
|
+
if entry["state"] == "active":
|
|
1006
|
+
return _done(env, a, sid, state="active", changed=False)
|
|
1007
|
+
if entry["state"] != "paused":
|
|
1008
|
+
raise ScheduleError("schedule_state", f"{sid} is {entry['state']}; only a paused schedule resumes")
|
|
1009
|
+
now = _now()
|
|
1010
|
+
caller = _person(env, a, now) # TCK-B22
|
|
1011
|
+
log = store.read_log(sid)
|
|
1012
|
+
events = policies.resume_events(entry, log, now, catch_up=bool(a.catch_up))
|
|
1013
|
+
_set_state(env, entry, "active", now)
|
|
1014
|
+
for e in events:
|
|
1015
|
+
extra: dict[str, Any] = {k: v for k, v in e.items() if k not in ("kind", "slot", "fire_id")}
|
|
1016
|
+
if e["kind"] == "resumed":
|
|
1017
|
+
extra["caller"] = caller
|
|
1018
|
+
store.append_event(sid, e["kind"], now=now, slot=e["slot"], fire_id=e["fire_id"], err=env.err, **extra)
|
|
1019
|
+
return _done(env, a, sid, state="active", missed=sum(1 for e in events if e["kind"] == "missed"),
|
|
1020
|
+
catch_up=bool(a.catch_up))
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
def cmd_skip(env: Any, a: argparse.Namespace) -> int:
|
|
1024
|
+
entry = _select(a.id)
|
|
1025
|
+
sid = str(entry["schedule_id"])
|
|
1026
|
+
if entry["state"] not in ("active", "paused"):
|
|
1027
|
+
raise ScheduleError("schedule_state", f"{sid} is {entry['state']}; nothing to skip")
|
|
1028
|
+
if a.next_ and a.until:
|
|
1029
|
+
raise ScheduleError("when_malformed", "--next and --until are alternatives")
|
|
1030
|
+
caller, now = _known_caller(env, a), _now()
|
|
1031
|
+
when = When.from_doc(entry["when"])
|
|
1032
|
+
handled = policies.handled_slots(store.read_log(sid))
|
|
1033
|
+
start = floor_minute(now)
|
|
1034
|
+
if a.until:
|
|
1035
|
+
try:
|
|
1036
|
+
day = date.fromisoformat(a.until)
|
|
1037
|
+
except ValueError:
|
|
1038
|
+
raise ScheduleError("when_malformed", f"--until {a.until!r}: an ISO date such as 2026-12-01 is needed") from None
|
|
1039
|
+
stop = wall_to_utc(datetime.combine(day, time(0)), zone_of(when.zone)) - timedelta(minutes=1)
|
|
1040
|
+
slots = [s.utc for s in slots_between(when, start, stop)]
|
|
1041
|
+
else:
|
|
1042
|
+
slots = [s.utc for s in next_slots(when, start, 8) if _stamp(s.utc) not in handled][:1]
|
|
1043
|
+
slots = [s for s in slots if _stamp(s) not in handled]
|
|
1044
|
+
if not slots:
|
|
1045
|
+
raise ScheduleError("no_slot", "there is no slot to skip")
|
|
1046
|
+
for s in slots:
|
|
1047
|
+
store.append_event(sid, "skipped", now=now, slot=_stamp(s), fire_id=policies.fire_id(sid, s), reason="person",
|
|
1048
|
+
caller=caller, err=env.err)
|
|
1049
|
+
return _done(env, a, sid, skipped=[_stamp(s) for s in slots])
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
def cmd_remove(env: Any, a: argparse.Namespace) -> int:
|
|
1053
|
+
entry = _select(a.id)
|
|
1054
|
+
sid = str(entry["schedule_id"])
|
|
1055
|
+
if entry["state"] == "removed":
|
|
1056
|
+
raise ScheduleError("schedule_state", f"{sid} is already removed")
|
|
1057
|
+
caller, now = env.caller(a), _now()
|
|
1058
|
+
_confirm(env, a, build_echo(When.from_doc(entry["when"]), [], now), f"Remove {sid}? Its history stays.")
|
|
1059
|
+
caller = _known_caller(env, a) if caller.get("kind") == "unknown" else caller # TCK-B22: anyone but `unknown`
|
|
1060
|
+
_set_state(env, entry, "removed", now)
|
|
1061
|
+
store.append_event(sid, "removed", now=now, caller=caller, err=env.err)
|
|
1062
|
+
return _done(env, a, sid, state="removed")
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
# --- dispatch ----------------------------------------------------------------------------------------------------
|
|
1066
|
+
|
|
1067
|
+
HANDLERS = {"parse": cmd_parse, "add": cmd_add, "list": cmd_list, "show": cmd_show, "history": cmd_history,
|
|
1068
|
+
"edit": cmd_edit, "pause": cmd_pause, "resume": cmd_resume, "skip": cmd_skip, "remove": cmd_remove,
|
|
1069
|
+
"runs": cmd_runs, "tick": cmd_tick, "fire": cmd_fire, "loop": cmd_loop,
|
|
1070
|
+
"trigger": cmd_trigger, "export": cmd_export}
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def cmd_schedule(env: Any, a: argparse.Namespace) -> int:
|
|
1074
|
+
from tempergraph.cli.main import UsageError
|
|
1075
|
+
|
|
1076
|
+
if a.action is None:
|
|
1077
|
+
raise UsageError("schedule needs a verb: parse, add, list, show, history, edit, pause, resume, skip, remove, fire, "
|
|
1078
|
+
"runs, tick, loop, trigger, export")
|
|
1079
|
+
try:
|
|
1080
|
+
return HANDLERS[a.action](env, a)
|
|
1081
|
+
except ScheduleError as exc:
|
|
1082
|
+
return _refuse(env, a, exc)
|
|
1083
|
+
except Needs as ask:
|
|
1084
|
+
return _needs(env, ask)
|
|
1085
|
+
except _Stop as stop:
|
|
1086
|
+
_emit(env, stop.doc)
|
|
1087
|
+
return stop.code
|
|
1088
|
+
|
|
1089
|
+
|
|
1090
|
+
COMMANDS = {"schedule": cmd_schedule}
|