diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 8f10d48932..f09af0d026 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -283,6 +283,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `repo-archive-backup.timer` | `OnCalendar=*-*-* 05:15:00` | `repo-archive-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `repo-universe-issue-check.timer` | `OnCalendar=*-*-* 00:00:00` | `repo-universe-issue-check.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `queue-coverage-reconcile.timer` (repo-shipped, not yet installed) | `OnCalendar=*-*-* *:41:00` | `queue-coverage-reconcile.service` | laptop (user systemd; code#7016) | not recorded | not recorded | 2026-11-08 | 2026-11-08 | +| `scheduled-history.timer` | `OnCalendar=*-*-* *:0/5:00` | `scheduled-history.service` | laptop (user systemd; code#2174) | not recorded | not recorded | 2026-11-11 | 2026-11-14 | | `supabase-backup.timer` | `OnCalendar=*-*-* 04:42:00,OnCalendar=*-*-* 16:42:00` | `supabase-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `supabase-turso-coord-mirror.timer` | `OnCalendar=*-*-* 04:24:00` | `supabase-turso-coord-mirror.service` | laptop (user systemd) | not recorded | not recorded | 2026-11-11 | 2026-11-11 | | `sync-models.timer` | `OnCalendar=*-*-* 00:00:00` | `sync-models.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | diff --git a/pm-stack/scheduled-history/README.md b/pm-stack/scheduled-history/README.md new file mode 100644 index 0000000000..b17cb8dbe2 --- /dev/null +++ b/pm-stack/scheduled-history/README.md @@ -0,0 +1,77 @@ +# scheduled-history — per-run history for OpenChamber scheduled tasks (#2174 Gap 1) + +The first evidence gap from issue #2174: OpenChamber's live +scheduled-task records retain only latest-run fields, and no consumer +persisted run events anywhere durable, so no per-run +outcome/token/elapsed dataset existed for the Muse↔OpenChamber +go/no-go comparison. This is that consumer. + +## Design — polling reconciler, not an event consumer + +Recon on #2174 (task 12585) found the scheduled-task-ran events are +ephemeral, emitter errors are swallowed, and the events that exist +report enqueue/send rather than assistant completion — an SSE-only +collector cannot guarantee a durable terminal record. Instead, each +tick polls the authoritative surface, +`openchamber schedule list --json --dir `, and reconciles: + +- Runs are keyed `@`. Exactly one durable + row per run, ever. +- A row's outcome follows the record until the status is terminal + (`success`, `error`, `failed`, `cancelled`, `timeout`, + `disabled`, `skipped`, …), then the row is frozen. +- When a newer run of the same task appears, an older non-terminal + row is finalized as-is with `finalized_by: superseded` — the + record no longer describes it, so it can never change again. +- `duration_ms` is the scheduler-reported figure, recorded as + reported; session wall-clock is carried separately + (`session_created_at`/`session_updated_at`). +- Token/cost enrichment comes from the OpenCode session store + (`session_v2` in `~/.local/share/opencode/opencode.db` — the + #2072 source), keyed by the run's `lastSessionId`. When the + session row is absent, `tokens` stays null: absence is recorded, + never invented. Enrichment is refreshed on every poll while the + session row exists — the outcome freezes at terminal, but a + session can keep accumulating tokens after its run is first seen, + so usage fields follow the session store rather than freezing at + first sight. + +## Store + +`~/.local/state/openchamber-scheduled-history/history.json` — one +JSON document (`{"schema": "scheduled-history/v1", "rows": {...}}`) +written atomically (tmp + rename). Fields per row: run_key, task_id, +task_name, project_dir, enabled, scheduled_for, started_at, +finished_at, duration_ms, session_id, outcome, outcome_terminal, +finalized_by, cost, tokens {input, output, reasoning, cache_read, +cache_write}, session_created_at, session_updated_at, token_source, +first_seen_at, last_seen_at. + +## Read path (the comparison / Gap 3 watchdog input) + +``` +collect.py list [--task ] [--since ] [--until ] [--json] +``` + +## Run it + +``` +python3 collect.py collect --dir ~/git/code [--dir ...] +python3 test_collect.py # 13 checks +``` + +Deployment on the laptop: `scheduled-history.service` + +`scheduled-history.timer` (user units, 5-minute tick, mirroring +opencode-usage-export). Installing this collector changes NO existing +Muse cron job, OpenChamber scheduled task, cadence, or lane count — +it only reads scheduled-task records (#2174 acceptance constraint). + +## Known limits + +- History begins at installation; runs from before the first tick + appear only as each task's then-latest run (one row per task at + backfill). +- `lastStatus` is the scheduler's own outcome for the run; where a + run's session outlives the scheduler's status transition, the + session timestamps and token totals in the row are the deeper + evidence (that layering is deliberate — see #2174 Gap 3). diff --git a/pm-stack/scheduled-history/collect.py b/pm-stack/scheduled-history/collect.py new file mode 100644 index 0000000000..859fb23caf --- /dev/null +++ b/pm-stack/scheduled-history/collect.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +"""collect.py — per-run history for OpenChamber scheduled tasks (#2174 Gap 1). + +Design: a POLLING RECONCILER, not an event consumer. OpenChamber's +scheduled-task-ran events are ephemeral and emitter errors are +swallowed, and the events that do exist report enqueue/send rather +than assistant completion — an SSE-only collector cannot guarantee a +durable terminal record (recon on issue #2174, task 12585). The +authoritative surface is the scheduled-task record itself +(`openchamber schedule list --json`), which retains the latest run's +fields. Polling it on a short tick and keying runs by +(task id, lastScheduledFor) yields exactly one durable row per run: + +- a run key first seen is inserted with its observed status; +- while a newer run has not appeared, the row's outcome follows the + record until the status is terminal, then the row is frozen; +- when a newer run for the same task appears, any older non-terminal + row is finalized with its last observed status + (finalized_by=superseded) — it can never update again, because the + record no longer describes it; +- token/cost fields are enriched from the OpenCode session store + (session_v2 in the opencode.db the #2072 exporter reads), keyed by + the run's session id, whenever that row exists; otherwise they + stay null — absence is recorded, never invented. Enrichment is + refreshed on every poll, independently of the outcome freeze: a + session can keep accumulating tokens after its run is first seen + (and after the scheduler marks the run terminal), so first-sight + values must not freeze the usage fields. + +The store is one JSON document (rows keyed by run key) written +atomically (tmp file + os.replace). At fleet scale (tens of tasks, +tens of runs per day) this is far below any size where a database +earns its keep; the row shape is the contract, not the container. + +Read path: `collect.py list [--task ID] [--since ISO] [--until ISO] +[--json]` — the input the #2174 comparison and the Gap 3 watchdog +check consume. + +This tool changes NO existing schedule: it only reads the +scheduled-task records. Installing its own timer is the deployment +step recorded in README.md. +""" + +import argparse, json, os, sqlite3, subprocess, sys, tempfile +from datetime import datetime, timezone + +TERMINAL_STATUSES = { + "success", "error", "failed", "failure", "cancelled", + "canceled", "timeout", "timed_out", "disabled", "skipped", +} + +DEFAULT_STORE = os.path.join( + os.path.expanduser("~/.local/state/openchamber-scheduled-history"), + "history.json", +) +DEFAULT_DB = os.path.expanduser("~/.local/share/opencode/opencode.db") + + +def iso(ms): + if ms is None: + return None + return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).isoformat() + + +def now_iso(clock=None): + t = clock() if clock else datetime.now(timezone.utc) + return t.isoformat() + + +def fetch_tasks(project_dir, runner=subprocess.run): + out = runner( + ["openchamber", "schedule", "list", "--json", "--dir", project_dir], + capture_output=True, text=True, timeout=120, + ) + if out.returncode != 0: + raise RuntimeError(f"openchamber schedule list failed for {project_dir}: {out.stderr.strip()[:200]}") + doc = json.loads(out.stdout) + if doc.get("status") != "ok": + raise RuntimeError(f"openchamber schedule list error for {project_dir}: {doc.get('error')}") + return doc.get("tasks", []) + + +def session_lookup(db_path, session_id): + """Token/cost totals for one session from session_v2, or None.""" + if not session_id or not db_path or not os.path.exists(db_path): + return None + try: + con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) + try: + row = con.execute( + "SELECT cost, tokens_input, tokens_output, tokens_reasoning," + " tokens_cache_read, tokens_cache_write, time_created, time_updated" + " FROM session_v2 WHERE id = ?", (session_id,), + ).fetchone() + finally: + con.close() + except sqlite3.Error: + return None + if row is None: + return None + cost, ti, to, tr, tcr, tcw, created, updated = row + return { + "cost": cost, + "tokens": { + "input": ti, "output": to, "reasoning": tr, + "cache_read": tcr, "cache_write": tcw, + }, + "session_created_at": iso(created), + "session_updated_at": iso(updated), + "token_source": "opencode session_v2", + } + + +def reconcile(rows, tasks, project_dir, clock=None, lookup=None): + """Fold one poll of one project's tasks into the row store. + + rows: {run_key: row} mutated in place. Returns (inserted, updated, + finalized) counts. lookup(session_id) -> enrichment dict or None. + """ + seen_at = now_iso(clock) + inserted = updated = finalized = 0 + latest_key_by_task = {} + for task in tasks: + state = task.get("state") or {} + run_at = state.get("lastRunAt") + scheduled_for = state.get("lastScheduledFor") or run_at + if run_at is None and scheduled_for is None: + continue # never ran — no run, no row + run_key = f"{task.get('id')}@{scheduled_for}" + latest_key_by_task[task.get("id")] = run_key + status = (state.get("lastStatus") or "unknown").lower() + terminal = status in TERMINAL_STATUSES + row = rows.get(run_key) + if row is None: + row = { + "run_key": run_key, + "task_id": task.get("id"), + "task_name": task.get("name"), + "project_dir": project_dir, + "enabled": task.get("enabled"), + "scheduled_for": iso(scheduled_for), + "started_at": iso(run_at), + "finished_at": None, + "duration_ms": state.get("lastDurationMs"), + "session_id": state.get("lastSessionId"), + "outcome": status, + "outcome_terminal": terminal, + "finalized_by": "terminal-status" if terminal else None, + "cost": None, + "tokens": None, + "session_created_at": None, + "session_updated_at": None, + "token_source": None, + "first_seen_at": seen_at, + "last_seen_at": seen_at, + } + rows[run_key] = row + inserted += 1 + elif not row.get("outcome_terminal"): + row["outcome"] = status + row["outcome_terminal"] = terminal + row["duration_ms"] = state.get("lastDurationMs") + row["session_id"] = state.get("lastSessionId") or row.get("session_id") + row["last_seen_at"] = seen_at + if terminal: + row["finalized_by"] = "terminal-status" + updated += 1 + if row.get("outcome_terminal") and row.get("finished_at") is None: + if row.get("started_at") and row.get("duration_ms") is not None: + start = datetime.fromisoformat(row["started_at"]) + row["finished_at"] = datetime.fromtimestamp( + start.timestamp() + row["duration_ms"] / 1000, tz=timezone.utc + ).isoformat() + # Enrichment refreshes on every poll (Codex P1 on PR #8437): + # a still-running session keeps accumulating tokens after the + # first poll, so gating on tokens-is-None would freeze partial + # usage forever. The outcome fields freeze at terminal; the + # usage fields follow the session store while it has the row. + if lookup is not None and row.get("session_id"): + got = lookup(row["session_id"]) + if got: + row.update(got) + # Finalize non-terminal rows superseded by a newer run of the task. + for key, row in rows.items(): + if row.get("outcome_terminal") or row.get("project_dir") != project_dir: + continue + latest = latest_key_by_task.get(row.get("task_id")) + if latest is not None and latest != key: + row["outcome_terminal"] = True + row["finalized_by"] = "superseded" + row["last_seen_at"] = seen_at + finalized += 1 + return inserted, updated, finalized + + +def load_store(path): + if os.path.exists(path): + with open(path) as f: + doc = json.load(f) + return doc.get("rows", {}) + return {} + + +def save_store(path, rows): + # Resolve the parent absolutely (Codex P2 on PR #8437): a bare + # relative filename has dirname "" and makedirs("") raises. + store_dir = os.path.dirname(os.path.abspath(path)) + os.makedirs(store_dir, exist_ok=True) + doc = {"schema": "scheduled-history/v1", "rows": rows} + fd, tmp = tempfile.mkstemp(dir=store_dir, suffix=".tmp") + try: + with os.fdopen(fd, "w") as f: + json.dump(doc, f, indent=1, sort_keys=True) + os.replace(tmp, path) + except BaseException: + if os.path.exists(tmp): + os.unlink(tmp) + raise + + +def cmd_collect(args): + rows = load_store(args.store) + totals = [0, 0, 0] + for project_dir in args.dir: + tasks = fetch_tasks(project_dir) + counts = reconcile( + rows, tasks, project_dir, + lookup=lambda sid: session_lookup(args.opencode_db, sid), + ) + totals = [a + b for a, b in zip(totals, counts)] + save_store(args.store, rows) + print(json.dumps({ + "rows_total": len(rows), "inserted": totals[0], + "updated": totals[1], "finalized_superseded": totals[2], + "store": args.store, + })) + return 0 + + +def parse_instant(text): + """Parse an ISO-8601 timestamp to an aware UTC datetime, or None. + + Accepts a trailing Z and non-UTC offsets (Codex P2 on PR #8437: + string comparison would compare representations, not instants, + because stored timestamps always carry +00:00). Naive values are + read as UTC. + """ + if not text: + return None + try: + dt = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc) + + +def cmd_list(args): + rows = load_store(args.store) + since_dt = parse_instant(args.since) if args.since else None + until_dt = parse_instant(args.until) if args.until else None + if args.since and since_dt is None: + print(f"error: --since is not an ISO-8601 timestamp: {args.since}", file=sys.stderr) + return 2 + if args.until and until_dt is None: + print(f"error: --until is not an ISO-8601 timestamp: {args.until}", file=sys.stderr) + return 2 + out = [] + for row in rows.values(): + if args.task and row.get("task_id") != args.task: + continue + started_dt = parse_instant(row.get("started_at")) + if since_dt is not None and (started_dt is None or started_dt < since_dt): + continue + if until_dt is not None and (started_dt is None or started_dt > until_dt): + continue + out.append(row) + out.sort(key=lambda r: r.get("started_at") or "") + if args.json: + print(json.dumps(out, indent=1)) + else: + for r in out: + tok = r.get("tokens") or {} + print( + f"{r.get('started_at')} {r.get('task_name')} outcome={r.get('outcome')}" + f" terminal={r.get('outcome_terminal')} session={r.get('session_id')}" + f" tokens_in={tok.get('input')} tokens_out={tok.get('output')}" + ) + print(f"{len(out)} run(s)") + return 0 + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--store", default=DEFAULT_STORE) + sub = ap.add_subparsers(dest="cmd", required=True) + c = sub.add_parser("collect", help="one polling tick over the given projects") + c.add_argument("--dir", action="append", required=True, + help="project directory (repeatable)") + c.add_argument("--opencode-db", default=DEFAULT_DB) + c.set_defaults(fn=cmd_collect) + l = sub.add_parser("list", help="query stored runs") + l.add_argument("--task", help="scheduled task id") + l.add_argument("--since", help="ISO timestamp, inclusive lower bound on started_at") + l.add_argument("--until", help="ISO timestamp, inclusive upper bound on started_at") + l.add_argument("--json", action="store_true") + l.set_defaults(fn=cmd_list) + args = ap.parse_args(argv) + return args.fn(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pm-stack/scheduled-history/scheduled-history.service b/pm-stack/scheduled-history/scheduled-history.service new file mode 100644 index 0000000000..2e7862299e --- /dev/null +++ b/pm-stack/scheduled-history/scheduled-history.service @@ -0,0 +1,8 @@ +[Unit] +Description=OpenChamber scheduled-task per-run history collector — code#2174 Gap 1 +After=network-online.target + +[Service] +Type=oneshot +TimeoutStartSec=180 +ExecStart=/usr/bin/env python3 %h/git/code/pm-stack/scheduled-history/collect.py collect --dir %h/git/code diff --git a/pm-stack/scheduled-history/scheduled-history.timer b/pm-stack/scheduled-history/scheduled-history.timer new file mode 100644 index 0000000000..1b8203fcce --- /dev/null +++ b/pm-stack/scheduled-history/scheduled-history.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Run the scheduled-task history collector every 5 minutes — code#2174 Gap 1 + +[Timer] +OnCalendar=*:0/5 +RandomizedDelaySec=20 +Persistent=true +Unit=scheduled-history.service + +[Install] +WantedBy=timers.target diff --git a/pm-stack/scheduled-history/test_collect.py b/pm-stack/scheduled-history/test_collect.py new file mode 100644 index 0000000000..972b4a818d --- /dev/null +++ b/pm-stack/scheduled-history/test_collect.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""test_collect.py — reconcile/list tests for the scheduled-history +collector (#2174 Gap 1). Oracle: the acceptance criteria — exactly +one durable row per run, terminal outcome recorded, superseded runs +finalized, token enrichment only from the session store. + +Run: python3 pm-stack/scheduled-history/test_collect.py +""" + +import json, os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import collect + +PASS = [] +def check(name, cond): + PASS.append((name, bool(cond))) + print(("PASS " if cond else "FAIL ") + name) + assert cond, name + +T0 = 1794362400000 # a scheduled tick, ms epoch + +def task(status="success", run_at=T0, sched=T0, session="ses_1", dur=5000, tid="task-1"): + return { + "id": tid, "name": "Lane", "enabled": True, + "state": {"lastStatus": status, "lastRunAt": run_at, + "lastScheduledFor": sched, "lastSessionId": session, + "lastDurationMs": dur}, + } + +# 1. first poll inserts exactly one row with the terminal outcome +rows = {} +ins, upd, fin = collect.reconcile(rows, [task()], "/proj") +check("insert: one row", len(rows) == 1 and ins == 1) +row = rows["task-1@%d" % T0] +check("insert: outcome success + terminal", row["outcome"] == "success" and row["outcome_terminal"]) +check("insert: finished_at = start + duration", row["finished_at"] is not None) +check("insert: session id carried", row["session_id"] == "ses_1") + +# 2. re-polling the same run inserts nothing and changes nothing +ins, upd, fin = collect.reconcile(rows, [task()], "/proj") +check("repoll: no duplicate", len(rows) == 1 and ins == 0) + +# 3. a running run updates in place to its terminal status +rows = {} +collect.reconcile(rows, [task(status="running")], "/proj") +check("running: not terminal", not rows["task-1@%d" % T0]["outcome_terminal"]) +collect.reconcile(rows, [task(status="error")], "/proj") +r = rows["task-1@%d" % T0] +check("running->error: same row, terminal", len(rows) == 1 and r["outcome"] == "error" and r["outcome_terminal"]) + +# 4. a newer run supersedes: the older non-terminal row is finalized +rows = {} +collect.reconcile(rows, [task(status="running")], "/proj") +collect.reconcile(rows, [task(status="running", run_at=T0 + 2400000, sched=T0 + 2400000, session="ses_2")], "/proj") +old = rows["task-1@%d" % T0] +check("supersede: old row finalized", old["outcome_terminal"] and old["finalized_by"] == "superseded") +check("supersede: two rows total", len(rows) == 2) + +# 5. token enrichment comes from the lookup, only when it has the session +rows = {} +lookup = lambda sid: {"cost": 0.5, "tokens": {"input": 10, "output": 3, "reasoning": 0, "cache_read": 0, "cache_write": 0}, "session_created_at": None, "session_updated_at": None, "token_source": "opencode session_v2"} if sid == "ses_1" else None +collect.reconcile(rows, [task()], "/proj", lookup=lookup) +check("tokens: enriched when session found", rows["task-1@%d" % T0]["tokens"]["input"] == 10) +rows = {} +collect.reconcile(rows, [task(session="ses_missing")], "/proj", lookup=lookup) +check("tokens: null when session absent (recorded, not invented)", rows["task-1@%d" % T0]["tokens"] is None) + +# 6. a task that never ran produces no row +rows = {} +t = task(); t["state"] = {} +collect.reconcile(rows, [t], "/proj") +check("never-ran: no row", rows == {}) + +# 7. store round-trips through save/load (atomic JSON document) +import tempfile +p = os.path.join(tempfile.mkdtemp(), "history.json") +rows = {} +collect.reconcile(rows, [task()], "/proj") +collect.save_store(p, rows) +check("store: round-trip", collect.load_store(p) == rows) + +# 8. enrichment refreshes on later polls (Codex P1 on PR #8437): a +# session still accumulating tokens must not freeze at first sight, +# even after the run's outcome is terminal +rows = {} +vals = {"input": 10} +lookup = lambda sid: {"cost": 0.5, "tokens": {"input": vals["input"], "output": 3, "reasoning": 0, "cache_read": 0, "cache_write": 0}, "session_created_at": None, "session_updated_at": None, "token_source": "opencode session_v2"} +collect.reconcile(rows, [task()], "/proj", lookup=lookup) +check("refresh: first poll enriches", rows["task-1@%d" % T0]["tokens"]["input"] == 10) +vals["input"] = 25 +collect.reconcile(rows, [task()], "/proj", lookup=lookup) +check("refresh: later poll updates tokens on a terminal row", rows["task-1@%d" % T0]["tokens"]["input"] == 25) + +# 9. a bare relative store filename saves (Codex P2 on PR #8437) +import tempfile +cwd = os.getcwd() +os.chdir(tempfile.mkdtemp()) +try: + rows = {} + collect.reconcile(rows, [task()], "/proj") + collect.save_store("history.json", rows) + check("store: bare relative filename round-trips", collect.load_store("history.json") == rows) +finally: + os.chdir(cwd) + +# 10. list window compares instants, not strings (Codex P2 on PR #8437): +# a bound at 13:00+01:00 is 12:00 UTC, so a 12:30 UTC run is inside +# --since 13:00+01:00 but outside --until 13:00+01:00 +import argparse, contextlib, io +sp = os.path.join(tempfile.mkdtemp(), "history.json") +srows = {"k": {"run_key": "k", "task_id": "task-1", "task_name": "Lane", + "started_at": "2026-11-11T12:30:00+00:00", "outcome": "success", + "outcome_terminal": True, "session_id": "ses_1", "tokens": None}} +collect.save_store(sp, srows) +def run_list(**kw): + a = argparse.Namespace(store=sp, task=None, since=None, until=None, json=True) + for k, v in kw.items(): + setattr(a, k, v) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rc = collect.cmd_list(a) + return rc, json.loads(buf.getvalue()) +rc, out = run_list(since="2026-11-11T13:00:00+01:00") +check("window: offset --since compares instants (included)", rc == 0 and len(out) == 1) +rc, out = run_list(until="2026-11-11T13:00:00+01:00") +check("window: offset --until compares instants (excluded)", rc == 0 and len(out) == 0) +rc, out = run_list(since="2026-11-11T12:00:00Z") +check("window: Z --since parses (included)", rc == 0 and len(out) == 1) + +print(f"\n{sum(1 for _, ok in PASS if ok)}/{len(PASS)} checks passed")