cribsheet 0.28.0.dev1__py3-none-any.whl → 0.28.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/__main__.py CHANGED
@@ -3,7 +3,7 @@ stable, PATH-independent way to re-invoke the CLI (DESIGN §14)."""
3
3
 
4
4
  import sys
5
5
 
6
- from .cli import main
6
+ from .entry import main # applies --root/--store/--writable before crib loads
7
7
 
8
8
  if __name__ == "__main__":
9
9
  sys.exit(main())
crib/access.py CHANGED
@@ -4,7 +4,7 @@ An instance can be told that only some projects are writable: `writable = [...]`
4
4
  in config.toml, `$CRIB_WRITABLE` (comma-separated, wins over the file), or the
5
5
  global `--writable` CLI flag. Every other project is READ-ONLY for that
6
6
  instance: reads are untouched, writes are refused with the reason. Unset means
7
- every project is writable (the default, and every instance before this).
7
+ every project is writable (the default).
8
8
 
9
9
  This is how an agent can be handed several projects (an overlay copy and the
10
10
  projects it needs for context) with writing confined to the copy. It is enforced
@@ -20,7 +20,7 @@ overlays", part 5.
20
20
  from __future__ import annotations
21
21
 
22
22
  import os
23
- from collections.abc import Iterable
23
+ from collections.abc import Callable, Iterable
24
24
 
25
25
  from .errors import CribUserError
26
26
 
@@ -32,16 +32,29 @@ class ReadOnlyProject(CribUserError):
32
32
 
33
33
 
34
34
  class WriteAccess:
35
- """The writable-project allowlist: None allows every project."""
35
+ """The writable-project allowlist: None allows every project. A project
36
+ `read_only` says is read-only by LOCATION (a bundle's context projects,
37
+ crib.paths.Paths.in_context) is refused whatever the allowlist says."""
36
38
 
37
- def __init__(self, writable: Iterable[str] | None = None) -> None:
39
+ def __init__(self, writable: Iterable[str] | None = None,
40
+ read_only: Callable[[str], bool] | None = None) -> None:
38
41
  self.writable = frozenset(writable) if writable is not None else None
42
+ self._read_only = read_only
43
+
44
+ def _located_read_only(self, project: str | None) -> bool:
45
+ return bool(project) and self._read_only is not None and self._read_only(project)
39
46
 
40
47
  def allows(self, project: str | None) -> bool:
48
+ if self._located_read_only(project):
49
+ return False
41
50
  return self.writable is None or (project or "") in self.writable
42
51
 
43
52
  def require(self, project: str | None, what: str = "write") -> None:
44
53
  """Refuse `what` on `project` unless this instance may write it."""
54
+ if self._located_read_only(project):
55
+ raise ReadOnlyProject(
56
+ f"{what} refused: project {project!r} is a read-only context "
57
+ "project (config `context_dir`). Reads still work.")
45
58
  if self.writable is None or (project or "") in self.writable:
46
59
  return
47
60
  named = ", ".join(sorted(self.writable)) or "none"
crib/app.py CHANGED
@@ -22,6 +22,7 @@ from dataclasses import dataclass, replace
22
22
  from pathlib import Path
23
23
  from typing import Any, Callable
24
24
 
25
+ from .bundle import VECTORS_FILE
25
26
  from .access import WriteAccess
26
27
  from . import __version__, claudemem, facets, notes
27
28
  from .chunk import (
@@ -183,33 +184,11 @@ def _kinded(
183
184
  return out or None
184
185
 
185
186
 
186
- _DURATION = {"s": 1, "m": 60, "h": 3600, "d": 86400}
187
-
188
-
189
- def _expiry(spec: str) -> str:
190
- """`expires` as an ISO-8601 UTC time: an ISO time is taken as given (UTC
191
- if it names no zone), a duration (`90s`, `30m`, `2h`, `1d`) counts from now."""
192
- spec = spec.strip()
193
- if spec and spec[-1] in _DURATION and spec[:-1].isdigit():
194
- at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
195
- seconds=int(spec[:-1]) * _DURATION[spec[-1]])
196
- else:
197
- try:
198
- at = datetime.datetime.fromisoformat(spec)
199
- except ValueError as e:
200
- raise CribUserError(
201
- f"expires: {spec!r} is neither an ISO time nor a duration like "
202
- "30m / 2h / 1d") from e
203
- if at.tzinfo is None:
204
- at = at.replace(tzinfo=datetime.UTC)
205
- return at.astimezone(datetime.UTC).isoformat(timespec="seconds")
206
-
207
-
208
- # A bundle's portable embedding-cache rows (crib.bundle), under its data dir.
209
- BUNDLE_VECTORS = "embed-cache.parquet"
210
187
 
211
188
  class Crib:
212
189
  def __init__(self, paths: Paths, config: Config, store: Store) -> None:
190
+ # every component below gets THESE paths: the context dir applied
191
+ paths = paths.with_context(config)
213
192
  self.paths = paths
214
193
  self.config = config
215
194
  self.store = store
@@ -230,7 +209,7 @@ class Crib:
230
209
  # (e.g. on --store scratch) loads it, so the rebuild re-embeds nothing.
231
210
  if (
232
211
  paths.root is not None
233
- and (vecs := paths.data_dir / BUNDLE_VECTORS).is_file()
212
+ and (vecs := paths.data_dir / VECTORS_FILE).is_file()
234
213
  and callable(getattr(store, "ec_import", None))
235
214
  and store.ec_count() == 0 # type: ignore[attr-defined]
236
215
  ):
@@ -276,7 +255,8 @@ class Crib:
276
255
  # verbs refuse with the reason.
277
256
  self.pending_facets: dict[str, str] = store.facet_pending()
278
257
  # which projects this instance may write (crib/access.py; None = all)
279
- self.access = WriteAccess(config.writable)
258
+ self.access = WriteAccess(config.writable, read_only=paths.in_context)
259
+ self._sweep_warned: set[str] = set() # scheduled-delete failures, reported once
280
260
  self.pillars: dict[str, NoteStore] = {
281
261
  spec.name: NoteStore(
282
262
  paths, store, self.index, self.versions, self.project_paths, spec,
@@ -335,6 +315,7 @@ class Crib:
335
315
  config,
336
316
  self._enumerate_code_files,
337
317
  self._register_code_root,
318
+ self._require_write,
338
319
  )
339
320
  # The code-index pipeline (extract → describe → persist), over CodeStore +
340
321
  # ProjectServices. Crib keeps delegators (below) so the watcher, the resident
@@ -426,7 +407,7 @@ class Crib:
426
407
  root = SymbolIndex(self.paths.project_dir(name)).source_root()
427
408
  # confined mode watches nothing outside the root (a source checkout
428
409
  # never sits inside it): indexing there is explicit
429
- if root is not None and self.paths.root is None:
410
+ if root is not None and self.paths.root is None and self._may_write(name):
430
411
  self._code_watcher.watch_root(name, root)
431
412
  self._code_watcher.start()
432
413
  # Deferred describe: the code-watcher persists STRUCTURE eagerly and hands the
@@ -815,6 +796,8 @@ class Crib:
815
796
  provider = provider_id(self.config.generate, "elaborate")
816
797
  pending = attempted = backing_off = 0
817
798
  for name in self.projects():
799
+ if not self._may_write(name):
800
+ continue # read-only here: its records aren't ours to describe
818
801
  try:
819
802
  si = SymbolIndex(self.paths.project_dir(name))
820
803
  root = si.source_root()
@@ -884,6 +867,8 @@ class Crib:
884
867
  ) or not self._may_generate(background=True):
885
868
  return
886
869
  for name in self.projects():
870
+ if not self._may_write(name):
871
+ continue # read-only here: its enrichment tiers aren't ours to write
887
872
  if self._skip_if_unavailable(self.project_paths(name), "not enriching"):
888
873
  continue
889
874
  try:
@@ -1617,6 +1602,8 @@ class Crib:
1617
1602
  the notes reconcile never walks them — only this sweep does. Best-effort:
1618
1603
  a project with no registered repo (or a root that's since moved) simply has
1619
1604
  no in-situ docs to recover."""
