orca-board 0.1.0__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.
orca_board/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Orca Board: a read-only live view of Orca orchestration."""
2
+
3
+ __version__ = "0.1.0"
orca_board/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """`python -m orca_board`: the same as the `orca-board` command."""
2
+
3
+ from orca_board.server import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,586 @@
1
+ """All SQL for Orca Board. SELECT-only, read-only.
2
+
3
+ This is the one module that knows Orca's schema. An Orca upgrade that renames a column means fixing
4
+ this file (and REQUIRED_COLUMNS) and nothing else.
5
+
6
+ Read-only is enforced three ways:
7
+ 1. the database is opened as ``file:///<absolute path>?mode=ro`` with ``uri=True`` (SQLite refuses writes),
8
+ 2. ``PRAGMA query_only=ON`` on every connection,
9
+ 3. every statement here is a SELECT (tests/test_board.py checks the source statically).
10
+
11
+ Timestamps: Orca stores two text formats, ``YYYY-MM-DD HH:MM:SS`` and ``YYYY-MM-DDTHH:MM:SS.sssZ``
12
+ (both UTC). Values in API objects are passed through as stored. Comparisons, cursors, ordering and
13
+ derived times (``last_activity``, history ``t``) use ``strftime('%Y-%m-%d %H:%M:%f', col)``, which
14
+ normalises both formats, so the derived values are ``YYYY-MM-DD HH:MM:SS`` (or with ``.fff``).
15
+ """
16
+
17
+ import json
18
+ import os
19
+ import sqlite3
20
+ from pathlib import Path, PurePath
21
+ from urllib.parse import quote
22
+
23
+ BODY_CAP = 4000
24
+ ACTIVE_STATES = ("starting", "ready", "stopping")
25
+
26
+ # Every column this module reads, checked against `pragma table_info` at startup and by /api/health.
27
+ REQUIRED_COLUMNS = {
28
+ "runs": ["id", "objective", "coordinator_handle", "created_at", "updated_at"],
29
+ "run_coordinator_handles": ["run_id", "terminal_handle", "first_bound_at"],
30
+ "tasks": ["id", "run_id", "parent_id", "task_title", "display_name", "spec", "status", "deps",
31
+ "result", "created_at", "completed_at"],
32
+ "dispatch_contexts": ["id", "run_id", "task_id", "status", "assignee_handle", "creator_dispatch_id",
33
+ "retry_of_dispatch_id", "depth", "dispatched_at", "completed_at", "created_at"],
34
+ "worker_dispatches": ["dispatch_id", "state", "stage", "worktree_id", "agent_terminal_handle",
35
+ "start_options", "last_error", "updated_at"],
36
+ "worker_dock_facts": ["dispatch_id", "model"],
37
+ "worker_presence": ["dispatch_id", "presence", "updated_at"],
38
+ "decision_gates": ["id", "run_id", "task_id", "question", "options", "status", "resolution",
39
+ "created_at", "resolved_at"],
40
+ "messages": ["id", "run_id", "sequence", "type", "priority", "from_handle", "to_handle", "thread_id",
41
+ "subject", "body", "created_at"],
42
+ "message_dispatch_provenance": ["message_id", "dispatch_id", "task_id"],
43
+ }
44
+
45
+
46
+ def _norm(col):
47
+ """SQL expression that normalises a timestamp column of either stored format."""
48
+ return "strftime('%Y-%m-%d %H:%M:%f', {})".format(col)
49
+
50
+
51
+ # --------------------------------------------------------------------------------------------- connect
52
+
53
+ def sqlite_uri(path):
54
+ """The read-only SQLite URI of `path`: ``file:`` plus the absolute path in POSIX form,
55
+ percent-encoded, so spaces, non-ASCII, ``?``, ``#`` and ``%`` in a path are safe.
56
+
57
+ `path` may be a string or a pathlib path; a PureWindowsPath gives the Windows form on any OS:
58
+ ``C:\\Users\\Zoë A\\x.db`` -> ``file:///C:/Users/Zo%C3%AB%20A/x.db?mode=ro``, and a UNC path
59
+ ``\\\\server\\share\\x.db`` -> ``file:////server/share/x.db?mode=ro`` (empty authority, which
60
+ SQLite accepts)."""
61
+ if isinstance(path, PurePath) and not isinstance(path, Path):
62
+ p = path # a pure path of another OS (tests); it is taken as given
63
+ else:
64
+ p = Path(os.path.expanduser(os.fspath(path))).absolute()
65
+ posix = p.as_posix()
66
+ if not posix.startswith("/"):
67
+ posix = "/" + posix # C:/x -> /C:/x
68
+ return "file://" + quote(posix, safe="/:") + "?mode=ro"
69
+
70
+
71
+ def connect(path):
72
+ """Open `path` read-only. Every caller (request, SSE client) gets its own connection."""
73
+ conn = sqlite3.connect(sqlite_uri(path), uri=True, timeout=5, check_same_thread=False)
74
+ conn.row_factory = sqlite3.Row
75
+ conn.execute("PRAGMA query_only=ON")
76
+ return conn
77
+
78
+
79
+ def missing_columns(conn):
80
+ """`table.column` names from REQUIRED_COLUMNS that the live schema lacks."""
81
+ missing = []
82
+ for table, cols in REQUIRED_COLUMNS.items():
83
+ have = {r["name"] for r in conn.execute("SELECT name FROM pragma_table_info(?)", (table,))}
84
+ if not have:
85
+ missing.append(table)
86
+ continue
87
+ missing.extend("{}.{}".format(table, c) for c in cols if c not in have)
88
+ return missing
89
+
90
+
91
+ def now(conn):
92
+ return conn.execute("SELECT strftime('%Y-%m-%d %H:%M:%S', 'now')").fetchone()[0]
93
+
94
+
95
+ # --------------------------------------------------------------------------------------------- helpers
96
+
97
+ def _json(value):
98
+ if value is None:
99
+ return None
100
+ try:
101
+ return json.loads(value)
102
+ except (TypeError, ValueError):
103
+ return value
104
+
105
+
106
+ def _secs(ts):
107
+ """'YYYY-MM-DD HH:MM:SS.fff' -> 'YYYY-MM-DD HH:MM:SS'."""
108
+ return ts[:19] if ts else ts
109
+
110
+
111
+ def _run_filter(run_id, alias):
112
+ if run_id is None:
113
+ return "", ()
114
+ return " AND {}.run_id = ?".format(alias), (run_id,)
115
+
116
+
117
+ # --------------------------------------------------------------------------------------------- runs
118
+
119
+ _RUN_SQL = """
120
+ SELECT r.id, r.objective, r.coordinator_handle, r.created_at, r.updated_at,
121
+ (SELECT json_group_array(h.terminal_handle)
122
+ FROM (SELECT terminal_handle FROM run_coordinator_handles
123
+ WHERE run_id = r.id ORDER BY first_bound_at) h) AS coordinator_handles,
124
+ (SELECT json_group_object(status, n)
125
+ FROM (SELECT status, count(*) AS n FROM tasks WHERE run_id = r.id GROUP BY status)) AS task_counts,
126
+ (SELECT count(*) FROM dispatch_contexts dc
127
+ JOIN worker_dispatches wd ON wd.dispatch_id = dc.id
128
+ WHERE dc.run_id = r.id AND wd.state IN ('starting', 'ready', 'stopping')) AS active_workers,
129
+ (SELECT count(*) FROM decision_gates g
130
+ WHERE g.run_id = r.id AND g.status = 'pending') AS pending_gates,
131
+ (SELECT max(t) FROM (
132
+ SELECT max({m}) AS t FROM messages m WHERE m.run_id = r.id
133
+ UNION ALL SELECT max({t}) FROM tasks t WHERE t.run_id = r.id
134
+ UNION ALL SELECT max({d}) FROM dispatch_contexts d WHERE d.run_id = r.id)) AS last_activity
135
+ FROM runs r
136
+ """.format(m=_norm("m.created_at"), t=_norm("t.created_at"), d=_norm("d.created_at"))
137
+
138
+
139
+ def _run(row):
140
+ return {
141
+ "id": row["id"],
142
+ "objective": row["objective"],
143
+ "coordinator_handle": row["coordinator_handle"],
144
+ "coordinator_handles": _json(row["coordinator_handles"]) or [],
145
+ "created_at": row["created_at"],
146
+ "updated_at": row["updated_at"],
147
+ "task_counts": _json(row["task_counts"]) or {},
148
+ "active_workers": row["active_workers"],
149
+ "pending_gates": row["pending_gates"],
150
+ "last_activity": _secs(row["last_activity"]),
151
+ }
152
+
153
+
154
+ def runs(conn):
155
+ """Every run, newest created_at first."""
156
+ rows = conn.execute(_RUN_SQL + " ORDER BY " + _norm("r.created_at") + " DESC, r.id DESC")
157
+ return [_run(r) for r in rows]
158
+
159
+
160
+ def run(conn, run_id):
161
+ row = conn.execute(_RUN_SQL + " WHERE r.id = ?", (run_id,)).fetchone()
162
+ return _run(row) if row else None
163
+
164
+
165
+ def active_run_id(conn):
166
+ """The run with the newest last_activity (falls back to newest created_at)."""
167
+ rows = runs(conn)
168
+ if not rows:
169
+ return None
170
+ return max(rows, key=lambda r: (r["last_activity"] or "", r["created_at"] or ""))["id"]
171
+
172
+
173
+ # --------------------------------------------------------------------------------------------- tasks
174
+
175
+ _TASK_SQL = """
176
+ SELECT t.id, t.run_id, t.parent_id, t.task_title, t.display_name, t.status, t.deps, t.spec, t.result,
177
+ t.created_at, t.completed_at,
178
+ max(coalesce({c}, ''), coalesce({k}, '')) AS change_ts
179
+ FROM tasks t
180
+ WHERE 1 = 1
181
+ """.format(c=_norm("t.created_at"), k=_norm("t.completed_at"))
182
+
183
+
184
+ def _task(row):
185
+ deps = _json(row["deps"])
186
+ return {
187
+ "id": row["id"],
188
+ "run_id": row["run_id"],
189
+ "parent_id": row["parent_id"],
190
+ "title": row["task_title"],
191
+ "display_name": row["display_name"],
192
+ "status": row["status"],
193
+ "deps": deps if deps is not None else [],
194
+ "spec": row["spec"],
195
+ "result": row["result"],
196
+ "created_at": row["created_at"],
197
+ "completed_at": row["completed_at"],
198
+ }
199
+
200
+
201
+ def tasks(conn, run_id=None, ids=None):
202
+ """Tasks of a run (or all), oldest first; `ids` limits them to those task ids."""
203
+ return [t for t, _ts in _tasks(conn, run_id, None, ids)]
204
+
205
+
206
+ def tasks_since(conn, run_id, since_ts):
207
+ """(Task, change_ts) for tasks whose created_at/completed_at is at or past since_ts."""
208
+ return _tasks(conn, run_id, since_ts, None)
209
+
210
+
211
+ def _tasks(conn, run_id, since_ts, ids):
212
+ sql, args = _TASK_SQL, []
213
+ f, a = _run_filter(run_id, "t")
214
+ sql += f
215
+ args += a
216
+ if ids is not None:
217
+ ids = list(ids)
218
+ if not ids:
219
+ return []
220
+ sql += " AND t.id IN (SELECT value FROM json_each(?))"
221
+ args.append(json.dumps(ids))
222
+ if since_ts is not None:
223
+ sql += " AND change_ts >= ?"
224
+ args.append(since_ts)
225
+ sql += " ORDER BY " + _norm("t.created_at") + ", t.rowid"
226
+ return [(_task(r), r["change_ts"]) for r in conn.execute(sql, args)]
227
+
228
+
229
+ # --------------------------------------------------------------------------------------------- dispatches
230
+
231
+ _DISPATCH_SQL = """
232
+ SELECT dc.id, dc.run_id, dc.task_id, dc.status, wd.state, wd.stage, wd.last_error, wd.worktree_id,
233
+ wd.agent_terminal_handle, dc.assignee_handle, dc.creator_dispatch_id, dc.retry_of_dispatch_id,
234
+ dc.depth,
235
+ json_extract(wd.start_options, '$.launch.effective.agent') AS agent,
236
+ coalesce(json_extract(wd.start_options, '$.launch.effective.model'), df.model) AS model,
237
+ wp.presence,
238
+ dc.dispatched_at, dc.completed_at, dc.created_at, wd.updated_at,
239
+ max(coalesce({a}, ''), coalesce({b}, ''), coalesce({c}, ''), coalesce({d}, ''),
240
+ coalesce({e}, '')) AS change_ts
241
+ FROM dispatch_contexts dc
242
+ LEFT JOIN worker_dispatches wd ON wd.dispatch_id = dc.id
243
+ LEFT JOIN worker_dock_facts df ON df.dispatch_id = dc.id
244
+ LEFT JOIN worker_presence wp ON wp.dispatch_id = dc.id
245
+ WHERE 1 = 1
246
+ """.format(a=_norm("dc.created_at"), b=_norm("dc.dispatched_at"), c=_norm("dc.completed_at"),
247
+ d=_norm("wd.updated_at"), e=_norm("wp.updated_at"))
248
+
249
+
250
+ def _dispatch(row):
251
+ return {
252
+ "id": row["id"],
253
+ "run_id": row["run_id"],
254
+ "task_id": row["task_id"],
255
+ "status": row["status"],
256
+ "state": row["state"],
257
+ "stage": row["stage"],
258
+ "last_error": row["last_error"],
259
+ "worktree_id": row["worktree_id"],
260
+ "terminal_handle": row["agent_terminal_handle"],
261
+ "assignee_handle": row["assignee_handle"],
262
+ "creator_dispatch_id": row["creator_dispatch_id"],
263
+ "retry_of_dispatch_id": row["retry_of_dispatch_id"],
264
+ "depth": row["depth"],
265
+ "agent": row["agent"],
266
+ "model": row["model"],
267
+ "presence": row["presence"],
268
+ "dispatched_at": row["dispatched_at"],
269
+ "completed_at": row["completed_at"],
270
+ "created_at": row["created_at"],
271
+ "updated_at": row["updated_at"],
272
+ }
273
+
274
+
275
+ def dispatches(conn, run_id=None):
276
+ """Dispatches of a run (or all), oldest first."""
277
+ return [d for d, _ts in _dispatches(conn, run_id, None)]
278
+
279
+
280
+ def dispatches_since(conn, run_id, since_ts):
281
+ """(Dispatch, change_ts) for dispatches whose context, worker or presence moved at/past since_ts."""
282
+ return _dispatches(conn, run_id, since_ts)
283
+
284
+
285
+ def _dispatches(conn, run_id, since_ts):
286
+ sql, args = _DISPATCH_SQL, []
287
+ f, a = _run_filter(run_id, "dc")
288
+ sql += f
289
+ args += a
290
+ if since_ts is not None:
291
+ sql += " AND change_ts >= ?"
292
+ args.append(since_ts)
293
+ sql += " ORDER BY " + _norm("dc.created_at") + ", dc.rowid"
294
+ return [(_dispatch(r), r["change_ts"]) for r in conn.execute(sql, args)]
295
+
296
+
297
+ # --------------------------------------------------------------------------------------------- gates
298
+
299
+ _GATE_SQL = """
300
+ SELECT g.id, g.run_id, g.task_id, g.question, g.options, g.status, g.resolution, g.created_at,
301
+ g.resolved_at, max(coalesce({c}, ''), coalesce({r}, '')) AS change_ts
302
+ FROM decision_gates g
303
+ WHERE 1 = 1
304
+ """.format(c=_norm("g.created_at"), r=_norm("g.resolved_at"))
305
+
306
+
307
+ def _gate(row):
308
+ options = _json(row["options"])
309
+ return {
310
+ "id": row["id"],
311
+ "run_id": row["run_id"],
312
+ "task_id": row["task_id"],
313
+ "question": row["question"],
314
+ "options": options if options is not None else [],
315
+ "status": row["status"],
316
+ "resolution": row["resolution"],
317
+ "created_at": row["created_at"],
318
+ "resolved_at": row["resolved_at"],
319
+ }
320
+
321
+
322
+ def gates(conn, run_id=None):
323
+ """Decision gates of a run (or all), oldest first."""
324
+ return [g for g, _ts in _gates(conn, run_id, None)]
325
+
326
+
327
+ def gates_since(conn, run_id, since_ts):
328
+ """(Gate, change_ts) for gates created or resolved at/past since_ts."""
329
+ return _gates(conn, run_id, since_ts)
330
+
331
+
332
+ def _gates(conn, run_id, since_ts):
333
+ sql, args = _GATE_SQL, []
334
+ f, a = _run_filter(run_id, "g")
335
+ sql += f
336
+ args += a
337
+ if since_ts is not None:
338
+ sql += " AND change_ts >= ?"
339
+ args.append(since_ts)
340
+ sql += " ORDER BY " + _norm("g.created_at") + ", g.rowid"
341
+ return [(_gate(r), r["change_ts"]) for r in conn.execute(sql, args)]
342
+
343
+
344
+ # --------------------------------------------------------------------------------------------- handles
345
+
346
+ class Resolver:
347
+ """Maps message handles to {"kind", "id"} per the Handles section of docs/API.md."""
348
+
349
+ def __init__(self, conn):
350
+ self.term_dispatch = {}
351
+ for r in conn.execute("SELECT dispatch_id, agent_terminal_handle FROM worker_dispatches"
352
+ " WHERE agent_terminal_handle IS NOT NULL ORDER BY updated_at"):
353
+ self.term_dispatch[r[1]] = r[0]
354
+ self.assignee_dispatch = {}
355
+ for r in conn.execute("SELECT id, assignee_handle FROM dispatch_contexts"
356
+ " WHERE assignee_handle IS NOT NULL ORDER BY created_at"):
357
+ self.assignee_dispatch[r[1]] = r[0]
358
+ self.term_runs = {}
359
+ for r in conn.execute("SELECT run_id, terminal_handle FROM run_coordinator_handles"
360
+ " WHERE terminal_handle IS NOT NULL"
361
+ " UNION SELECT id, coordinator_handle FROM runs"
362
+ " WHERE coordinator_handle IS NOT NULL"):
363
+ self.term_runs.setdefault(r[1], set()).add(r[0])
364
+
365
+ def resolve(self, handle, run_id=None):
366
+ if handle and handle.startswith("run:"):
367
+ return {"kind": "coordinator", "id": handle[4:]}
368
+ if handle and handle.startswith("dispatch:"):
369
+ return {"kind": "dispatch", "id": handle[9:]}
370
+ if handle and handle.startswith("term_"):
371
+ if handle in self.term_dispatch:
372
+ return {"kind": "dispatch", "id": self.term_dispatch[handle]}
373
+ if handle in self.assignee_dispatch:
374
+ return {"kind": "dispatch", "id": self.assignee_dispatch[handle]}
375
+ owners = self.term_runs.get(handle)
376
+ if owners:
377
+ # One terminal can coordinate several runs: prefer the message's own run.
378
+ rid = run_id if run_id in owners else sorted(owners)[-1]
379
+ return {"kind": "coordinator", "id": rid}
380
+ return {"kind": "unknown", "id": handle}
381
+
382
+
383
+ # --------------------------------------------------------------------------------------------- messages
384
+
385
+ _MSG_SQL = """
386
+ SELECT m.id, m.run_id, m.sequence, m.type, m.priority, m.from_handle, m.to_handle, m.thread_id,
387
+ m.subject, m.body, m.created_at, p.dispatch_id AS prov_dispatch_id, p.task_id AS prov_task_id
388
+ FROM messages m
389
+ LEFT JOIN message_dispatch_provenance p ON p.message_id = m.id
390
+ WHERE 1 = 1
391
+ """
392
+
393
+
394
+ def _message(row, resolver):
395
+ body = row["body"] or ""
396
+ cut = len(body) > BODY_CAP
397
+ return {
398
+ "id": row["id"],
399
+ "run_id": row["run_id"],
400
+ "sequence": row["sequence"],
401
+ "type": row["type"],
402
+ "priority": row["priority"],
403
+ "from_handle": row["from_handle"],
404
+ "to_handle": row["to_handle"],
405
+ "from": resolver.resolve(row["from_handle"], row["run_id"]),
406
+ "to": resolver.resolve(row["to_handle"], row["run_id"]),
407
+ "dispatch_id": row["prov_dispatch_id"],
408
+ "task_id": row["prov_task_id"],
409
+ "thread_id": row["thread_id"],
410
+ "subject": row["subject"],
411
+ "body": body[:BODY_CAP],
412
+ "body_truncated": cut,
413
+ "created_at": row["created_at"],
414
+ }
415
+
416
+
417
+ def messages(conn, run_id=None, after_seq=None, last_n=None, resolver=None):
418
+ """Messages ordered by sequence (oldest first). last_n keeps only the newest N."""
419
+ resolver = resolver or Resolver(conn)
420
+ sql, args = _MSG_SQL, []
421
+ f, a = _run_filter(run_id, "m")
422
+ sql += f
423
+ args += a
424
+ if after_seq is not None:
425
+ sql += " AND m.sequence > ?"
426
+ args.append(after_seq)
427
+ if last_n is not None:
428
+ sql = "SELECT * FROM (" + sql + " ORDER BY m.sequence DESC LIMIT ?) ORDER BY sequence"
429
+ args.append(int(last_n))
430
+ else:
431
+ sql += " ORDER BY m.sequence"
432
+ return [_message(r, resolver) for r in conn.execute(sql, args)]
433
+
434
+
435
+ # --------------------------------------------------------------------------------------------- cursor
436
+
437
+ _CURSOR_SQL = """
438
+ SELECT (SELECT coalesce(max(sequence), 0) FROM messages) AS message_seq,
439
+ (SELECT max(max(coalesce({tc}, '')), max(coalesce({tk}, ''))) FROM tasks) AS task_ts,
440
+ (SELECT max(max(coalesce({dc}, '')), max(coalesce({dd}, '')), max(coalesce({dk}, '')))
441
+ FROM dispatch_contexts) AS dc_ts,
442
+ (SELECT max(coalesce({wu}, '')) FROM worker_dispatches) AS wd_ts,
443
+ (SELECT max(coalesce({pu}, '')) FROM worker_presence) AS wp_ts,
444
+ (SELECT max(max(coalesce({gc}, '')), max(coalesce({gr}, ''))) FROM decision_gates) AS gate_ts,
445
+ (SELECT max(max(coalesce({rc}, '')), max(coalesce({ru}, ''))) FROM runs) AS run_ts
446
+ """.format(tc=_norm("created_at"), tk=_norm("completed_at"), dc=_norm("created_at"),
447
+ dd=_norm("dispatched_at"), dk=_norm("completed_at"), wu=_norm("updated_at"),
448
+ pu=_norm("updated_at"), gc=_norm("created_at"), gr=_norm("resolved_at"),
449
+ rc=_norm("created_at"), ru=_norm("updated_at"))
450
+
451
+
452
+ def cursor(conn):
453
+ """Current change cursors. Timestamps are normalised ('YYYY-MM-DD HH:MM:SS.fff'), '' when empty.
454
+ 'run_ts' is internal to the SSE loop; the API Cursor object carries the other four."""
455
+ r = conn.execute(_CURSOR_SQL).fetchone()
456
+ return {
457
+ "message_seq": r["message_seq"],
458
+ "task_ts": r["task_ts"] or "",
459
+ "dispatch_ts": max(r["dc_ts"] or "", r["wd_ts"] or "", r["wp_ts"] or ""),
460
+ "gate_ts": r["gate_ts"] or "",
461
+ "run_ts": r["run_ts"] or "",
462
+ }
463
+
464
+
465
+ def norm_ts(conn, value):
466
+ """Normalise one stored timestamp the same way the SQL above does."""
467
+ if value is None:
468
+ return None
469
+ return conn.execute("SELECT strftime('%Y-%m-%d %H:%M:%f', ?)", (value,)).fetchone()[0]
470
+
471
+
472
+ # --------------------------------------------------------------------------------------------- history
473
+
474
+ def history(conn, run_id):
475
+ """Every event of one run in time order: (t, seq, kind, ref, data) sorted by t, then seq."""
476
+ resolver = Resolver(conn)
477
+ out = []
478
+
479
+ def add(ts, kind, ref, data, seq=None):
480
+ if ts is None:
481
+ return
482
+ t = norm_ts(conn, ts)
483
+ if t is None:
484
+ return
485
+ out.append((t, seq, kind, ref, data))
486
+
487
+ for t in tasks(conn, run_id):
488
+ add(t["created_at"], "task_created", t["id"], t)
489
+ add(t["completed_at"], "task_completed", t["id"], t)
490
+ for d in dispatches(conn, run_id):
491
+ add(d["dispatched_at"] or d["created_at"], "dispatch_started", d["id"], d)
492
+ if d["updated_at"] and d["updated_at"] != (d["dispatched_at"] or d["created_at"]):
493
+ add(d["updated_at"], "dispatch_updated", d["id"], d)
494
+ for g in gates(conn, run_id):
495
+ add(g["created_at"], "gate_created", g["id"], g)
496
+ add(g["resolved_at"], "gate_resolved", g["id"], g)
497
+ for m in messages(conn, run_id, resolver=resolver):
498
+ add(m["created_at"], "message", m["id"], m, seq=m["sequence"])
499
+
500
+ # Sorted by t (whole seconds, as emitted), then seq, so messages keep messages.sequence order;
501
+ # the full-precision time breaks remaining ties.
502
+ out.sort(key=lambda e: (_secs(e[0]), e[1] if e[1] is not None else -1, e[0]))
503
+ return [{"t": _secs(t), "kind": kind, "seq": seq, "ref": ref, "data": data}
504
+ for (t, seq, kind, ref, data) in out]
505
+
506
+
507
+ # --------------------------------------------------------------------------------------------- stats
508
+
509
+ def _secs_between(a, b):
510
+ """SQL for whole seconds from timestamp a to b; julianday() reads both stored formats."""
511
+ return "CAST(round((julianday({b}) - julianday({a})) * 86400) AS INTEGER)".format(a=a, b=b)
512
+
513
+
514
+ def _median(values):
515
+ vals = sorted(v for v in values if v is not None and v >= 0)
516
+ if not vals:
517
+ return None
518
+ mid = len(vals) // 2
519
+ return vals[mid] if len(vals) % 2 else (vals[mid - 1] + vals[mid]) // 2
520
+
521
+
522
+ def stats(conn, run_id):
523
+ """Run totals for the stats strip (docs/API.md, Stats). Counts come from the whole run, not
524
+ from the message window a snapshot carries. SELECT-only, like everything in this module."""
525
+ one = lambda sql, args=(run_id,): conn.execute(sql, args).fetchone()
526
+ pairs = lambda sql: {r[0]: r[1] for r in conn.execute(sql, (run_id,))}
527
+
528
+ by_status = pairs("SELECT status, count(*) FROM tasks WHERE run_id = ? GROUP BY status")
529
+ task_durs = [r[0] for r in conn.execute(
530
+ "SELECT " + _secs_between("created_at", "completed_at") + " FROM tasks"
531
+ " WHERE run_id = ? AND status = 'completed' AND completed_at IS NOT NULL", (run_id,))]
532
+
533
+ workers = conn.execute(
534
+ "SELECT dc.id, dc.retry_of_dispatch_id, dc.creator_dispatch_id, wd.state,"
535
+ " json_extract(wd.start_options, '$.launch.effective.agent') AS agent,"
536
+ " " + _secs_between("coalesce(dc.dispatched_at, dc.created_at)", "dc.completed_at") + " AS dur"
537
+ " FROM dispatch_contexts dc LEFT JOIN worker_dispatches wd ON wd.dispatch_id = dc.id"
538
+ " WHERE dc.run_id = ?", (run_id,)).fetchall()
539
+ by_state, by_agent = {}, {}
540
+ for w in workers:
541
+ st = w["state"] or "unknown"
542
+ by_state[st] = by_state.get(st, 0) + 1
543
+ ag = w["agent"] or "unknown"
544
+ by_agent[ag] = by_agent.get(ag, 0) + 1
545
+
546
+ by_type = pairs("SELECT type, count(*) FROM messages WHERE run_id = ? GROUP BY type")
547
+ gates = conn.execute(
548
+ "SELECT status, " + _secs_between("created_at", "resolved_at") + " AS dur"
549
+ " FROM decision_gates WHERE run_id = ?", (run_id,)).fetchall()
550
+
551
+ t = one("SELECT r.created_at,"
552
+ " (SELECT max(x) FROM (SELECT max({m}) AS x FROM messages WHERE run_id = r.id"
553
+ " UNION ALL SELECT max({tc}) FROM tasks WHERE run_id = r.id"
554
+ " UNION ALL SELECT max({tk}) FROM tasks WHERE run_id = r.id"
555
+ " UNION ALL SELECT max({d}) FROM dispatch_contexts WHERE run_id = r.id"
556
+ " UNION ALL SELECT max({g}) FROM decision_gates WHERE run_id = r.id)) AS last,"
557
+ " (SELECT min({dd}) FROM dispatch_contexts WHERE run_id = r.id) AS first_dispatch,"
558
+ " strftime('%Y-%m-%d %H:%M:%f', 'now') AS now"
559
+ " FROM runs r WHERE r.id = ?".format(
560
+ m=_norm("created_at"), tc=_norm("created_at"), tk=_norm("completed_at"),
561
+ d=_norm("created_at"), g=_norm("coalesce(resolved_at, created_at)"),
562
+ dd=_norm("coalesce(dispatched_at, created_at)")))
563
+ if t is None:
564
+ return None
565
+ # _secs_between renders julianday(b) before julianday(a), so the placeholders bind as (b, a).
566
+ secs = lambda a, b: one("SELECT " + _secs_between("?", "?"), (b, a))[0] if a and b else None
567
+
568
+ total_tasks = sum(by_status.values())
569
+ active = sum(by_state.get(s, 0) for s in ACTIVE_STATES)
570
+ return {
571
+ "tasks": {"total": total_tasks, "by_status": by_status,
572
+ "done": by_status.get("completed", 0), "failed": by_status.get("failed", 0)},
573
+ "workers": {"total": len(workers), "active": active, "by_state": by_state, "by_agent": by_agent,
574
+ "retries": sum(1 for w in workers if w["retry_of_dispatch_id"]),
575
+ "spawned": sum(1 for w in workers if w["creator_dispatch_id"])},
576
+ "messages": {"total": sum(by_type.values()), "by_type": by_type},
577
+ "gates": {"total": len(gates), "pending": sum(1 for g in gates if g["status"] == "pending"),
578
+ "resolved": sum(1 for g in gates if g["status"] == "resolved"),
579
+ "median_resolve_s": _median([g["dur"] for g in gates if g["status"] == "resolved"])},
580
+ "time": {"started_at": t["created_at"], "last_activity": _secs(t["last"]),
581
+ "elapsed_s": secs(t["created_at"], t["last"]),
582
+ "idle_s": secs(t["last"], t["now"]),
583
+ "first_dispatch_s": secs(t["created_at"], t["first_dispatch"]),
584
+ "median_task_s": _median(task_durs),
585
+ "median_worker_s": _median([w["dur"] for w in workers])},
586
+ }
orca_board/paths.py ADDED
@@ -0,0 +1,81 @@
1
+ """Where Orca keeps orchestration.db, per operating system.
2
+
3
+ Orca writes the database as ``<userData>/orchestration.db``. What ``userData`` is depends on how
4
+ Orca runs, so the board tries a short list of candidates and takes the first one that exists:
5
+
6
+ 1. ``$ORCA_USER_DATA_PATH`` and ``$ORCA_USER_DATA``: Orca's own overrides of its data folder. Orca
7
+ exports the first one into the terminals it opens, so a board started from an Orca terminal finds
8
+ the right database even for a non-default profile.
9
+ 2. The data folder of Orca's background service (orcad, used by ``orca serve`` and remote
10
+ runtimes): ``$XDG_DATA_HOME/Orca`` when that is set, otherwise ``~/.orca``, on every OS.
11
+ 3. The data folder of the Orca desktop app (Electron's ``userData``):
12
+ macOS ``~/Library/Application Support/orca``, Windows ``%APPDATA%\\orca``, Linux
13
+ ``$XDG_CONFIG_HOME/orca`` (default ``~/.config/orca``).
14
+
15
+ Sources, read in the Orca CLI and orcad bundles (orcad 0.1.0, minified JavaScript):
16
+
17
+ - ``orchestrationDbPath() { return join(app.getPath("userData"), "orchestration.db") }``
18
+ (orcad-server.js, line 9866; the helper is on line 8913).
19
+ - orcad's ``userData``: ``ORCA_USER_DATA``, else ``XDG_DATA_HOME/Orca``, else ``~/.orca``
20
+ (orcad-server.js, line 400).
21
+ - The desktop data folder per platform: darwin ``~/Library/Application Support/orca``, win32
22
+ ``%APPDATA%/orca``, otherwise ``(XDG_CONFIG_HOME || ~/.config)/orca``, with
23
+ ``ORCA_USER_DATA_PATH`` taking precedence (out/cli/index.js, line 101; the same logic again on
24
+ line 1433, where a missing APPDATA falls back to ``~/AppData/Roaming``).
25
+
26
+ Confidence: ``~/.orca`` is confirmed on Linux against a running Orca. The macOS and Windows desktop
27
+ folders come from Orca's source only and have not been checked against a real install; if the
28
+ board does not find the database there, pass ``--db`` (or set ``ORCA_BOARD_DB``).
29
+
30
+ Everything here is a pure function of (platform, environment, home) so tests can check every OS on
31
+ any OS. No file is created or written.
32
+ """
33
+
34
+ import ntpath
35
+ import os
36
+ import posixpath
37
+ import sys
38
+
39
+ DB_NAME = "orchestration.db"
40
+
41
+
42
+ def _pathmod(platform):
43
+ return ntpath if platform == "win32" else posixpath
44
+
45
+
46
+ def candidates(platform=None, env=None, home=None):
47
+ """Every place Orca may keep orchestration.db on `platform`, most specific first, no duplicates."""
48
+ platform = sys.platform if platform is None else platform
49
+ env = os.environ if env is None else env
50
+ home = os.path.expanduser("~") if home is None else home
51
+ p = _pathmod(platform)
52
+ dirs = []
53
+ for var in ("ORCA_USER_DATA_PATH", "ORCA_USER_DATA"):
54
+ if env.get(var):
55
+ dirs.append(env[var])
56
+ # orcad, the background service: the same layout on every OS.
57
+ if env.get("XDG_DATA_HOME"):
58
+ dirs.append(p.join(env["XDG_DATA_HOME"], "Orca"))
59
+ dirs.append(p.join(home, ".orca"))
60
+ # The desktop app's Electron userData folder.
61
+ if platform == "darwin":
62
+ dirs.append(p.join(home, "Library", "Application Support", "orca"))
63
+ elif platform == "win32":
64
+ dirs.append(p.join(env.get("APPDATA") or p.join(home, "AppData", "Roaming"), "orca"))
65
+ else:
66
+ dirs.append(p.join(env.get("XDG_CONFIG_HOME") or p.join(home, ".config"), "orca"))
67
+ out = []
68
+ for d in dirs:
69
+ path = p.join(d, DB_NAME)
70
+ if path not in out:
71
+ out.append(path)
72
+ return out
73
+
74
+
75
+ def default_db(platform=None, env=None, home=None, exists=os.path.exists):
76
+ """The first candidate that exists, else the first candidate (so errors name a real guess)."""
77
+ found = candidates(platform, env, home)
78
+ for path in found:
79
+ if exists(path):
80
+ return path
81
+ return found[0]