cribsheet 0.28.0.dev3__py3-none-any.whl → 0.28.0.dev4__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.
crib/app.py CHANGED
@@ -9,6 +9,7 @@ from __future__ import annotations
9
9
 
10
10
  import asyncio
11
11
  import contextlib
12
+ import contextvars
12
13
  import functools
13
14
  import dataclasses
14
15
  import datetime
@@ -35,6 +36,7 @@ from .chunk import (
35
36
  )
36
37
  from .claudemem import MemoryBindings
37
38
  from .codeindexer import CodeIndexer
39
+ from .diag import DIAG
38
40
  from .codequery import CodeQuery
39
41
  from .codestore import CodeStore, StoreCode
40
42
  from .codestore import format_sweep
@@ -254,9 +256,27 @@ class Crib:
254
256
  # (`crib facets sync`) is PENDING: no store, not indexed or watched; its
255
257
  # verbs refuse with the reason.
256
258
  self.pending_facets: dict[str, str] = store.facet_pending()
259
+ if self.pending_facets and paths.root is not None:
260
+ # Confined mode: the store is a disposable cache rebuilt from the
261
+ # root, and the facets come from the root's (trusted) config, so
262
+ # conform it here rather than leave a bundle's routines/agents
263
+ # unlisted until someone runs `facets sync`. Never drops a facet.
264
+ try:
265
+ store.facet_sync(drop=False)
266
+ self.pending_facets = store.facet_pending()
267
+ except Exception as e: # noqa: BLE001 — stays pending, verbs say why
268
+ print(f"[crib] confined: facet sync skipped: {e}", file=sys.stderr)
257
269
  # which projects this instance may write (crib/access.py; None = all)
258
270
  self.access = WriteAccess(config.writable, read_only=paths.in_context)
259
271
  self._sweep_warned: set[str] = set() # scheduled-delete failures, reported once
