cctally 1.91.0 → 1.92.0

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/bin/_cctally_cache.py +863 -74
  3. package/bin/_cctally_config.py +57 -0
  4. package/bin/_cctally_core.py +39 -8
  5. package/bin/_cctally_dashboard.py +146 -5
  6. package/bin/_cctally_dashboard_conversation.py +164 -18
  7. package/bin/_cctally_dashboard_envelope.py +2 -0
  8. package/bin/_cctally_db.py +372 -10
  9. package/bin/_cctally_doctor.py +18 -1
  10. package/bin/_cctally_journal.py +535 -13
  11. package/bin/_cctally_journal_repair.py +6 -0
  12. package/bin/_cctally_parser.py +6 -0
  13. package/bin/_cctally_quota.py +171 -55
  14. package/bin/_cctally_record.py +13 -1
  15. package/bin/_cctally_rederive.py +4 -0
  16. package/bin/_cctally_store.py +311 -6
  17. package/bin/_cctally_transcript.py +32 -2
  18. package/bin/_lib_cache_report.py +8 -3
  19. package/bin/_lib_codex_conversation.py +851 -81
  20. package/bin/_lib_codex_conversation_query.py +2005 -95
  21. package/bin/_lib_codex_find_projection.py +370 -0
  22. package/bin/_lib_codex_harness_preamble.py +176 -0
  23. package/bin/_lib_codex_hooks.py +5 -3
  24. package/bin/_lib_codex_js_scan.py +254 -0
  25. package/bin/_lib_codex_landmarks.py +309 -0
  26. package/bin/_lib_codex_title_clean.py +116 -0
  27. package/bin/_lib_conversation_dispatch.py +153 -21
  28. package/bin/_lib_conversation_watch.py +4 -2
  29. package/bin/_lib_doctor.py +64 -0
  30. package/bin/_lib_quota_alert_axes.py +31 -34
  31. package/bin/_lib_stats_damage.py +523 -0
  32. package/bin/cctally +5 -0
  33. package/dashboard/static/assets/index-BEzzJtUd.js +97 -0
  34. package/dashboard/static/assets/{index-Dwirao3Y.css → index-DnWdv8um.css} +1 -1
  35. package/dashboard/static/dashboard.html +2 -2
  36. package/package.json +7 -1
  37. package/dashboard/static/assets/index-CILAoEja.js +0 -90
@@ -306,14 +306,43 @@ def _map_claude_item(session_id: str, it: dict) -> dict:
306
306
  """One Claude assembled item → the neutral detail item shape (§5.6). Claude's
307
307
  kinds/blocks pass through untranslated (both vocabularies are provider-truthful
308
308
  values of the same required field)."""
309
+ own_uuid = it["anchor"]["uuid"]
309
310
  return {
310
- "item_key": _claude_item_key(session_id, it["anchor"]["uuid"]),
311
+ "item_key": _claude_item_key(session_id, own_uuid),
311
312
  "kind": it["kind"],
312
313
  "timestamp_utc": it.get("ts"),
313
314
  "model": it.get("model"),
314
315
  "blocks": it.get("blocks", []),
315
316
  "cost_usd": it.get("cost_usd"),
316
317
  "tokens": _claude_tokens_union(it.get("tokens")),
318
+ "member_item_keys": [
319
+ _claude_item_key(session_id, uuid)
320
+ for uuid in it.get("member_uuids", []) if uuid != own_uuid
321
+ ],
322
+ "subagent_key": it.get("subagent_key"),
323
+ "parent_item_key": (
324
+ _claude_item_key(session_id, it["parent_uuid"])
325
+ if it.get("parent_uuid") is not None else None
326
+ ),
327
+ "is_sidechain": bool(it.get("is_sidechain")),
328
+ "meta_kind": it.get("meta_kind"),
329
+ "skill_name": it.get("skill_name"),
330
+ "command_name": it.get("command_name"),
331
+ "cache_failure": it.get("cache_failure"),
332
+ }
333
+
334
+
335
+ def _map_claude_subagent_meta(session_id: str, values: dict | None) -> dict:
336
+ """Translate the one identity-bearing field in legacy subagent metadata."""
337
+ return {
338
+ key: ({
339
+ **meta,
340
+ "spawn_uuid": (
341
+ _claude_item_key(session_id, meta["spawn_uuid"])
342
+ if meta.get("spawn_uuid") is not None else None
343
+ ),
344
+ } if isinstance(meta, dict) else meta)
345
+ for key, meta in (values or {}).items()
317
346
  }
