cribsheet 0.23.0.dev1__py3-none-any.whl → 0.23.0.dev2__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 dataclasses
12
13
  import datetime
13
14
  import os
14
15
  import re
@@ -182,13 +183,20 @@ class Crib:
182
183
  build_embedder(embed_cfg, stored_dim=_stored_dim(store)),
183
184
  store,
184
185
  )
186
+ # The keyword_index / summary_index enrichments, mapped into the store
187
+ # (crib.enrichments): what the BM25 corpus and the alias index read.
188
+ from .enrichments import Enrichments
189
+
190
+ self.enrichments = Enrichments(
191
+ store, self.embedder, lambda p: self.project_paths(p).project_dir
192
+ )
185
193
  self.index = IndexEngine(
186
194
  store,
187
195
  self.embedder,
188
196
  config.chunk.window_words,
189
197
  config.chunk.overlap_words,
190
- keyword_terms=self._keyword_terms,
191
- summary_terms=self._summary_terms,
198
+ keyword_map=self.enrichments.keyword_map,
199
+ alias_vectors=self.enrichments.alias_vectors,
192
200
  )
193
201
  # DESIGN §14: network git is CLI-side (the terminal owns auth) — the
194
202
  # daemon only ever snapshots/reads history locally.
@@ -367,11 +375,16 @@ class Crib:
367
375
  # the notes keyword facet (refresh timers cancelled on stop): elaborate's
368
376
  # content-hash gate is its durable signal, so the catch-up is a cheap no-op
369
377
  # when nothing was lost.
370
- self._spawn_bg(loop, self._describe_backlog())
378
+ self._spawn_bg(loop, self._describe_backlog(), "describe backlog")
371
379
  # Records changed while crib was down (a git pull, another machine's sync):
372
380
  # the watcher only sees edits from now on, and reads refresh lazily.
373
- self._spawn_bg(loop, self._refresh_records_at_start())
374
- self._spawn_bg(loop, self._keyword_backlog())
381
+ self._spawn_bg(loop, self._refresh_records_at_start(), "symbol refresh (startup)")
382
+ self._spawn_bg(loop, self._keyword_backlog(), "keyword backlog")
383
+ # Is the platform delivering file events? (fseventsd can saturate and
384
+ # delay them for minutes.) While it isn't, a catch-up sweep stands in.
385
+ d = self.config.daemon
386
+ self._watcher.start_probe(d.watch_probe_s, d.watch_catchup_s,
387
+ self._catch_up_while_degraded)
375
388
 
376
389
  def _in_repo_store_roots(self) -> dict[str, Path]:
377
390
  """`{project: data root}` for every project adopted into a repo whose
@@ -407,12 +420,19 @@ class Crib:
407
420
  )
408
421
  return True
409
422
 
410
- def _spawn_bg(self, loop: asyncio.AbstractEventLoop, coro: Any) -> None:
423
+ def _spawn_bg(
424
+ self, loop: asyncio.AbstractEventLoop, coro: Any, name: str = "background"
425
+ ) -> None:
411
426
  """Fire-and-forget on the daemon loop, with a strong reference held until done