272
+ # Scheduled deletes: each transient project's expiry, read from its stub
273
+ # into an in-memory queue (the stubs are the truth: scanned once at the
274
+ # sweeper's start); the sweeper waits on the soonest, and a stub change
275
+ # (the watcher, or a create/rename here) wakes it to wait again.
276
+ from . import expiry as _expiry
277
+
278
+ self._expiry = _expiry.ExpiryTable()
279
+ self._expiry_wake: asyncio.Event | None = None
260
280
  self.pillars: dict[str, NoteStore] = {
261
281
  spec.name: NoteStore(
262
282
  paths, store, self.index, self.versions, self.project_paths, spec,
@@ -396,6 +416,7 @@ class Crib:
396
416
  self._in_root(self._in_repo_store_roots()),
397
417
  on_records=self._on_record_change,
398
418
  mapped=self._in_root(self._mapped_facet_roots()),
419
+ on_stub=self._on_stub_change,
399
420
  )
400
421
  self._watcher.start()
401
422
  # Code watcher — reindexes source on edit (notes-watcher reloads notes,
@@ -433,7 +454,8 @@ class Crib:
433
454
  # the watcher only sees edits from now on, and reads refresh lazily.
434
455
  self._spawn_bg(loop, self._refresh_records_at_start(), "symbol refresh (startup)")
435
456
  self._spawn_bg(loop, self._keyword_backlog(), "keyword backlog")
436
- self._spawn_bg(loop, self._transient_sweeper(), "transient expiry")
457
+ # resident: status shows its next scheduled delete instead (next_delete)
458
+ self._spawn_bg(loop, self._transient_sweeper(), "transient expiry", listed=False)
437
459
  # Is the platform delivering file events? (fseventsd can saturate and
438
460
  # delay them for minutes.) While it isn't, a catch-up sweep stands in.
439
461
  d = self.config.daemon
@@ -616,18 +638,25 @@ class Crib:
616
638
  return True
617
639
 
618
640
  def _spawn_bg(
619
- self, loop: asyncio.AbstractEventLoop, coro: Any, name: str = "background"
641
+ self, loop: asyncio.AbstractEventLoop, coro: Any, name: str = "background",
642
+ listed: bool = True,
620
643
  ) -> None:
621
644
  """Fire-and-forget on the daemon loop, with a strong reference held until done
622
645
  (asyncio keeps only weak refs — an unreferenced task can be GC'd mid-flight).
623
- `name` is how `status` lists it while it runs (crib.diag)."""
646
+ `name` is how `status` lists it while it runs (crib.diag); a resident
647
+ loop that runs for the daemon's whole life (`listed=False`) isn't
648
+ "running" anything, and reports itself its own way."""
624
649
  from .diag import DIAG
625
650
 
626
- token = DIAG.job(name)
627
- t = loop.create_task(coro)
651
+ ctx = contextvars.copy_context()
652
+ token = DIAG.job(name) if listed else None
653
+ if token is not None:
654
+ ctx.run(DIAG.bind, token) # the task reports progress on its own row
655
+ t = loop.create_task(coro, context=ctx)
628
656
  self._bg_tasks.add(t)
629
657
  t.add_done_callback(self._bg_tasks.discard)
630
- t.add_done_callback(lambda _t: DIAG.done(token))
658
+ if token is not None:
659
+ t.add_done_callback(lambda _t: DIAG.done(token))
631
660
 
632
661
  async def _on_fs_change(self, project: str, store: str, relpath: str) -> None:
633
662
  if (spec := facets.by_store(store)) is not None and spec.noun in self.pending_facets:
@@ -678,6 +707,9 @@ class Crib:
678
707
  with DIAG.track("watch catch-up sweep"):
679
708
  await self.reconcile_all()
680
709
  await self._refresh_records_at_start()
710
+ if self._expiry_wake is not None: # stub changes may have been missed
711
+ self._sync_expiry_all()
712
+ self._expiry_wake.set()
681
713
 
682
714
  def _refresh_symbols(self, project: str, names: list[str] | None = None) -> None:
683
715
  self.code.refresh(project, names)
@@ -826,10 +858,13 @@ class Crib:
826
858
  break
827
859
  attempted += 1
828
860
  rel = target.split(":", 1)[1]
861
+ DIAG.progress(f"{name}: {rel} ({attempted} of at most {budget} "
862
+ f"files; {pending} waiting)")
829
863
  try: # inline: describe now, no queue — per-file boundary
830
- await asyncio.to_thread(
831
- self._index_code_file_tracked, root, rel, name, True
832
- )
864
+ with DIAG.labelled(f"{name}: {rel}"):
865
+ await asyncio.to_thread(
866
+ self._index_code_file_tracked, root, rel, name, True
867
+ )
833
868
  except Exception as e: # noqa: BLE001 — see comment below
834
869
  print(
835
870
  f"[crib] enrichment catch-up: skipped {rel!r}: {e}",
@@ -871,6 +906,7 @@ class Crib:
871
906
  continue # read-only here: its enrichment tiers aren't ours to write
872
907
  if self._skip_if_unavailable(self.project_paths(name), "not enriching"):
873
908
  continue
909
+ DIAG.progress(name)
874
910
  try:
875
911
  # one combined pass, all facets; background: the ledger may skip
876
912
  await self.enrich(project=name, background=True)
@@ -3783,6 +3819,9 @@ class Crib:
3783
3819
  pcfg.transient, pcfg.expires = True, until
3784
3820
  pcfg.save(pdir / ".cribproject")
3785
3821
  self.project_paths.invalidate(name)
3822
+ if transient: # scheduled now; the watcher would see the stub too
3823
+ with contextlib.suppress(Exception): # never fails the create
3824
+ await self._on_stub_change(name)
3786
3825
  return {
3787
3826
  "project": name,
3788
3827
  "project_created": True,
@@ -3809,55 +3848,108 @@ class Crib:
3809
3848
  return False
3810
3849
  return bool(pcfg.transient) and ignore == "*" and pcfg.host == claudemem.hostslug()
3811
3850
 
3812
- def expired_transients(self, now: datetime.datetime | None = None) -> list[str]:
3813
- """The transient projects due for their scheduled delete: discardable
3814
- (see `_discardable`) and past `expires`."""
3851
+ def _expiry_at(self, project: str) -> float | None:
3852
+ """When `project` is due for its scheduled delete (epoch seconds), read
3853
+ from its stub, freshly (the cached paths are dropped first, so a change
3854
+ no watcher event reported is still seen): a discardable transient with
3855
+ an `expires`; else None."""
3815
3856
  from . import expiry
3816
3857
 
3817
- due = []
3818
- for name in self.projects():
3858
+ self.project_paths.invalidate(project)
3859
+ try:
3860
+ pp = self.project_paths(project)
3861
+ except Exception: # noqa: BLE001 — an unreadable stub is not ours to delete
3862
+ return None
3863
+ if not (pp.transient and pp.expires) or not self._discardable(project):
3864
+ return None
3865
+ at = expiry.when(pp.expires)
3866
+ return at.timestamp() if at is not None else None
3867
+
3868
+ def _next_delete(self) -> dict[str, Any]:
3869
+ """The sweeper's queue for `status`: the soonest scheduled delete
3870
+ (project, when, in how long), and how many are scheduled; empty when
3871
+ none is."""
3872
+ nxt = self._expiry.expiry_next()
3873
+ if nxt is None:
3874
+ return {"scheduled": 0}
3875
+ project, at = nxt
3876
+ when = datetime.datetime.fromtimestamp(at, datetime.UTC)
3877
+ return {
3878
+ "project": project,
3879
+ "at": when.isoformat(timespec="seconds"),
3880
+ "in_s": round(max(0.0, at - time.time()), 1),
3881
+ "scheduled": len(self._expiry),
3882
+ }
3883
+
3884
+ def _sync_expiry_all(self) -> None:
3885
+ """Rebuild the queue from every stub (the sweeper's start, and the
3886
+ watch catch-up while events aren't arriving)."""
3887
+ rows = {n: at for n in self.projects() if (at := self._expiry_at(n)) is not None}
3888
+ self._expiry.expiry_replace(rows)
3889
+
3890
+ async def _on_stub_change(self, project: str) -> None:
3891
+ """A stub was created, rewritten or deleted: re-read its expiry and wake
3892
+ the sweeper to wait on the (possibly new) soonest one."""
3893
+ self._expiry.expiry_set(project, self._expiry_at(project))
3894
+ if self._expiry_wake is not None:
3895
+ self._expiry_wake.set()
3896
+
3897
+ async def _transient_sweeper(self, retry_s: float = 3600.0,
3898
+ max_wait_s: float = 3600.0) -> None:
3899
+ """The daemon's scheduled deletes of expired transient projects: wait
3900
+ until the soonest expiry, delete what is due, repeat. A stub change
3901
+ wakes the wait. Each wait is capped at `max_wait_s`: the loop's clock
3902
+ doesn't advance while a laptop sleeps and the expiry is wall-clock, and
3903
+ a stub change the watcher missed is bounded too; a capped wake only
3904
+ re-reads the queue, it scans nothing. Each due project's stub is
3905
+ re-read first, so an extension made anywhere is honoured; a failed
3906
+ delete is retried after `retry_s`, and a failed pass (a store error)
3907
+ backs off and carries on. Runs only alongside the watchers (the daemon
3908
+ starts both); not in confined mode (a bundle's lifetime is the
3909
+ caller's, and its overlay is discarded with it)."""
3910
+ if self.paths.root is not None:
3911
+ return
3912
+ self._expiry_wake = wake = asyncio.Event()
3913
+ self._sync_expiry_all()
3914
+ failed = False
3915
+ while True:
3916
+ wake.clear() # before reading the queue: a change after this wakes us
3819
3917
  try:
3820
- pp = self.project_paths(name)
3821
- except Exception: # noqa: BLE001 — an unreadable stub is not ours to delete
3918
+ timeout = await self._sweep_due(retry_s, max_wait_s)
3919
+ failed = False
3920
+ except Exception as e: # noqa: BLE001 — the sweeper never dies
3921
+ if not failed: # once per run of failures
3922
+ print(f"[crib] scheduled-delete pass failed: {e}", file=sys.stderr)
3923
+ failed = True
3924
+ timeout = min(60.0, max_wait_s)
3925
+ if timeout == 0.0 and not wake.is_set():
3926
+ continue # something came due while we deleted
3927
+ try:
3928
+ await asyncio.wait_for(wake.wait(), timeout)
3929
+ except TimeoutError:
3930
+ pass
3931
+
3932
+ async def _sweep_due(self, retry_s: float, max_wait_s: float) -> float:
3933
+ """One pass: delete every due project; how long to wait for the next."""
3934
+ now = time.time()
3935
+ for name in self._expiry.expiry_due(now):
3936
+ at = self._expiry_at(name)
3937
+ if at is None or at > now: # extended, or no longer transient
3938
+ self._expiry.expiry_set(name, at)
3822
3939
  continue
3823
- if pp.transient and expiry.due(pp.expires, now) and self._discardable(name):
3824
- due.append(name)
3825
- return due
3826
-
3827
- async def delete_expired_transients(
3828
- self, now: datetime.datetime | None = None
3829
- ) -> list[str]:
3830
- """Delete each of `expired_transients` through the ordinary delete path
3831
- (index rows, vectors, stamps, bindings, files; no .trash). One that
3832
- can't be deleted is reported once and retried next sweep."""
3833
- deleted = []
3834
- for name in self.expired_transients(now):
3835
3940
  try:
3836
3941
  await self.project_delete(project=name, force=True)
3837
- deleted.append(name)
3942
+ self._expiry.expiry_set(name, None)
3838
3943
  except Exception as e: # noqa: BLE001 — one project never stops the sweep
3944
+ self._expiry.expiry_set(name, now + retry_s)
3839
3945
  if name not in self._sweep_warned: # once per project
3840
3946
  self._sweep_warned.add(name)
3841
3947
  print(f"[crib] transient {name!r} not deleted yet: {e}",
3842
3948
  file=sys.stderr)
3843
- return deleted
3844
-
3845
- async def _transient_sweeper(self, every_s: float = 300.0) -> None:
3846
- """The daemon's scheduled deletes: expired transient projects, and (on
3847
- the trusted side) expired registered bundles. In confined mode neither:
3848
- a bundle's lifetime belongs to the trusted side."""
3849
- from . import bundle as bundles
3850
-
3851
- if self.paths.root is not None:
3852
- return
3853
- while True:
3854
- await self.delete_expired_transients()
3855
- try:
3856
- for gone in await asyncio.to_thread(bundles.sweep, self.paths):
3857
- print(f"[crib] expired bundle deleted: {gone}", file=sys.stderr)
3858
- except Exception as e: # noqa: BLE001 — a sweep never kills the daemon
3859
- print(f"[crib] bundle sweep failed: {e}", file=sys.stderr)
3860
- await asyncio.sleep(every_s)
3949
+ nxt = self._expiry.expiry_next()
3950
+ if nxt is None:
3951
+ return max_wait_s
3952
+ return min(max(0.0, nxt[1] - time.time()), max_wait_s)
3861
3953
 
3862
3954
  def _pillar_note_count(self, pp: ProjectPaths) -> int:
3863
3955
  """*.md count across every pillar of a project (delete/rename reports)."""
@@ -4335,6 +4427,9 @@ class Crib:
4335
4427
  for r in self._project_refs(p)
4336
4428
  if r.get("project") == old
4337
4429
  ]
4430
+ for p in (old, new): # a transient's schedule moves with its stub
4431
+ with contextlib.suppress(Exception):
4432
+ await self._on_stub_change(p)
4338
4433
  return {
4339
4434
  "project": new,
4340
4435
  "from": old,
@@ -5328,6 +5423,8 @@ class Crib:
5328
5423
  except Exception as e: # noqa: BLE001 — status must still answer
5329
5424
  out["store_stats"] = {"error": str(e)}
5330
5425
  out["daemon"] = self._daemon_state()
5426
+ if self._expiry_wake is not None: # the scheduled-delete sweeper runs
5427
+ out["next_delete"] = self._next_delete()
5331
5428
  out["generation"] = self._generation_state(projects)
5332
5429
  hits = getattr(self.embedder, "hits", None)
5333
5430
  if hits is not None:
@@ -6265,6 +6362,7 @@ class Crib:
6265
6362
  done: dict[str, set[str]] = {f["label"]: set() for f in facets} # label → shs
6266
6363
  tag = f"{purpose} {'+'.join(f['label'] for f in facets)}"
6267
6364
  mode = "bulk+mop-up" if gen.bulk else "per-section"
6365
+ DIAG.progress(f"{proj}: {total} sections to generate ({purpose})")
6268
6366
  print(
6269
6367
  f"[{tag}] {total} sections to generate ({mode}; skipped {skipped} "
6270
6368
  f"cached; concurrency {gen.concurrency}, timeout {gen.timeout:g}s)",
@@ -6390,16 +6488,18 @@ class Crib:
6390
6488
  user = "\n\n".join(f"<<< SECTION: {t[2]} >>>\n{t[3]}" for t in batch)
6391
6489
  try:
6392
6490
  async with sem:
6393
- data = await agenerate_structured(
6394
- gen,
6395
- bulk_system,
6396
- user,
6397
- bulk_schema,
6398
- purpose=purpose,
6399
- schema_name="emit_terms",
6400
- schema_description="Per-section search terms for the document.",
6401
- timeout=gen.timeout,
6402
- )
6491
+ with DIAG.labelled(f"{proj}: {rp}"):
6492
+ data = await agenerate_structured(
6493
+ gen,
6494
+ bulk_system,
6495
+ user,
6496
+ bulk_schema,
6497
+ purpose=purpose,
6498
+ schema_name="emit_terms",
6499
+ schema_description=(
6500
+ "Per-section search terms for the document."),
6501
+ timeout=gen.timeout,
6502
+ )
6403
6503
  except Exception as e: # noqa: BLE001 — bulk fails → mop-up covers it
6404
6504
  print(
6405
6505
  f"[{tag}] bulk ERR {rp} ({len(batch)} sec) — "
@@ -6425,6 +6525,8 @@ class Crib:
6425
6525
  if terms:
6426
6526
  _record(facet, tgt[0], tgt[1], tgt[2], terms)
6427
6527
  counters["bulk_docs"] += 1
6528
+ DIAG.progress(f"{proj}: {counters['bulk_docs']}/{len(batches)} notes "
6529
+ f"({purpose})")
6428
6530
  got = sum(
6429
6531
  1 for t in batch if all(t[0] in done[f["label"]] for f in t[4])
6430
6532
  )