|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +One-shot backfill of ``task_names`` from ``marcus.db::task_metadata``. |
| 4 | +
|
| 5 | +Marcus's `marcus.db` (collection ``task_metadata`` inside the |
| 6 | +key-value ``persistence`` table) is the source of truth for task |
| 7 | +names. The cost-tracking dashboard reads from `costs.db::task_names`. |
| 8 | +After Marcus #530 added the snapshot path, new tasks land in both |
| 9 | +DBs at creation time. Historical tasks created before #530 only |
| 10 | +exist in `marcus.db`; the dashboard renders their opaque hex IDs. |
| 11 | +
|
| 12 | +This script reads every row in the ``task_metadata`` collection, |
| 13 | +extracts ``(task_id, name)``, and calls |
| 14 | +:meth:`CostStore.record_task_name` for each. The store's UPSERT |
| 15 | +makes the operation idempotent — re-running is safe and a no-op |
| 16 | +when nothing has changed. |
| 17 | +
|
| 18 | +Usage |
| 19 | +----- |
| 20 | +.. code-block:: console |
| 21 | +
|
| 22 | + $ python scripts/backfill_task_names.py |
| 23 | + Backfilled 287 task names from /Users/.../data/marcus.db |
| 24 | + Skipped 5 rows (malformed JSON or missing name) |
| 25 | +
|
| 26 | +Pass ``--marcus-db PATH`` to point at a non-default Marcus DB. |
| 27 | +Pass ``--costs-db PATH`` to override the cost-store path (defaults |
| 28 | +to ``~/.marcus/costs.db``). |
| 29 | +""" |
| 30 | + |
| 31 | +from __future__ import annotations |
| 32 | + |
| 33 | +import argparse |
| 34 | +import json |
| 35 | +import sys |
| 36 | +from pathlib import Path |
| 37 | +from typing import Tuple |
| 38 | + |
| 39 | +# Allow running directly from the repo root without installing. |
| 40 | +_REPO_ROOT = Path(__file__).resolve().parent.parent |
| 41 | +sys.path.insert(0, str(_REPO_ROOT)) |
| 42 | + |
| 43 | +from src.cost_tracking.cost_store import CostStore # noqa: E402 |
| 44 | + |
| 45 | + |
| 46 | +def _parse_args() -> argparse.Namespace: |
| 47 | + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 48 | + parser.add_argument( |
| 49 | + "--marcus-db", |
| 50 | + type=Path, |
| 51 | + default=_REPO_ROOT / "data" / "marcus.db", |
| 52 | + help="Path to Marcus's marcus.db (default: ./data/marcus.db).", |
| 53 | + ) |
| 54 | + parser.add_argument( |
| 55 | + "--costs-db", |
| 56 | + type=Path, |
| 57 | + default=Path.home() / ".marcus" / "costs.db", |
| 58 | + help="Path to costs.db (default: ~/.marcus/costs.db).", |
| 59 | + ) |
| 60 | + return parser.parse_args() |
| 61 | + |
| 62 | + |
| 63 | +def backfill(marcus_db: Path, costs_db: Path) -> Tuple[int, int, int]: |
| 64 | + """Copy ``(task_id, name)`` from ``marcus.db`` into ``costs.db``. |
| 65 | +
|
| 66 | + Two passes: |
| 67 | +
|
| 68 | + 1. **Parent tasks.** Read every row in ``marcus.db::task_metadata`` |
| 69 | + and snapshot its ``(task_id, name)`` into ``task_names``. |
| 70 | + 2. **Subtasks.** Marcus decomposes some tasks into subtasks with |
| 71 | + IDs like ``<parent_hex>_sub_1`` / ``_sub_2``. Those IDs land in |
| 72 | + ``token_events.task_id`` but never appear in ``task_metadata`` |
| 73 | + (only parents do). Walk every distinct ``_sub_N`` ID in |
| 74 | + ``token_events``, look up the parent's snapshotted name, and |
| 75 | + write a derived label (``"<parent name> — subtask N"``) so the |
| 76 | + dashboard surfaces something readable instead of a hex tail. |
| 77 | +
|
| 78 | + Returns |
| 79 | + ------- |
| 80 | + (parents, subtasks, skipped) : tuple of int |
| 81 | + Counts for parent-task names recorded, subtask-derived names |
| 82 | + recorded, and rows skipped (malformed JSON, missing name). |
| 83 | + """ |
| 84 | + import sqlite3 |
| 85 | + |
| 86 | + if not marcus_db.exists(): |
| 87 | + raise FileNotFoundError(f"marcus.db not found at {marcus_db}") |
| 88 | + |
| 89 | + store = CostStore(db_path=costs_db) |
| 90 | + |
| 91 | + src = sqlite3.connect(str(marcus_db)) |
| 92 | + rows = src.execute( |
| 93 | + "SELECT key, data FROM persistence WHERE collection = 'task_metadata'" |
| 94 | + ).fetchall() |
| 95 | + src.close() |
| 96 | + |
| 97 | + # Pass 1: parent-task names from marcus.db. |
| 98 | + parents = 0 |
| 99 | + skipped = 0 |
| 100 | + for key, raw in rows: |
| 101 | + try: |
| 102 | + parsed = json.loads(raw) if isinstance(raw, str) else raw |
| 103 | + except (json.JSONDecodeError, ValueError, TypeError): |
| 104 | + skipped += 1 |
| 105 | + continue |
| 106 | + |
| 107 | + if not isinstance(parsed, dict): |
| 108 | + skipped += 1 |
| 109 | + continue |
| 110 | + |
| 111 | + task_id = parsed.get("task_id") or key |
| 112 | + name = parsed.get("name") |
| 113 | + if not isinstance(task_id, str) or not isinstance(name, str) or not name: |
| 114 | + skipped += 1 |
| 115 | + continue |
| 116 | + |
| 117 | + store.record_task_name(task_id, name) |
| 118 | + parents += 1 |
| 119 | + |
| 120 | + # Pass 2: subtask derived names. Look for ``_sub_N`` task_ids that |
| 121 | + # appear in token_events but have no entry in task_names yet, and |
| 122 | + # synthesize a label from the parent's snapshotted name. |
| 123 | + subtasks = 0 |
| 124 | + sub_rows = store.conn.execute(""" |
| 125 | + SELECT DISTINCT te.task_id |
| 126 | + FROM token_events te |
| 127 | + LEFT JOIN task_names tn USING (task_id) |
| 128 | + WHERE te.task_id IS NOT NULL |
| 129 | + AND tn.task_id IS NULL |
| 130 | + AND instr(te.task_id, '_sub_') > 0 |
| 131 | + """).fetchall() |
| 132 | + for (sub_id,) in sub_rows: |
| 133 | + suffix_at = sub_id.find("_sub_") |
| 134 | + parent_id = sub_id[:suffix_at] |
| 135 | + suffix = sub_id[suffix_at + len("_sub_") :] |
| 136 | + parent_name = store.get_task_name(parent_id) |
| 137 | + if not parent_name: |
| 138 | + continue |
| 139 | + store.record_task_name(sub_id, f"{parent_name} — subtask {suffix}") |
| 140 | + subtasks += 1 |
| 141 | + |
| 142 | + return parents, subtasks, skipped |
| 143 | + |
| 144 | + |
| 145 | +def main() -> int: |
| 146 | + """Parse CLI args, run the backfill, and print a short summary.""" |
| 147 | + args = _parse_args() |
| 148 | + parents, subtasks, skipped = backfill(args.marcus_db, args.costs_db) |
| 149 | + print(f"Backfilled {parents} parent task names from {args.marcus_db}") |
| 150 | + if subtasks > 0: |
| 151 | + print(f"Backfilled {subtasks} subtask names derived from parents") |
| 152 | + if skipped > 0: |
| 153 | + print(f"Skipped {skipped} rows (malformed JSON or missing name)") |
| 154 | + return 0 |
| 155 | + |
| 156 | + |
| 157 | +if __name__ == "__main__": |
| 158 | + raise SystemExit(main()) |
0 commit comments