318
347
 
319
348
 
@@ -386,6 +415,8 @@ def _claude_detail(
386
415
  "title": res["title"],
387
416
  "items": neutral_items,
388
417
  "page": page,
418
+ "subagent_meta": _map_claude_subagent_meta(
419
+ session_id, res.get("subagent_meta")),
389
420
  "children": [],
390
421
  "parent": None,
391
422
  "total_cost_usd": res["cost_usd"],
@@ -399,33 +430,98 @@ def _claude_detail(
399
430
  def _claude_outline(
400
431
  conn: sqlite3.Connection, session_id: str, conversation_key: str,
401
432
  ) -> dict:
402
- """Claude outline envelope (§5.6). Reuses the existing kernel outline for
403
- ``stats``/``files``; the per-turn ``item_key`` + block-kind counts are built
404
- from the SAME assembled items the detail pages, so outline and detail item
405
- keys align exactly. ``children`` is empty (no native threading)."""
433
+ """Claude outline envelope (§5.6), without weakening the native outline.
434
+
435
+ The legacy kernel is the authority for navigation: it already derives tool
436
+ failures, subagent topology, cache rebuilds, files, task completion, and the
437
+ complete turn skeleton from the same assembled items as detail. This
438
+ adapter changes only identity-bearing fields from native UUIDs to neutral
439
+ item keys and names the provider-neutral file fields. Re-deriving a smaller
440
+ outline from assembled blocks here previously stripped precisely the facts
441
+ the qualified reader needs (#491).
442
+ """
406
443
  o = lcq.get_conversation_outline(conn, session_id)
407
444
  if o is None:
408
445
  return {"status": "not_found", "conversation_key": conversation_key}
409
- asm = lcq._assemble_session_memoized(conn, session_id)
446
+
447
+ def item_key(uuid):
448
+ return _claude_item_key(session_id, uuid) if uuid is not None else None
449
+
410
450
  turns = []
411
- for it in asm["items"]:
412
- kinds: dict[str, int] = {}
413
- for b in it.get("blocks", []):
414
- bk = b.get("kind")
415
- if bk:
416
- kinds[bk] = kinds.get(bk, 0) + 1
417
- turns.append({
418
- "item_key": _claude_item_key(session_id, it["anchor"]["uuid"]),
419
- "label": lcq._outline_label(it.get("text", "")),
420
- "timestamp_utc": it.get("ts"),
421
- "kinds": kinds,
451
+ for turn in o["turns"]:
452
+ own_key = item_key(turn["uuid"])
453
+ neutral = {
454
+ "item_key": own_key,
455
+ "kind": turn["kind"],
456
+ "label": turn["label"],
457
+ "timestamp_utc": turn.get("ts"),
458
+ "kinds": {turn["kind"]: 1},
459
+ "member_item_keys": [
460
+ item_key(uuid) for uuid in turn.get("member_uuids", [])
461
+ if uuid != turn["uuid"]
462
+ ],
463
+ "subagent_key": turn.get("subagent_key"),
464
+ "parent_item_key": item_key(turn.get("parent_uuid")),
465
+ "is_sidechain": bool(turn.get("is_sidechain")),
466
+ }
467
+ for field in (
468
+ "tools", "thinking", "model", "tokens", "meta_kind",
469
+ "skill_name", "cache_failure"):
470
+ if field in turn:
471
+ neutral[field] = turn[field]
472
+ turns.append(neutral)
473
+
474
+ stats = dict(o["stats"])
475
+ cache_failures = stats.get("cache_failures")
476
+ if isinstance(cache_failures, dict):
477
+ cache_failures = dict(cache_failures)
478
+ cache_failures["rebuilds"] = [
479
+ {**row, "uuid": item_key(row.get("uuid"))}
480
+ for row in cache_failures.get("rebuilds", [])
481
+ ]
482
+ stats["cache_failures"] = cache_failures
483
+
484
+ files = []
485
+ for file in o.get("files", []):
486
+ touches = [{
487
+ "item_key": item_key(touch.get("uuid")),
488
+ "timestamp_utc": None,
489
+ "tool_use_id": touch.get("tool_use_id"),
490
+ "op": touch.get("op"),
491
+ "added": touch.get("add"),
492
+ "removed": touch.get("del"),
493
+ } for touch in file.get("touches", [])]
494
+ tools = list(dict.fromkeys(
495
+ touch["op"] for touch in touches if touch.get("op")))
496
+ files.append({
497
+ "file_path": file.get("path"),
498
+ # The count-only neutral file shape requires a tool label. Rich
499
+ # Claude entries retain every native operation instead of claiming
500
+ # that Write/MultiEdit touches were Edit calls.
501
+ "tool": ",".join(tools),
502
+ "count": len(touches),
503
+ "added": file.get("add"),
504
+ "removed": file.get("del"),
505
+ "touches": touches,
422
506
  })
507
+
508
+ subagent_meta = _map_claude_subagent_meta(
509
+ session_id, o.get("subagent_meta"))
510
+ task_completion = o.get("task_completion")
511
+ if isinstance(task_completion, dict):
512
+ task_completion = {
513
+ **task_completion,
514
+ "anchor_uuid": item_key(task_completion.get("anchor_uuid")),
515
+ }
423
516
  return {
424
517
  "status": "ok",
425
518
  "conversation_key": conversation_key,
426
519
  "turns": turns,
427
- "stats": o["stats"],
428
- "files": o["files"],
520
+ "subagent_meta": subagent_meta,
521
+ "subagent_costs": o.get("subagent_costs", {}),
522
+ "stats": stats,
523
+ "files": files,
524
+ "task_completion": task_completion,
429
525
  "children": [],
430
526
  }
431
527
 
@@ -531,6 +627,25 @@ def neutral_browse(
531
627
  raise ValueError(f"unknown source: {source!r}")
532
628
 
533
629
 
630
+ def neutral_facets(
631
+ conn: sqlite3.Connection, *, source: str, effective_speed: str | None = None,
632
+ ) -> dict:
633
+ """Facet-only collection envelope for one source.
634
+
635
+ Codex has a dedicated rollup projection so the facets request never builds
636
+ or prices a browse page that its transport discards. Claude retains its
637
+ established browse-derived facet contract.
638
+ """
639
+ speed = effective_speed or _DEFAULT_SPEED
640
+ if source == "codex":
641
+ return q.list_codex_conversation_facets(conn)
642
+ if source == "claude":
643
+ env = _claude_browse(conn, effective_speed=speed)
644
+ return {"status": env.get("status"), "facets": env.get("facets") or {
645
+ "projects": [], "models": []}}
646
+ raise ValueError(f"unknown source: {source!r}")
647
+
648
+
534
649
  def neutral_detail(
535
650
  conn: sqlite3.Connection, ref: str, *, effective_speed: str | None = None,
536
651
  after: str | None = None, before: str | None = None,
@@ -725,6 +840,8 @@ def _claude_export(
725
840
  def neutral_find(
726
841
  conn: sqlite3.Connection, ref: str, query: str, *, kind: str = "all",
727
842
  regex: bool = False, case: bool = False, effective_speed: str | None = None,
843
+ limit: int = 100, cursor: str | None = None, direction: str = "next",
844
+ around: str | None = None,
728
845
  ) -> dict:
729
846
  """In-conversation find for a neutral reference (§3.1). An unknown ``kind``
730
847
  raises ``ValueError`` (route → 400); an unknown/garbage ref → ``not_found``.
@@ -736,8 +853,23 @@ def neutral_find(
736
853
  if cref is None:
737
854
  return {"status": "not_found", "conversation_key": ref}
738
855
  if cref.source == "codex":
739
- return q.find_in_codex_conversation(
740
- conn, cref.conversation_key, query, kind=kind, regex=regex, case=case)
856
+ try:
857
+ return q.find_occurrences_in_codex_conversation(
858
+ conn,
859
+ cref.conversation_key,
860
+ query,
861
+ kind=kind,
862
+ regex=regex,
863
+ case_sensitive=case,
864
+ limit=limit,
865
+ cursor=cursor,
866
+ direction=direction,
867
+ around=around,
868
+ )
869
+ except q.InvalidFindCursor:
870
+ return {"status": "invalid_find_cursor"}
871
+ except q.StaleFindCursor:
872
+ return {"status": "stale_find_cursor"}
741
873
  return _claude_find(
742
874
  conn, cref.native_key, cref.conversation_key, query,
743
875
  kind=kind, regex=regex, case=case)
@@ -51,7 +51,9 @@ def watch_step(files, seen, *, stat_fn=file_sig, ingest_fn, committed_sig_fn=Non
51
51
  cursor, in session_files, lags the new disk size). committed_sig_fn defaults
52
52
  to stat_fn for pure unit tests with no cache. A contended/declined/failed
53
53
  ingest leaves `seen` untouched so the next cycle retries (the 5s backstop is
54
- the floor)."""
54
+ the floor). Account-scoped callers may additionally expose
55
+ ``stats.targeted_visible``: the clean ingest still advances ``seen``, but a
56
+ false value suppresses the tail frame when only another account changed."""
55
57
  committed_sig_fn = committed_sig_fn or stat_fn
56
58
  changed = changed_paths(files, seen, stat_fn)
57
59
  if not changed:
@@ -64,4 +66,4 @@ def watch_step(files, seen, *, stat_fn=file_sig, ingest_fn, committed_sig_fn=Non
64
66
  sig = committed_sig_fn(p)
65
67
  if sig is not None:
66
68
  new_seen[p] = sig
67
- return new_seen, True
69
+ return new_seen, bool(getattr(stats, "targeted_visible", True))
@@ -210,6 +210,11 @@ class DoctorState:
210
210
  # walk, so `files_failed`/`files_deferred_torn` are both zero, no `blocked`
211
211
  # record is ever written, and the ingest-backlog leg reads a drained store.
212
212
  codex_replay_deferred: Optional[dict] = None
213
+ # #485: privacy-safe durable records written when cache.db and/or
214
+ # conversations.db refused to treat an invalid Codex root as deletion
215
+ # evidence. None is the normal state; each record contains counts/reasons
216
+ # but never configured paths or provider identifiers.
217
+ codex_prune_refusals: Optional[list[dict]] = None
213
218
  # #279 S2 (F5b): PRAGMA quick_check(1) results, gathered ONLY under
214
219
  # doctor_gather_state(deep=True) (CLI cmd_doctor) — the dashboard
215
220
  # rebuild loop calls the gather every rebuild and quick_check on a
@@ -1236,6 +1241,64 @@ def _check_data_codex_replay(s: DoctorState) -> CheckResult:
1236
1241
  )
1237
1242
 
1238
1243
 
1244
+ def _check_data_codex_prune_safety(s: DoctorState) -> CheckResult:
1245
+ """Surface a fail-closed orphan-prune decision instead of silent loss."""
1246
+ records = [
1247
+ record for record in (s.codex_prune_refusals or [])
1248
+ if isinstance(record, dict)
1249
+ ]
1250
+ if not records:
1251
+ return CheckResult(
1252
+ id="data.codex_prune_safety",
1253
+ title="Codex orphan pruning",
1254
+ severity="ok",
1255
+ summary="no refused prune",
1256
+ remediation=None,
1257
+ details={"refusalCount": 0, "stores": []},
1258
+ )
1259
+ stores = sorted({
1260
+ str(record.get("store"))
1261
+ for record in records
1262
+ if record.get("store") in {"cache", "conversations"}
1263
+ })
1264
+ preserved_files = max(
1265
+ (int(record.get("preservedFileCount") or 0) for record in records),
1266
+ default=0,
1267
+ )
1268
+ since_values = sorted({
1269
+ str(record["since"])
1270
+ for record in records
1271
+ if isinstance(record.get("since"), str) and record["since"]
1272
+ })
1273
+ reasons = sorted({
1274
+ str(reason)
1275
+ for record in records
1276
+ for reason in (
1277
+ record.get("reasons") if isinstance(record.get("reasons"), list) else []
1278
+ )
1279
+ if isinstance(reason, str)
1280
+ })
1281
+ return CheckResult(
1282
+ id="data.codex_prune_safety",
1283
+ title="Codex orphan pruning",
1284
+ severity="warn",
1285
+ summary=(
1286
+ f"refused unsafe prune; preserved {preserved_files} tracked file(s)"
1287
+ ),
1288
+ remediation=(
1289
+ "Check that every $CODEX_HOME root is mounted and contains Codex "
1290
+ "rollout JSONL, then run `cctally cache-sync --source codex`"
1291
+ ),
1292
+ details={
1293
+ "refusalCount": len(records),
1294
+ "stores": stores,
1295
+ "since": since_values[0] if since_values else None,
1296
+ "reasons": reasons,
1297
+ "preservedFileCount": preserved_files,
1298
+ },
1299
+ )
1300
+
1301
+
1239
1302
  def _check_data_codex_quota_verification(s: DoctorState) -> CheckResult:
1240
1303
  """WARN when the detached Codex quota verification is not landing.
1241
1304
 
@@ -2935,6 +2998,7 @@ _CATEGORY_DEFINITIONS: tuple[tuple[str, str, tuple[tuple[str, str], ...]], ...]
2935
2998
  # tests/test_doctor_codex_project_metadata.py), so the replay leg goes
2936
2999
  # after the pair rather than between them.
2937
3000
  ("data.codex_project_metadata", "_check_data_codex_project_metadata"),
3001
+ ("data.codex_prune_safety", "_check_data_codex_prune_safety"),
2938
3002
  ("data.codex_replay", "_check_data_codex_replay"),
2939
3003
  ("data.codex_ingest_backlog", "_check_data_codex_ingest_backlog"),
2940
3004
  ("data.codex_quota", "_check_data_codex_quota"),
@@ -23,9 +23,10 @@ in ``quota_window_snapshots`` moving at all:
23
23
  and becomes eligible when wall time passes it with no mutation to observe.
24
24
  Persisting that boundary and treating ``now >= boundary`` as dirty is what
25
25
  closes it. Unlike axes 2 and 3 this one fires on WALL CLOCK rather than on a
26
- configuration change, which is why the hook path defers it
27
- (``defer_scheduled``) instead of paying an unannounced whole-history pass on
28
- a blocking tick.
26
+ configuration change. An ownership schedule lets the hook evaluate only the
27
+ complete roots whose deadlines matured; scalar-only legacy state still
28
+ defers rather than paying an unannounced whole-history pass on a blocking
29
+ tick.
29
30
  5. **Durable lifecycle state** — the existing arming rows and terminal events,
30
31
  unchanged. Represented here only as the fingerprints axis 2 compares.
31
32
 
@@ -80,6 +81,7 @@ def alert_dirty_scope(
80
81
  gate_after: bool,
81
82
  now: dt.datetime,
82
83
  next_evaluation_at: "dt.datetime | None",
84
+ scheduled_roots: "Iterable[str] | None" = None,
83
85
  defer_scheduled: bool = False,
84
86
  ) -> AlertDirtyScope:
85
87
  """Resolve the five axes into one decision.
@@ -89,14 +91,11 @@ def alert_dirty_scope(
89
91
  observed_slot, window_minutes)``; the ROOT is element 1, which is what an
90
92
  exact-rule change is scoped to.
91
93
 
92
- ``defer_scheduled`` is the hook path's (``full_pass="defer"``). Axes 2 and 3
93
- are driven by a configuration change the user just made, so widening for
94
- them is bounded and expected; axis 4 is driven by WALL CLOCK, which makes it
95
- the one route into a whole-history pass that can land on a blocking hook
96
- tick with nothing to have predicted it. Under this flag it is recorded as
97
- ``REASON_SCHEDULED_DEFERRED`` and does NOT strengthen the scope — and the
98
- caller owes the stored boundary a carry-through, because a deferral that
99
- lets the boundary be recomputed is a silent drop.
94
+ ``scheduled_roots`` is the validated ownership retained with axis 4. When
95
+ present, a matured instant scopes to those roots even on the hook path.
96
+ ``None`` is the legacy/unavailable-ownership shape; only that shape needs
97
+ ``defer_scheduled`` to avoid an unannounced whole-history hook pass, and the
98
+ caller then owes the scalar boundary a carry-through.
100
99
  """
101
100
  reasons: list[str] = []
102
101
  if not gate_after:
@@ -132,11 +131,19 @@ def alert_dirty_scope(
132
131
  reasons.append("rule_changed")
133
132
 
134
133
  if next_evaluation_at is not None and now >= next_evaluation_at:
135
- # A future-clocked observation just became eligible. Which identity it
136
- # belongs to is not recorded — only the instant — so the honest scope is
137
- # everything, and on the hook path "everything" is precisely what may
138
- # not run.
139
- if defer_scheduled:
134
+ # Epoch 1007 records the roots owning each scheduled instant. A complete
135
+ # semantic pass over those roots is bounded enough for the hook path and
136
+ # is all axis 4 needs. ``None`` means legacy/unavailable ownership, where
137
+ # the only honest scope remains everything (and therefore deferral on a
138
+ # hook tick). An empty known set means the owning roots are not lifecycle
139
+ # eligible on this tick; the stored axis remains due for a later tick.
140
+ if scheduled_roots is not None:
141
+ due_roots = {str(root) for root in scheduled_roots if str(root)}
142
+ if due_roots:
143
+ scope = _strongest(scope, SCOPE_ROOTS)
144
+ roots |= due_roots
145
+ reasons.append("scheduled")
146
+ elif defer_scheduled:
140
147
  reasons.append(REASON_SCHEDULED_DEFERRED)
141
148
  else:
142
149
  scope = _strongest(scope, SCOPE_ALL)
@@ -154,12 +161,12 @@ def next_evaluation_boundary(
154
161
  ) -> "dt.datetime | None":
155
162
  """The earliest still-future capture the projector must come back for.
156
163
 
157
- A bounded pass only sees the dirty windows, so the STORED boundary is
164
+ This is the legacy scalar helper. A bounded pass only sees dirty windows, so
165
+ the STORED boundary is
158
166
  retained whenever it is still in the future: dropping it would forget a
159
167
  future-clocked observation sitting in a window this pass never loaded. Once
160
- wall time passes it the axis fires, the pass widens to everything, and the
161
- boundary is recomputed from complete evidence — so a retained value can only
162
- ever cost one extra pass, never a missed one.
168
+ wall time passes it the axis fires and the caller decides whether it has
169
+ enough ownership to scope the pass.
163
170
 
164
171
  ``retain_due`` keeps a boundary that is ALREADY due, which is the case where
165
172
  "recomputed from complete evidence" is a lie: a reporting-only pass never
@@ -167,20 +174,10 @@ def next_evaluation_boundary(
167
174
  the widening deliberately did not look. Either would otherwise retire the
168
175
  axis on behalf of an evaluation nobody performed.
169
176
 
170
- A due value sorts before every future candidate, so it stays until a pass
171
- that genuinely looked at everything retires it — in practice a hook tick
172
- that widened to whole-history for axis 2 or 3, since carrying alert
173
- eligibility is what separates such a pass from a reporting-only one and the
174
- hook is the only production caller that carries it.
175
-
176
- It does NOT stay "until a pass that can act on it does", and that gap is
177
- open rather than closed: on a hook-only install with a steady enabled gate,
178
- unchanged rules and a quiet ledger, no qualifying pass ever runs and the
179
- instant is retained indefinitely. The cost is bounded — the tick stays
180
- bounded and fast, and the window is re-evaluated as soon as it goes
181
- ledger-dirty again, which for a live window is continuous — so the exposure
182
- is a future-clocked capture in a window that then goes permanently quiet
183
- never qualifying a threshold. Under-alerting, never a stall or a burst.
177
+ Epoch 1007's per-root map is maintained by the projector rather than this
178
+ helper. It closes the quiet-window gap by letting a hook tick replace only
179
+ the roots it evaluated; scalar-only legacy state still uses ``retain_due``
180
+ and the conservative full/deferred path.
184
181
  """
185
182
  candidates = [value for value in capture_times if value > now]
186
183
  if stored is not None and (retain_due or stored > now):