1605
+ if not self._may_write(project):
1606
+ return 0 # read-only here: nothing of it is ours to re-sweep
1620
1607
  try:
1621
1608
  res = await self.index_docs_insitu(project=project)
1622
1609
  except Exception as e: # noqa: BLE001 — no repo / moved root / unreadable doc
@@ -2314,9 +2301,13 @@ class Crib:
2314
2301
  def _revalidate(self, proj: str) -> None:
2315
2302
  """Delegate to CodeStore, injecting the pipeline's per-file indexer. A
2316
2303
  query finding code changed is background work: it describes only when
2317
- [generate] mode is "on"."""
2304
+ [generate] mode is "on". A project this instance holds read-only is
2305
+ never revalidated (that would re-index, or drop, its records)."""
2318
2306
  import functools
2319
2307
 
2308
+ if not self._may_write(proj):
2309
+ return
2310
+
2320
2311
  # Never inline: a query must not wait on an LLM. Changed files are
2321
2312
  # re-indexed for structure now and queued for description (the daemon's
2322
2313
  # describe queue; without one, as in a one-shot CLI, inline).
@@ -2343,7 +2334,8 @@ class Crib:
2343
2334
  return wanted if self._may_generate(background=True) else "none"
2344
2335
 
2345
2336
  def _drop_file(self, proj: str, relpath: str) -> None:
2346
- self.code.drop_file(proj, relpath)
2337
+ if self._may_write(proj): # a read-only project's records stay
2338
+ self.code.drop_file(proj, relpath)
2347
2339
 
2348
2340
  def _require_code_index(self, proj: str) -> None:
2349
2341
  """Raise a self-diagnosing error when `proj` has no code index — so a call