412
- (asyncio keeps only weak refs — an unreferenced task can be GC'd mid-flight)."""
427
+ (asyncio keeps only weak refs — an unreferenced task can be GC'd mid-flight).
428
+ `name` is how `status` lists it while it runs (crib.diag)."""
429
+ from .diag import DIAG
430
+
431
+ token = DIAG.job(name)
413
432
  t = loop.create_task(coro)
414
433
  self._bg_tasks.add(t)
415
434
  t.add_done_callback(self._bg_tasks.discard)
435
+ t.add_done_callback(lambda _t: DIAG.done(token))
416
436
 
417
437
  async def _on_fs_change(self, project: str, store: str, relpath: str) -> None:
418
438
  pillar = self.pillars.get(store, self.notestore)
@@ -433,9 +453,28 @@ class Crib:
433
453
  crib.watch.RECORD_TIERS): bring the store in line now, rather than at the
434
454
  next read. Reads still refresh, so whichever comes first does the work
435
455
  and the stamps make the other a no-op."""
436
- if facet != "symbol" or project not in self.projects():
456
+ if project not in self.projects():
437
457
  return
438
- await asyncio.to_thread(self._refresh_symbols, project, names)
458
+ if facet == "symbol":
459
+ await asyncio.to_thread(self._refresh_symbols, project, names)
460
+ elif facet in ("keywords", "summary"):
461
+ await asyncio.to_thread(self._refresh_enrichments, project, facet, names)
462
+
463
+ def _refresh_enrichments(self, project: str, facet: str,
464
+ names: list[str] | None) -> None:
465
+ # the BM25 corpus and the alias index fold these in: drop them on change
466
+ if self.enrichments.refresh(project, facet, names):
467
+ self.index.invalidate_caches(project)
468
+
469
+ async def _catch_up_while_degraded(self) -> None:
470
+ """What the watchers would have done, done by sweeping: the stamp-gated
471
+ reconcile (only changed notes are read) and every project's symbol
472
+ refresh. The enrichments refresh on their next read."""
473
+ from .diag import DIAG
474
+
475
+ with DIAG.track("watch catch-up sweep"):
476
+ await self.reconcile_all()
477
+ await self._refresh_records_at_start()
439
478
 
440
479
  def _refresh_symbols(self, project: str, names: list[str] | None = None) -> None:
441
480
  self.code.refresh(project, names)
@@ -519,7 +558,7 @@ class Crib:
519
558
  project,
520
559
  True,
521
560
  None,
522
- "defer",
561
+ self._background_describe("defer"),
523
562
  )
524
563
  except Exception as e: # noqa: BLE001 — per-file batch boundary, see below
525
564
  # OUTER RUNNER (per-file indexing batch): one malformed/unreadable
@@ -548,6 +587,8 @@ class Crib:
548
587
  from .codeindex import SymbolIndex
549
588
  from .genledger import provider_id
550
589
 
590
+ if not self._may_generate(background=True):
591
+ return # [generate] mode: descriptions wait for an explicit index
551
592
  budget = max(0, int(self.config.generate.backlog_budget))
552
593
  provider = provider_id(self.config.generate, "elaborate")
553
594
  pending = attempted = backing_off = 0
@@ -618,7 +659,7 @@ class Crib:
618
659
  the orphan prune (`SectionIndex.prune`) for each label."""
619
660
  if not (
620
661
  self.config.retrieve.keyword_labels or self.config.retrieve.summary_labels
621
- ):
662
+ ) or not self._may_generate(background=True):
622
663
  return
623
664
  for name in self.projects():
624
665
  if self._skip_if_unavailable(self.project_paths(name), "not enriching"):
@@ -683,31 +724,6 @@ class Crib:
683
724
  def notes_dir(self, project: str) -> Path:
684
725
  return self.notestore.dir(project)
685
726
 
686
- def _keyword_terms(
687
- self, project: str, section_hash: str, labels: tuple[str, ...]
688
- ) -> list[str]:
689
- """Per-section keyword_index terms for the given labels — the BM25 feed
690
- (§3.1). Read from the section-addressed TOML store; empty when a section
691
- has no keyword set for a label yet (graceful: BM25 falls back to
692
- body+heading)."""
693
- from .section_index import SectionIndex
694
-
695
- return SectionIndex(
696
- self.project_paths(project).project_dir, "keyword_index"
697
- ).terms_for(section_hash, list(labels))
698
-
699
- def _summary_terms(
700
- self, project: str, section_hash: str, labels: tuple[str, ...]
701
- ) -> list[str]:
702
- """Per-section summary_index rephrasings for the given labels — the dense
703
- alias feed (§3). Read from the section-addressed TOML store; empty when a
704
- section has no summary for a label yet."""
705
- from .section_index import SectionIndex
706
-
707
- return SectionIndex(
708
- self.project_paths(project).project_dir, "summary_index"
709
- ).terms_for(section_hash, list(labels))
710
-
711
727
  def _source_roots(self, project: str) -> "SourceRoots":
712
728
  """Per-project registry of docs indexed in-situ (prefix -> repo root)."""
713
729
  return self.notestore.source_roots(project)
@@ -740,6 +756,7 @@ class Crib:
740
756
  or self.config.retrieve.summary_labels
741
757
  )
742
758
  or self._describe_q is None
759
+ or not self._may_generate(background=True)
743
760
  ):
744
761
  return # describe queue present ⇒ daemon
745
762
  try:
@@ -771,10 +788,6 @@ class Crib:
771
788
  self._kw_timers[key] = loop.call_later(self._KW_SETTLE_S, _fire)
772
789
 
773
790
  # --- tool verbs --------------------------------------------------------
774
- # near-duplicate nudge: a stored note whose probe matches an existing note
775
- # this closely is flagged in the result (the descriptions preach append/edit
776
- # over duplicating; this is what detects it).
777
- DEDUPE_WARN_SCORE = 0.85
778
791
 
779
792
  def project_is_new(self, proj: str) -> bool:
780
793
  """True if `proj` has no notes dir yet (a write would create it)."""
@@ -791,43 +804,106 @@ class Crib:
791
804
  i += 1
792
805
  return f"{slug}-{i}.md"
793
806
 
794
- def _similar(
795
- self, proj: str, content: str, exclude: str, store: str = "notes"
796
- ) -> list[dict[str, Any]]:
797
- """Near-duplicate hints for a just-stored note (excludes the note itself),
798
- probing the SAME pillar it was stored into — a near-duplicate note is
799
- redundancy, a near-duplicate decision forks the graph, and each is a
800
- same-pillar question.
801
-
802
- Blocking (a query embed + a retrieval pass) — callers on the event loop
803
- must `to_thread` it."""
804
- probe = content.strip().splitlines()[0][:200] if content.strip() else ""
805
- if not probe:
806
- return []
807
+ # Write-time warnings (`similar`, Stage E4), measured on the live corpus
808
+ # (1,141 items, 2026-11-13): an item's nearest same-project neighbour sits at
809
+ # body cosine 0.54 (median) to 0.84 (p99), and every pair from 0.94 up was a
810
+ # real duplicate; nearest TITLE cosine 0.32 (median) to 0.53 (p95), and the
811
+ # few pairs with titles >= 0.85 but bodies < 0.80 were true confusables.
812
+ SIMILAR_RELATED = 0.75 # body: listed (no warning)
813
+ SIMILAR_SETTLED = 0.80 # body (or a title past SIMILAR_CONFUSABLE), against
814
+ # a done/declined/parked/superseded item
815
+ SIMILAR_DUPLICATE = 0.90 # body: the same thing again
816
+ SIMILAR_CONFUSABLE = 0.85 # title, with the body below SIMILAR_SETTLED
817
+ _SETTLED_STATES = ("done", "verified", "declined", "parked", "superseded")
818
+ _SIMILAR_KINDS = ("note", "design", "plan")
819
+
820
+ def _similar(self, proj: str, relpath: str, store: str = "notes") -> list[dict[str, Any]]:
821
+ """What a just-written note / decision / plan item is close to, across
822
+ those three kinds, each with a verdict and the verb that answers it:
823
+ `duplicate` (the same thing again: append to or edit that one),
824
+ `confusable` (titles alike, bodies not: say how this one differs),
825
+ `settled` (it is already done / declined / parked / superseded), or
826
+ `related`. From the items' STORED title and body vectors, so the whole
827
+ item is compared, not its first line.
828
+
829
+ Blocking (store reads) — callers on the event loop must `to_thread` it.
830
+ A nudge, never a failure: any error answers []."""
807
831
  try:
808
- hits = self.lookup(probe, project=proj, k=4, store=store)
809
- except Exception: # noqa: BLE001 — a nudge must never fail the store
832
+ return self._similar_rows(proj, relpath, kind_of(store, relpath))
833
+ except Exception: # noqa: BLE001 — a nudge must never fail the write
834
+ return []
835
+
836
+ def _similar_rows(self, proj: str, relpath: str, kind: str) -> list[dict[str, Any]]:
837
+ import numpy as np
838
+
839
+ mine = self.store.items({"project": proj, "kind": kind, "relpath": relpath})
840
+ if not mine:
841
+ return []
842
+ me = next(iter(mine.values()))
843
+ if not me.body_vec or not any(me.body_vec):
810
844
  return []
811
- rows = [
812
- {"relpath": h.relpath, "heading": h.heading, "score": h.score}
813
- for h in hits
814
- if h.relpath != exclude and h.score >= self.DEDUPE_WARN_SCORE
815
- ]
816
- # FACET STATE AT THE CUE (plan-deferral-review.md P2): a probe hit that is
817
- # parked or declined is the answer, not redundancy — "was this already
818
- # planned/parked/declined?" carries the status (and, for plan rows, the
819
- # trigger/why lives one `plan_read` away). Notes have no status.
820
- if store in ("design", "plans") and rows:
821
- graph = self.designs._load_graph(proj)
822
- by_rel = {
823
- n.relpath: n
824
- for n in graph.of_kind("design" if store == "design" else "plan")
825
- }
826
- for r in rows:
827
- n = by_rel.get(r["relpath"])
828
- if n:
829
- r["status"] = n.status
830
- return rows
845
+
846
+ def unit(v: Any) -> Any:
847
+ a = np.asarray(v, dtype=np.float32)
848
+ n = float(np.linalg.norm(a))
849
+ return a / n if n else a
850
+
851
+ body, title = unit(me.body_vec), unit(me.title_vec or me.body_vec)
852
+ # missing links (Stage E5): a decision or plan close to a live decision it
853
+ # doesn't depend on probably builds on it
854
+ my_deps = {e.dst for e in me.edges
855
+ if e.kind == "dep" or e.kind in ("follows", "rests_on", "informed_by")}
856
+ noun = {"design": "design", "plan": "plan"}.get(kind)
857
+ rows: list[dict[str, Any]] = []
858
+ for k in self._SIMILAR_KINDS:
859
+ for it in self.store.items({"project": proj, "kind": k}).values():
860
+ if it.id == me.id or not it.body_vec or not any(it.body_vec):
861
+ continue
862
+ b = float(unit(it.body_vec) @ body)
863
+ t = float(unit(it.title_vec) @ title) if it.title_vec else 0.0
864
+ status = it.facet.get("status")
865
+ # settled first: a twin of something done or declined is answered
866
+ # by that state, not by "merge them"
867
+ if status in self._SETTLED_STATES and (
868
+ b >= self.SIMILAR_SETTLED or t >= self.SIMILAR_CONFUSABLE
869
+ ): # the same thing, or the same title, as finished work
870
+ verdict = "settled"
871
+ elif b >= self.SIMILAR_DUPLICATE:
872
+ verdict = "duplicate"
873
+ elif t >= self.SIMILAR_CONFUSABLE and b < self.SIMILAR_SETTLED:
874
+ verdict = "confusable"
875
+ elif b >= self.SIMILAR_RELATED:
876
+ verdict = "related"
877
+ else:
878
+ continue
879
+ row = {"relpath": it.relpath, "kind": k, "title": it.title,
880
+ **({"status": status} if status else {}),
881
+ "score": round(b, 4), "title_score": round(t, 4),
882
+ "verdict": verdict,
883
+ "next": self._similar_next(verdict, k, it.relpath, status)}
884
+ if (noun and k == "design" and verdict in ("related", "duplicate")
885
+ and status in ("active", "proposed")
886
+ and it.id not in my_deps):
887
+ row["link"] = (f"probably builds on it: {noun}_dep_add "
888
+ f"{relpath} {it.relpath} (as rests_on)")
889
+ rows.append(row)
890
+ rank = {"duplicate": 0, "settled": 1, "confusable": 2, "related": 3}
891
+ rows.sort(key=lambda r: (rank[r["verdict"]], -r["score"]))
892
+ return rows[:5]
893
+
894
+ @staticmethod
895
+ def _similar_next(verdict: str, kind: str, relpath: str, status: str | None) -> str:
896
+ noun = {"note": "note", "design": "design", "plan": "plan"}[kind]
897
+ if verdict == "duplicate":
898
+ return (f"the same thing already exists: {noun}_append / {noun}_edit "
899
+ f"{relpath} instead, and delete this one")
900
+ if verdict == "settled":
901
+ return (f"already {status}: read it ({noun}_read {relpath}) before "
902
+ f"keeping this one")
903
+ if verdict == "confusable":
904
+ return ("titles alike, contents not: retitle this one (or that one) so "
905
+ "the difference shows")
906
+ return f"related: {noun}_read {relpath}"
831
907
 
832
908
  async def store_note(
833
909
  self,
@@ -851,7 +927,7 @@ class Crib:
851
927
  fm["tags"] = tags
852
928
  note = Note(path=self.abspath(proj, relpath), frontmatter=fm, body=content)
853
929
  res = await self._write_note(proj, relpath, note)
854
- similar = await asyncio.to_thread(self._similar, proj, content, relpath)
930
+ similar = await asyncio.to_thread(self._similar, proj, relpath)
855
931
  return {
856
932
  "project": proj,
857
933
  "relpath": relpath,
@@ -1164,9 +1240,13 @@ class Crib:
1164
1240
  f"distinct ids)",
1165
1241
  file=sys.stderr,
1166
1242
  )
1167
- self._spawn_bg(loop, self._reconcile_background(reason))
1243
+ self._spawn_bg(loop, self._reconcile_background(reason),
1244
+ f"reconcile ({reason})" if reason else "reconcile")
1168
1245
 
1169
1246
  async def _reconcile_background(self, reason: str | None = None) -> None:
1247
+ from .diag import DIAG
1248
+
1249
+ DIAG.milestone("reconcile started", reason=reason or "startup")
1170
1250
  try:
1171
1251
  rec = await self.reconcile_all()
1172
1252
  except Exception as e: # noqa: BLE001 — a failed sweep must not kill the daemon
@@ -1174,6 +1254,8 @@ class Crib:
1174
1254
  f"[crib] {reason or 'startup'} reconcile failed: {e}", file=sys.stderr
1175
1255
  )
1176
1256
  return
1257
+ DIAG.milestone("reconcile finished", projects=rec["projects"],
1258
+ changed=rec["changed"], removed=rec["removed"])
1177
1259
  if rec["changed"] or rec["removed"]:
1178
1260
  print(
1179
1261
  f"[crib] startup reconcile: {rec['changed']} updated, "
@@ -1229,7 +1311,8 @@ class Crib:
1229
1311
  async with sem:
1230
1312
  try:
1231
1313
  await asyncio.to_thread(
1232
- self._index_code_file_tracked, root, rel, proj, True
1314
+ self._index_code_file_tracked, root, rel, proj, True,
1315
+ None, self._background_describe("inline"),
1233
1316
  )
1234
1317
  return True
1235
1318
  except Exception: # noqa: BLE001 — the lazy gate backstops
@@ -1534,6 +1617,14 @@ class Crib:
1534
1617
  store=store,
1535
1618
  labels=tags,
1536
1619
  )
1620
+ return self._hits_from(proj, raw, k, dedupe, min_score)
1621
+
1622
+ def _hits_from(
1623
+ self, proj: str, raw: list[Any], k: int, dedupe: str, min_score: float
1624
+ ) -> list[LookupHit]:
1625
+ """Ranked retrieval `Hit`s as `LookupHit`s: below `min_score` dropped,
1626
+ `dedupe`d, each with its section's line span on disk and its markers
1627
+ (taint, index rebuilding), the first `k` kept."""
1537
1628
  # a store wipe this project hasn't been re-swept after: what comes back is
1538
1629
  # incomplete, so every hit says so rather than thin results reading as "all
1539
1630
  # there is" (cleared per project by the recovery sweep)
@@ -1630,6 +1721,7 @@ class Crib:
1630
1721
  facts/decisions, drop deliberation, preserve code verbatim. Thrash-guarded
1631
1722
  (no write if the body is unchanged), marked `source: distilled`, written
1632
1723
  through the version ring so a bad revision is a cheap rollback."""
1724
+ self._require_generation("distill")
1633
1725
  proj = self.resolve_project(project, cwd)
1634
1726
  path = self.abspath(proj, relpath)
1635
1727
  if not path.exists():
@@ -1773,8 +1865,32 @@ class Crib:
1773
1865
  return sorted(out, key=lambda x: -x["symbols"])
1774
1866
 
1775
1867
  def _revalidate(self, proj: str) -> None:
1776
- """Delegate to CodeStore, injecting the pipeline's per-file indexer."""
1777
- self.code.revalidate(proj, self._index_code_file_tracked)
1868
+ """Delegate to CodeStore, injecting the pipeline's per-file indexer. A
1869
+ query finding code changed is background work: it describes only when
1870
+ [generate] mode is "on"."""
1871
+ import functools
1872
+
1873
+ self.code.revalidate(proj, functools.partial(
1874
+ self._index_code_file_tracked,
1875
+ describe_mode=self._background_describe("inline")))
1876
+
1877
+ def _may_generate(self, background: bool) -> bool:
1878
+ """[generate] mode: "on" generates anywhere, "explicit" only for a verb
1879
+ someone called, "off" never."""
1880
+ mode = self.config.generate.resolved_mode()
1881
+ return mode == "on" or (mode == "explicit" and not background)
1882
+
1883
+ def _require_generation(self, verb: str) -> None:
1884
+ if self.config.generate.resolved_mode() == "off":
1885
+ raise CribUserError(
1886
+ f"{verb} needs LLM generation, and [generate] mode is \"off\" in "
1887
+ f"crib's config; set it to \"explicit\" or \"on\" to allow it")
1888
+
1889
+ def _background_describe(self, wanted: str) -> str:
1890
+ """The describe mode for indexing nobody asked for: `wanted` when
1891
+ background generation is allowed, else "none" (structure now, the
1892
+ description left pending)."""
1893
+ return wanted if self._may_generate(background=True) else "none"
1778
1894
 
1779
1895
  def _drop_file(self, proj: str, relpath: str) -> None:
1780
1896
  self.code.drop_file(proj, relpath)
@@ -4279,6 +4395,8 @@ class Crib:
4279
4395
  out["store_stats"] = stats()
4280
4396
  except Exception as e: # noqa: BLE001 — status must still answer
4281
4397
  out["store_stats"] = {"error": str(e)}
4398
+ out["daemon"] = self._daemon_state()
4399
+ out["generation"] = self._generation_state(projects)
4282
4400
  hits = getattr(self.embedder, "hits", None)
4283
4401
  if hits is not None:
4284
4402
  out["embed_cache"] = {
@@ -4287,6 +4405,57 @@ class Crib:
4287
4405
  }
4288
4406
  return out
4289
4407
 
4408
+ def _generation_state(self, projects: list[dict[str, Any]]) -> dict[str, Any]:
4409
+ """[generate] mode, and, unless it is "on", the symbols whose description
4410
+ is waiting for an explicit index (structure saved, description blank)."""
4411
+ mode = self.config.generate.resolved_mode()
4412
+ out: dict[str, Any] = {"mode": mode}
4413
+ if mode != "on":
4414
+ pending: dict[str, int] = {}
4415
+ for row in projects:
4416
+ if not row.get("symbols"):
4417
+ continue
4418
+ try:
4419
+ rows = self.store.facet_values(
4420
+ {"project": row["project"], "kind": "symbol"},
4421
+ ["description", "symbol_content_hash"])
4422
+ except Exception: # noqa: BLE001 — status must still answer
4423
+ continue
4424
+ n = sum(1 for r in rows
4425
+ if r["symbol_content_hash"] and not r["description"])
4426
+ if n:
4427
+ pending[row["project"]] = n
4428
+ if pending:
4429
+ out["pending_descriptions"] = pending
4430
+ out["next"] = ("descriptions are generated only on request in this "
4431
+ "mode: `crib project index` (or code_index) fills them")
4432
+ return out
4433
+
4434
+ def _daemon_state(self) -> dict[str, Any]:
4435
+ """The daemon's own state for `status`: uptime, startup milestones, the
4436
+ background work running now (crib.diag), and the queues behind it."""
4437
+ from .diag import DIAG
4438
+
4439
+ out = DIAG.snapshot()
4440
+ queues: dict[str, int] = {}
4441
+ q = self._describe_q
4442
+ if q is not None:
4443
+ queues["describe_files"] = q.pending_files()
4444
+ queues["describe_symbols"] = q.pending_symbols()
4445
+ if self._kw_timers:
4446
+ queues["keyword_refresh"] = len(self._kw_timers)
4447
+ for label, w in (("note_watch", self._watcher), ("code_watch", self._code_watcher)):
4448
+ if w is not None:
4449
+ n = w.pending()
4450
+ if n:
4451
+ queues[label] = n
4452
+ out["queues"] = queues
4453
+ if self._watcher is not None or self._code_watcher is not None:
4454
+ out["watchers"] = {
4455
+ label: w.health() for label, w in
4456
+ (("notes", self._watcher), ("code", self._code_watcher)) if w is not None}
4457
+ return out
4458
+
4290
4459
  def project_forget(
4291
4460
  self,
4292
4461
  project: str | None = None,
@@ -4442,6 +4611,84 @@ class Crib:
4442
4611
  lang=lang,
4443
4612
  )
4444
4613
 
4614
+ def project_doctor(
4615
+ self, project: str | None = None, cwd: Path | None = None
4616
+ ) -> dict[str, Any]:
4617
+ """What in this project needs attention, each finding naming the verb
4618
+ that resolves it (crib.doctor). Report-only: nothing is changed."""
4619
+ from .doctor import diagnose
4620
+
4621
+ return diagnose(self, self.resolve_project(project, cwd))
4622
+
4623
+ # The pillars one cross-kind lookup searches, as (kind, store) pairs.
4624
+ _LOOKUP_PILLARS = (("note", "notes"), ("design", "design"), ("plan", "plans"),
4625
+ ("learning", "learnings"))
4626
+
4627
+ def lookup_all(
4628
+ self,
4629
+ query: str,
4630
+ project: str | None = None,
4631
+ k: int = 8,
4632
+ kinds: list[str] | None = None,
4633
+ status: list[str] | None = None,
4634
+ cwd: Path | None = None,
4635
+ ) -> list[dict[str, Any]]:
4636
+ """One lookup across kinds (notes, decisions, plans, learnings). Each
4637
+ pillar's candidates are retrieved with its own calibration and pooled
4638
+ BEFORE reranking; the cross-encoder then judges the merged pool once
4639
+ (its query/passage score is the one scale every pillar shares). Each
4640
+ hit carries its `kind` and, for a decision or plan, its `status`;
4641
+ `kinds` and `status` filter."""
4642
+ from .codequery import check_k, check_query
4643
+
4644
+ check_query(query)
4645
+ check_k(k)
4646
+ proj = self.resolve_project(project, cwd)
4647
+ wanted = [(kd, st) for kd, st in self._LOOKUP_PILLARS
4648
+ if not kinds or kd in kinds]
4649
+ if kinds and not wanted:
4650
+ raise CribUserError(
4651
+ f"unknown kinds {kinds}: use any of "
4652
+ f"{[kd for kd, _ in self._LOOKUP_PILLARS]}")
4653
+ r = self.config.retrieve
4654
+ vec = embed_query_batch(self.embedder, [query])[0]
4655
+ topn = max(k * 3, 30)
4656
+ pool: list[Any] = []
4657
+ for _kind, store in wanted:
4658
+ pool += self._retrieve(
4659
+ proj, query, vec, topn, r.hybrid, False,
4660
+ tuple(r.keyword_labels), r.keyword_weight,
4661
+ tuple(r.summary_labels), r.summary_weight,
4662
+ hint_weight=r.hint_weight, store=store)
4663
+ pool.sort(key=lambda h: -h.score) # hybrid order, then
4664
+ if r.rerank:
4665
+ pool = self._rerank(query, pool) # one judge for every pillar
4666
+ kind_of_store = {st: kd for kd, st in self._LOOKUP_PILLARS}
4667
+ graph = None
4668
+ out: list[dict[str, Any]] = []
4669
+ for h in self._hits_from(proj, pool, len(pool), "section", 0.0):
4670
+ row = {"kind": kind_of_store.get(h.store, h.store), **dataclasses.asdict(h)}
4671
+ if row["kind"] in ("design", "plan"):
4672
+ graph = graph or self.designs._load_graph(proj)
4673
+ node = next((n for n in graph.of_kind(row["kind"])
4674
+ if n.relpath == h.relpath), None)
4675
+ row["status"] = node.status if node is not None else None
4676
+ if status and row.get("status") not in status:
4677
+ continue
4678
+ out.append(row)
4679
+ if len(out) >= k:
4680
+ break
4681
+ return out
4682
+
4683
+ def project_related(
4684
+ self, ref: str, k: int = 3, project: str | None = None,
4685
+ cwd: Path | None = None,
4686
+ ) -> dict[str, Any]:
4687
+ """One item and what surrounds it, across kinds (crib.related)."""
4688
+ from .related import related
4689
+
4690
+ return related(self, self.resolve_project(project, cwd), ref, k)
4691
+
4445
4692
  def learning_report(
4446
4693
  self,
4447
4694
  project: str | None = None,
@@ -4511,16 +4758,18 @@ class Crib:
4511
4758
  proj, title, content, deps, sources, proposed,
4512
4759
  _kinded(follows, rests_on, informed_by),
4513
4760
  )
4514
- similar = await asyncio.to_thread(
4515
- self._similar, proj, content, out["relpath"], "design"
4516
- )
4761
+ similar = await asyncio.to_thread(self._similar, proj, out["relpath"], "design")
4517
4762
  return {**out, "similar": similar}
4518
4763
 
4519
4764
  def design_read(
4520
4765
  self, ref: str, project: str | None = None, cwd: Path | None = None
4521
4766
  ) -> dict[str, Any]:
4522
- """A decision's dossier: body, status, annotated edges, taint + chains."""
4523
- return self.designs.design_read(self.resolve_project(project, cwd), ref)
4767
+ """A decision's dossier: body, status, annotated edges, taint + chains,
4768
+ and `suggested_deps`: live decisions it is close to but doesn't depend
4769
+ on (see `_similar`)."""
4770
+ proj = self.resolve_project(project, cwd)
4771
+ out = self.designs.design_read(proj, ref)
4772
+ return {**out, "suggested_deps": self._suggested_deps(proj, out, "design")}
4524
4773
 
4525
4774
  async def design_edit(
4526
4775
  self,
@@ -4690,14 +4939,67 @@ class Crib:
4690
4939
  self, relpath: str, project: str | None = None, cwd: Path | None = None
4691
4940
  ) -> dict[str, Any]:
4692
4941
  """A doc's sections + hashes + existing citations + the extraction
4693
- procedure — the read that precedes an LLM-driven design import."""
4694
- return self.designs.design_import(self.resolve_project(project, cwd), relpath)
4942
+ procedure — the read that precedes an LLM-driven design import. Each
4943
+ section names the existing decisions `closest` to it (Stage E7)."""
4944
+ proj = self.resolve_project(project, cwd)
4945
+ return self._import_matches(proj, self.designs.design_import(proj, relpath),
4946
+ "design")
4695
4947
 
4696
4948
  def plan_import(
4697
4949
  self, relpath: str, project: str | None = None, cwd: Path | None = None
4698
4950
  ) -> dict[str, Any]:
4699
4951
  """The same for the plan facet (actionable work rather than decisions)."""
4700
- return self.designs.plan_import(self.resolve_project(project, cwd), relpath)
4952
+ proj = self.resolve_project(project, cwd)
4953
+ return self._import_matches(proj, self.designs.plan_import(proj, relpath),
4954
+ "plan")
4955
+
4956
+ def _import_matches(self, proj: str, out: dict[str, Any],
4957
+ kind: str) -> dict[str, Any]:
4958
+ """Each imported section's `closest` existing items of `kind` (body
4959
+ cosine >= SIMILAR_RELATED, best 3), so an extraction appends to or
4960
+ supersedes what is already there instead of adding a near-duplicate.
4961
+ Section text comes from the same split the import hashed; items from
4962
+ their stored vectors. Best-effort: a doc that can't be read answers as
4963
+ before."""
4964
+ import numpy as np
4965
+
4966
+ from .chunk import chunk_note
4967
+ from .embed import embed_batch
4968
+
4969
+ doc = out.get("relpath", "")
4970
+ try:
4971
+ _, body = notes.parse(self.designs._doc_abspath(proj, doc).read_text(), doc)
4972
+ except (OSError, ValueError, UnicodeDecodeError, notes.NoteParseError):
4973
+ return out
4974
+ text_by_source: dict[str, str] = {}
4975
+ for c in chunk_note(proj, doc, "", body):
4976
+ if not c.window_idx:
4977
+ key = section_key(c.heading_path, c.occurrence)
4978
+ text_by_source[f"{doc}#{key}" if key else doc] = c.section_text
4979
+ items = [it for it in self.store.items({"project": proj, "kind": kind}).values()
4980
+ if it.body_vec and any(it.body_vec)]
4981
+ rows = [s for s in out.get("sections", []) if text_by_source.get(s["source"])]
4982
+ if not items or not rows:
4983
+ return out
4984
+ M = np.asarray([it.body_vec for it in items], dtype=np.float32)
4985
+ M /= np.linalg.norm(M, axis=1, keepdims=True)
4986
+ Q = np.asarray(embed_batch(self.embedder,
4987
+ [text_by_source[s["source"]] for s in rows]),
4988
+ dtype=np.float32)
4989
+ S = Q @ M.T
4990
+ noun = "design" if kind == "design" else "plan"
4991
+ for row, sims in zip(rows, S):
4992
+ best = [j for j in np.argsort(-sims)[:3] if sims[j] >= self.SIMILAR_RELATED]
4993
+ row["closest"] = [{
4994
+ "relpath": items[j].relpath, "title": items[j].title,
4995
+ **({"status": items[j].facet["status"]} if items[j].facet.get("status") else {}),
4996
+ "score": round(float(sims[j]), 4),
4997
+ "next": (f"already there: cite this section on it ({noun}_edit "
4998
+ f"{items[j].relpath} with sources) rather than adding one"
4999
+ if sims[j] >= self.SIMILAR_DUPLICATE else
5000
+ f"close: {noun}_read {items[j].relpath} before adding")}
5001
+ for j in best]
5002
+ return out
4701
5003
 
4702
5004
  def design_tree(
4703
5005
  self,
@@ -4759,9 +5061,11 @@ class Crib:
4759
5061
  informed_by: list[str] | None = None,
4760
5062
  ) -> dict[str, Any]:
4761
5063
  """Add one plan item, or a whole batch (`items`), ranked at the end unless