@@ -2421,6 +2413,10 @@ class Crib:
2421
2413
  BOUNDARIES: their code belongs to the nested project (a vendored
2422
2414
  submodule with a .crib, say), never to the parent's index. `refs:` is
2423
2415
  how the parent xrefs into it (cross-project refs)."""
2416
+ if self.paths.root is not None:
2417
+ # confined mode: a checkout's .crib (here, one planted in the code
2418
+ # under review) must not hide files from the index
2419
+ return []
2424
2420
  junk = self._code_ignore()
2425
2421
  out: list[Path] = []
2426
2422
  for dp, dirs, files in os.walk(root):
@@ -2445,12 +2441,20 @@ class Crib:
2445
2441
  # reaching in would index the same bytes twice under two identities.
2446
2442
  if (link := CribLink.find(root)) is not None and link.store_dir is not None:
2447
2443
  bounds.append(link.store_dir)
2444
+ real_root = root.resolve()
2445
+
2446
+ def inside(p: Path) -> bool:
2447
+ # a symlink whose target escapes the checkout is not its code (and
2448
+ # would break every relpath taken from it)
2449
+ return p.resolve().is_relative_to(real_root)
2450
+
2448
2451
  for g in globs:
2449
2452
  for p in root.glob(g):
2450
2453
  if (
2451
2454
  p.is_file()
2452
2455
  and not any(part in junk for part in p.relative_to(root).parts)
2453
2456
  and not any(p.is_relative_to(b) for b in bounds)
2457
+ and inside(p)
2454
2458
  ):
2455
2459
  seen.add(p)
2456
2460
  # extensionless / unknown-extension files matched by the grammar map
@@ -2476,7 +2480,7 @@ class Crib:
2476
2480
  ]
2477
2481
  for fn in files:
2478
2482
  p = Path(dp) / fn
2479
- if p in seen or p.suffix.lower() in known_exts:
2483
+ if p in seen or p.suffix.lower() in known_exts or not inside(p):
2480
2484
  continue # globs already cover known extensions
2481
2485
  lang = content_lang(p, grammar)
2482
2486
  if lang and lang in served:
@@ -2583,9 +2587,47 @@ class Crib:
2583
2587
  lines += ["paths:", *[f' - "{g}"' for g in globs]]
2584
2588
  if want_docs:
2585
2589
  lines += ["docs:", ' - "README.md"', ' - "docs/**/*.md"']
2590
+ self._require_write(name, "create .crib")
2586
2591
  (root / ".crib").write_text("\n".join(lines) + "\n")
2587
2592
  return CribLink.find(root), True
2588
2593
 
2594
+ def _require_write(self, project: str | None, verb: str) -> None:
2595
+ """Refuse `verb` on `project` unless this instance may write it: the
2596
+ writable allowlist (crib.access), and in confined mode (--root) the
2597
+ project's home under the root. The one check every writing verb makes;
2598
+ NoteStore makes the same per item."""
2599
+ self.access.require(project, verb)
2600
+ if (base := self.paths.root) is not None and project:
2601
+ home = self.project_paths(project).data_root.resolve()
2602
+ if not home.is_relative_to(base):
2603
+ raise CribUserError(
2604
+ f"{verb} refused: confined mode (--root {base}) writes only "
2605
+ f"under its root; project {project!r} lives at {home}")
2606
+
2607
+ def _may_write(self, project: str | None) -> bool:
2608
+ """`_require_write` as a test: may this instance write `project`?"""
2609
+ try:
2610
+ self._require_write(project, "write")
2611
+ except CribUserError:
2612
+ return False
2613
+ return True
2614
+
2615
+ def _crib_file(self, project: str, root: Path) -> Path:
2616
+ """The `.crib` a project's index is scoped by: the repo's, or in
2617
+ confined mode the trusted copy under the root (a checkout's own is
2618
+ never consulted there)."""
2619
+ if self.paths.root is not None:
2620
+ return self.paths.project_dir(project) / ".crib"
2621
+ return root / ".crib"
2622
+
2623
+ def _refuse_residency_when_confined(self, verb: str) -> None:
2624
+ """Residency verbs write a `.crib` and a store into a repo: never in
2625
+ confined mode, where the repo is the code under review."""
2626
+ if self.paths.root is not None:
2627
+ raise CribUserError(
2628
+ f"{verb} refused in confined mode (--root): it writes into a "
2629
+ "repo, which here is the code under review")
2630
+
2589
2631
  def _confined_link(
2590
2632
  self, cwd: Path | None, project: str | None, want_code: bool, want_docs: bool
2591
2633
  ) -> CribLink:
@@ -2643,7 +2685,7 @@ class Crib:
2643
2685
  explicit verb.)"""