4762
- after/before place them."""
4763
- return await self.designs.plan_add(
4764
- self.resolve_project(project, cwd),
5064
+ after/before place them. A single item answers with `similar` (what it
5065
+ is close to, with a verdict: see `_similar`)."""
5066
+ proj = self.resolve_project(project, cwd)
5067
+ out = await self.designs.plan_add(
5068
+ proj,
4765
5069
  title,
4766
5070
  content,
4767
5071
  deps,
@@ -4771,6 +5075,10 @@ class Crib:
4771
5075
  sources,
4772
5076
  _kinded(follows, rests_on, informed_by),
4773
5077
  )
5078
+ if not items and out.get("relpath"):
5079
+ out["similar"] = await asyncio.to_thread(
5080
+ self._similar, proj, out["relpath"], "plans")
5081
+ return out
4774
5082
 
4775
5083
  async def plan_status(
4776
5084
  self, ref: str, status: str, project: str | None = None, cwd: Path | None = None
@@ -4817,7 +5125,7 @@ class Crib:
4817
5125
  `plan_review_apply` applies the batch."""
4818
5126
  return await self.designs.plan_review(
4819
5127
  self.resolve_project(project, cwd),
4820
- probe=lambda p, text, exclude: self._similar(p, text, exclude, "plans"),
5128
+ probe=lambda p, text, exclude: self._similar(p, exclude, "plans"),
4821
5129
  )
4822
5130
 
4823
5131
  async def plan_review_apply(
@@ -4835,8 +5143,21 @@ class Crib:
4835
5143
  self, ref: str, project: str | None = None, cwd: Path | None = None
4836
5144
  ) -> dict[str, Any]:
4837
5145
  """A plan item's dossier: body, status, annotated edges, derived blocking
4838
- + taint — the plan-side design_read."""
4839
- return self.designs.plan_read(self.resolve_project(project, cwd), ref)
5146
+ + taint — the plan-side design_read — and `suggested_deps` (see
5147
+ `design_read`)."""
5148
+ proj = self.resolve_project(project, cwd)
5149
+ out = self.designs.plan_read(proj, ref)
5150
+ return {**out, "suggested_deps": self._suggested_deps(proj, out, "plans")}
5151
+
5152
+ def _suggested_deps(self, proj: str, read: dict[str, Any],
5153
+ store: str) -> list[dict[str, Any]]:
5154
+ """The `link` rows of `_similar` for a read item: live decisions it is
5155
+ close to and doesn't declare."""
5156
+ rel = read.get("relpath")
5157
+ if not rel:
5158
+ return []
5159
+ return [{k: r[k] for k in ("relpath", "title", "status", "score", "link")
5160
+ if k in r} for r in self._similar(proj, rel, store) if "link" in r]
4840
5161
 
4841
5162
  async def plan_edit(
4842
5163
  self,
@@ -5127,6 +5448,11 @@ class Crib:
5127
5448
  The per-section mop-up sweeps the bulk-missed tail per facet (plain-text
5128
5449
  `parse_terms`, the proven path). Bounded-concurrent, per-call timeout,
5129
5450
  error-isolated; off the write path."""
5451
+ if not self._may_generate(background):
5452
+ if background:
5453
+ return {"project": proj, "written": 0, "skipped": 0,
5454
+ "pending": "generation waits for an explicit verb"}
5455
+ self._require_generation(purpose)
5130
5456
  from .generate import (
5131
5457
  GenerationError,
5132
5458
  agenerate,