2644
2686
  link, created = self._ensure_crib(cwd, project, want_code=True, want_docs=True)
2645
2687
  proj = project or link.project
2646
- self.access.require(proj, "project_setup")
2688
+ self._require_write(proj, "project_setup")
2647
2689
  new_project = proj not in self.projects() # before indexing creates its dirs
2648
2690
  mapped = await self._sync_mappings(proj, link)
2649
2691
  docs = (
@@ -2713,9 +2755,9 @@ class Crib:
2713
2755
  """The body of `project_index` (which adds the facet summary)."""
2714
2756
  link, created = self._ensure_crib(cwd, project, want_code=True, want_docs=False)
2715
2757
  proj = project or link.project
2716
- self.access.require(proj, "project_index")
2758
+ self._require_write(proj, "project_index")
2717
2759
  await self._sync_mappings(proj, link)
2718
- crib_file = link.root / ".crib"
2760
+ crib_file = self._crib_file(proj, link.root)
2719
2761
  crib_at = crib_file.stat().st_mtime if crib_file.exists() else None
2720
2762
  running = self.code_jobs.get(proj)
2721
2763
  if running is not None and not running["task"].done():
@@ -2811,7 +2853,7 @@ class Crib:
2811
2853
  new_project = proj not in self.projects() # before indexing creates its dirs
2812
2854
  docs = await self.index_docs_insitu(proj, root) if link.doc_patterns else {}
2813
2855
  globs = link.paths or self._detect_code_globs(root)
2814
- crib_file = root / ".crib"
2856
+ crib_file = self._crib_file(proj, root)
2815
2857
  crib_at = crib_file.stat().st_mtime if crib_file.exists() else None
2816
2858
  if phased if phased is not None else self.paths.root is not None:
2817
2859
  code = await self.indexer.index_phased(
@@ -3272,6 +3314,7 @@ class Crib:
3272
3314
  it with no cwd near the repo; the derived index tiers do NOT move.
3273
3315
  Idempotent: adopting an already-adopted project at the same store is a
3274
3316
  no-op."""
3317
+ self._refuse_residency_when_confined("project_adopt")
3275
3318
  link = CribLink.find(cwd or Path.cwd())
3276
3319
  if link is None or link.root is None:
3277
3320
  raise CribUserError(
@@ -3280,7 +3323,7 @@ class Crib:
3280
3323
  "`store:`, or run `crib project setup` first)"
3281
3324
  )
3282
3325
  proj = check_project_name(project or link.project)
3283
- self.access.require(proj, "project_adopt")
3326
+ self._require_write(proj, "project_adopt")
3284
3327
  if project and link.project != proj:
3285
3328
  raise CribUserError(
3286
3329
  f"the `.crib` at {link.root} names project {link.project!r}, not "
@@ -3390,8 +3433,9 @@ class Crib:
3390
3433
  ring) back into the global store and clear the stub's `store_root`. Use it
3391
3434
  when the repo is going away, or when the notes should stop travelling with
3392
3435
  it. Idempotent: releasing an already-global project is a no-op."""
3436
+ self._refuse_residency_when_confined("project_release")
3393
3437
  proj = self.resolve_project(project, cwd)
3394
- self.access.require(proj, "project_release")
3438
+ self._require_write(proj, "project_release")
3395
3439
  mapped, kept = self._release_mapped(proj)
3396
3440
  extra = {**({"mapped": mapped} if mapped else {}),
3397
3441
  **({"kept": kept} if kept else {})}
@@ -3508,6 +3552,8 @@ class Crib:
3508
3552
 
3509
3553
  if expires is not None and not transient:
3510
3554
  raise CribUserError("expires applies to a transient project: pass transient too")
3555
+ if store is not None:
3556
+ self._refuse_residency_when_confined("project_create with store=")
3511
3557
  if store is not None and transient:
3512
3558
  raise CribUserError(
3513
3559
  "a transient project can't declare repo residency (store=): it is "
@@ -3561,7 +3607,7 @@ class Crib:
3561
3607
  )
3562
3608
  root = link.root
3563
3609
  store_decl = link.store
3564
- self.access.require(name, "project_create")
3610
+ self._require_write(name, "project_create")
3565
3611
  # The shared bucket never lives inside ONE repo — residency is a
3566
3612
  # repo's own memory, and `default` would silently adopt it into a
3567
3613
  # repo checkout (and into every clone's .crib).
@@ -3712,8 +3758,9 @@ class Crib:
3712
3758
  "(residency is declared with store=<repo-relative path>)"
3713
3759
  )
3714
3760
  name = check_project_name(project)
3715
- self.access.require(name, "project_create")
3716
- if self.paths.project_dir(name).exists():
3761
+ if not self.paths.project_dir(name).exists():
3762
+ self._require_write(name, "project_create")
3763
+ else:
3717
3764
  return {
3718
3765
  "project": name,
3719
3766
  "project_created": False,
@@ -3721,7 +3768,9 @@ class Crib:
3721
3768
  "message": f"{name} already exists (implicit birth on first "
3722
3769
  "write, or a previous create) — nothing changed",
3723
3770
  }
3724
- until = _expiry(expires) if expires else None
3771
+ from . import expiry
3772
+
3773
+ until = expiry.parse(expires) if expires else None
3725
3774
  pdir = self.paths.project_dir(name)
3726
3775
  pdir.mkdir(parents=True, exist_ok=True)
3727
3776
  if transient:
@@ -3747,56 +3796,67 @@ class Crib:
3747
3796
  ),
3748
3797
  }
3749
3798
 
3750
- def sweep_expired_transients(self, now: datetime.datetime | None = None) -> list[str]:
3751
- """Delete every transient project whose `expires` has passed (the
3752
- scheduled delete): the ordinary delete path (index rows, vectors,
3753
- stamps, bindings, files), with no .trash. Returns the names deleted."""
3754
- now = now or datetime.datetime.now(datetime.UTC)
3755
- gone: list[str] = []
3799
+ def _discardable(self, project: str) -> bool:
3800
+ """A transient project THIS machine made, so it may be deleted without
3801
+ .trash (and on schedule): its stub says transient, its directory still
3802
+ carries the `*` .gitignore written at birth, and its stub names this host.
3803
+ A stub alone could have arrived by git sync, a hand edit or a merge."""
3804
+ try:
3805
+ pp = self.project_paths(project)
3806
+ pcfg = ProjectConfig.load(pp.config_file, project)
3807
+ ignore = (pp.project_dir / ".gitignore").read_text().strip()
3808
+ except Exception: # noqa: BLE001 — unreadable: not provably ours
3809
+ return False
3810
+ return bool(pcfg.transient) and ignore == "*" and pcfg.host == claudemem.hostslug()
3811
+
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`."""
3815
+ from . import expiry
3816
+
3817
+ due = []
3756
3818
  for name in self.projects():
3757
3819
  try:
3758
3820
  pp = self.project_paths(name)
3759
3821
  except Exception: # noqa: BLE001 — an unreadable stub is not ours to delete
3760
3822
  continue
3761
- if not (pp.transient and pp.expires):
3762
- continue
3763
- try:
3764
- due = datetime.datetime.fromisoformat(pp.expires)
3765
- except ValueError:
3766
- continue
3767
- if due.tzinfo is None:
3768
- due = due.replace(tzinfo=datetime.UTC)
3769
- if due <= now:
3770
- gone.append(name)
3771
- return gone
3823
+ if pp.transient and expiry.due(pp.expires, now) and self._discardable(name):
3824
+ due.append(name)
3825
+ return due
3772
3826
 
3773
3827
  async def delete_expired_transients(
3774
3828
  self, now: datetime.datetime | None = None
3775
3829
  ) -> list[str]:
3776
- """`sweep_expired_transients`, deleting each due project."""
3777
- due = self.sweep_expired_transients(now)
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."""
3778
3833
  deleted = []
3779
- for name in due:
3834
+ for name in self.expired_transients(now):
3780
3835
  try:
3781
3836
  await self.project_delete(project=name, force=True)
3782
3837
  deleted.append(name)
3783
- except CribUserError as e: # e.g. a sweep still running: next time
3784
- print(f"[crib] transient {name!r} not deleted yet: {e}", file=sys.stderr)
3838
+ except Exception as e: # noqa: BLE001 — one project never stops the sweep
3839
+ if name not in self._sweep_warned: # once per project
3840
+ self._sweep_warned.add(name)
3841
+ print(f"[crib] transient {name!r} not deleted yet: {e}",
3842
+ file=sys.stderr)
3785
3843
  return deleted
3786
3844
 
3787
3845
  async def _transient_sweeper(self, every_s: float = 300.0) -> None:
3788
- """The daemon's scheduled delete of expired transient projects, and of
3789
- expired registered bundles (crib.bundle; trusted side only)."""
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."""
3790
3849
  from . import bundle as bundles
3791
3850
 
3851
+ if self.paths.root is not None:
3852
+ return
3792
3853
  while True:
3793
3854
  await self.delete_expired_transients()
3794
- if self.paths.root is None:
3795
- try:
3796
- for gone in bundles.sweep(self.paths):
3797
- print(f"[crib] expired bundle deleted: {gone}", file=sys.stderr)
3798
- except Exception as e: # noqa: BLE001 — a sweep never kills the daemon
3799
- print(f"[crib] bundle sweep failed: {e}", file=sys.stderr)
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)
3800
3860
  await asyncio.sleep(every_s)
3801
3861
 
3802
3862
  def _pillar_note_count(self, pp: ProjectPaths) -> int:
@@ -3883,7 +3943,7 @@ class Crib:
3883
3943
  "the default project"
3884
3944
  )
3885
3945
  proj = check_project_name(project)
3886
- self.access.require(proj, "project_delete")
3946
+ self._require_write(proj, "project_delete")
3887
3947
  del cwd # deliberately unused: the selector above is the whole answer
3888
3948
  plan = self._delete_plan(proj, force)
3889
3949
  if not plan["exists_anywhere"]:
@@ -3917,7 +3977,7 @@ class Crib:
3917
3977
  # The global tree (machine-local stub + derived caches) travels to
3918
3978
  # the trash — it is shared-git/data-root state, undo for free.
3919
3979
  # The user repo's store is deliberately NOT touched here.
3920
- if plan["tree_exists"] and self._is_transient(proj):
3980
+ if plan["tree_exists"] and self._discardable(proj):
3921
3981
  # a transient project is discarded whole: no undo copy
3922
3982
  shutil.rmtree(self.paths.project_dir(proj))
3923
3983
  elif plan["tree_exists"]:
@@ -4085,8 +4145,8 @@ class Crib:
4085
4145
  old = check_project_name(project)
4086
4146
  del cwd # deliberately unused, same rule as delete
4087
4147
  new = check_project_name(to)
4088
- self.access.require(old, "project_rename")
4089
- self.access.require(new, "project_rename (to)")
4148
+ self._require_write(old, "project_rename")
4149
+ self._require_write(new, "project_rename (to)")
4090
4150
  if old == new:
4091
4151
  raise CribUserError(f"rename to the same name ({old!r}) does nothing")
4092
4152
  if old == self.config.default_project or new == self.config.default_project:
@@ -4452,6 +4512,7 @@ class Crib:
4452
4512
  The foreign residue — other projects citing this repo by the old
4453
4513
  spellings — is REPORTED (`foreign_refs`), never edited (rename's
4454
4514
  rule: each registry is per-project and machine-local)."""
4515
+ self._refuse_residency_when_confined("project_relocate")
4455
4516
  from .config import CribLink, ProjectConfig, portable_path
4456
4517
  from .sources import SRC_PREFIX
4457
4518
  from .watch import PILLAR_SEGMENTS
@@ -4463,7 +4524,7 @@ class Crib:
4463
4524
  "never the default project and never a cwd guess"
4464
4525
  )
4465
4526
  old = check_project_name(project)
4466
- self.access.require(old, "project_relocate")
4527
+ self._require_write(old, "project_relocate")
4467
4528
  new_root = Path(project_path).expanduser().resolve()
4468
4529
  if not new_root.is_dir():
4469
4530
  raise CribUserError(f"no such directory: {new_root}")
@@ -4909,7 +4970,7 @@ class Crib:
4909
4970
  Per record, no ordering constraint against the entry conversion, re-running
4910
4971
  is the resume. DRY RUN unless `apply`."""
4911
4972
  proj = self.resolve_project(project, cwd)
4912
- self.access.require(proj, "learning_migrate")
4973
+ self._require_write(proj, "learning_migrate")
4913
4974
  return await self._anchored_facet(facet).convert_notes(proj, apply=apply)
4914
4975
 
4915
4976
  async def code_convert(
@@ -4930,7 +4991,7 @@ class Crib:
4930
4991
  from .symconvert import convert_entry, convertible, preserved
4931
4992
 
4932
4993
  proj = self.resolve_project(project, cwd)
4933
- self.access.require(proj, "code_convert")
4994
+ self._require_write(proj, "code_convert")
4934
4995
  store = SymbolIndex(self.paths.project_dir(proj))
4935
4996
  rows = store.records()
4936
4997
  # COLLISION GUARD. Distinct records whose cleaned identities derive ONE key
@@ -5014,7 +5075,7 @@ class Crib:
5014
5075
  explicitly. Idempotent; collisions are skipped and reported, never
5015
5076
  merged."""
5016
5077
  proj = self.resolve_project(project, cwd)
5017
- self.access.require(proj, "project_migrate")
5078
+ self._require_write(proj, "project_migrate")
5018
5079
  self.project_paths(proj).require()
5019
5080
  mig = self._migrate_legacy_layout(proj)
5020
5081
  rec = await self.reindex(project=proj)
@@ -5345,7 +5406,7 @@ class Crib:
5345
5406
  from .codeindex import SymbolIndex
5346
5407
 
5347
5408
  proj = self.resolve_project(project, cwd)
5348
- self.access.require(proj, "project_forget")
5409
+ self._require_write(proj, "project_forget")
5349
5410
  si_root = SymbolIndex(self.project_paths(proj).project_dir).root
5350
5411
  removed = len(list(si_root.glob("*.toml"))) if si_root.exists() else 0
5351
5412
  if si_root.exists():
@@ -6010,6 +6071,7 @@ class Crib:
6010
6071
  )
6011
6072
 
6012
6073
  proj = self.resolve_project(project, cwd)
6074
+ self._require_write(proj, "enrich") # writes the project's enrichment tiers
6013
6075
  facets: list[dict[str, Any]] = []
6014
6076
  for table, builtins, root, labels in (
6015
6077
  (
@@ -6059,6 +6121,7 @@ class Crib:
6059
6121
  """Single-facet shim over `_generate_enrichment` (the `elaborate`/`summarize`
6060
6122
  verbs) — legacy flat result shape preserved."""
6061
6123
  proj = self.resolve_project(project, cwd)
6124
+ self._require_write(proj, purpose) # writes (and prunes) its index tier
6062
6125
  from .section_index import SectionIndex
6063
6126
 
6064
6127
  if prompt is None:
@@ -6533,7 +6596,7 @@ class Crib:
6533
6596
  preserved across re-pulls. Provenance is byte-identical across machines so a
6534
6597
  git sync never conflicts on it (DESIGN §14)."""
6535
6598
  proj = self.resolve_project(project, cwd)
6536
- self.access.require(proj, "import_files")
6599
+ self._require_write(proj, "import_files")
6537
6600
  created = self.project_is_new(proj)
6538
6601
  today = datetime.date.today().isoformat()
6539
6602
 
@@ -6610,7 +6673,7 @@ class Crib:
6610
6673
  )
6611
6674
  mem_dir = claudemem.harness_memory_dir(src_root)
6612
6675
  proj = self.resolve_project(project, cwd)
6613
- self.access.require(proj, "import_claude_memory")
6676
+ self._require_write(proj, "import_claude_memory")
6614
6677
  created = self.project_is_new(proj)
6615
6678
  prefix = f"claude-memory/{claudemem.hostslug()}/"
6616
6679
  today = datetime.date.today().isoformat()
@@ -6728,10 +6791,9 @@ class Crib:
6728
6791
  return False
6729
6792
 
6730
6793
  def projects(self) -> list[str]:
6731
- pd = self.paths.projects_dir
6732
- if not pd.is_dir():
6733
- return []
6734
- return sorted(p.name for p in pd.iterdir() if p.is_dir())
6794
+ names = {p.name for d in (self.paths.projects_dir, self.paths.context_dir)
6795
+ if d is not None and d.is_dir() for p in d.iterdir() if p.is_dir()}
6796
+ return sorted(names)
6735
6797
 
6736
6798
  def project_config(self, project: str) -> ProjectConfig:
6737
6799
  return ProjectConfig.load(self.project_paths(project).config_file, project)