cribsheet 0.21.2.dev4__py3-none-any.whl → 0.21.3.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
@@ -26,6 +26,7 @@ from .claudemem import MemoryBindings
26
26
  from .codeindexer import CodeIndexer
27
27
  from .codequery import CodeQuery
28
28
  from .codestore import CodeStore, _ResidentCode
29
+ from .codestore import format_sweep
29
30
  from .config import Config, CribLink, ProjectConfig, portable_path, resolve_project
30
31
  from .designs import Designs
31
32
  from .embed import build_embedder, embed_batch, embed_query_batch
@@ -63,6 +64,13 @@ DEFAULT_DISTILL_PROMPT = (
63
64
  )
64
65
 
65
66
 
67
+ # The polling interval for bounded JOINS inside a kick/wait sweep — the poll
68
+ # contract's own cadence: a join checks the sweep every interval until it is
69
+ # done. Lives HERE (app), not server (server imports app; never the reverse);
70
+ # server.py re-exports its own copy for the MCP face's historic progress loop.
71
+ _PROGRESS_EVERY_S = 2.0
72
+
73
+
66
74
  @dataclass
67
75
  class LookupHit:
68
76
  project: str
@@ -1944,20 +1952,27 @@ class Crib:
1944
1952
  project: str | None = None,
1945
1953
  cwd: Path | None = None,
1946
1954
  budget_s: float | None = None,
1955
+ wait_s: float | None = None,
1947
1956
  ) -> dict[str, Any]:
1948
1957
  """(Re)index the project's SOURCE CODE and in-situ docs from its `.crib`
1949
1958
  (ensuring a `.crib` first). Cheap re-run via the content-hash gate.
1950
1959
 
1951
- JOIN-DON'T-RESTART: a re-invoke while a sweep runs for this project
1952
- awaits the running task and returns its result (`joined: true`) instead
1953
- of racing a second sweep — the zero-reset counter bug, fixed at the
1954
- source. A scope change (`.crib` mtime moved since kick-off) returns a
1955
- `conflict` instead of silently joining a stale-scoped sweep; cancel the
1956
- running one (`project_cancel`) and re-invoke.
1957
-
1958
- `budget_s` bounds the call and DEFERS the rest (`complete=False`,
1959
- `remaining=N`) — re-invoke to continue; poll `project_status` for live
1960
- `{done,total}` progress meanwhile."""
1960
+ THE POLLING CONTRACT: the sweep runs as a daemon-owned job — a call
1961
+ returns a RUNNING HANDLE at once (`running: true` + live done/total)
1962
+ and never holds a client request for the sweep's length (a capped proxy
1963
+ would cut it; poll `project_status`'s `jobs` — it never errors or
1964
+ blocks, and reporting a failed job is its job). A re-invoke JOINS the
1965
+ running sweep (never a second one — the zero-reset counter bug, fixed
1966
+ at the source); `wait_s=<seconds>` BLOCKS bounded (scripts/terminals;
1967
+ the agent-facing faces don't expose it), returning the final result or
1968
+ a still-running handle. A finished sweep's re-invoke returns its full
1969
+ result. A scope change (`.crib` mtime moved since kick-off) returns a
1970
+ `conflict` instead of silently joining a stale-scoped sweep —
1971
+ `project_cancel` then re-invoke.
1972
+
1973
+ `budget_s` bounds the WORK: files not reached are deferred
1974
+ (`complete=False, remaining=N`) — re-invoke to continue (finished files
1975
+ re-skip via the content-hash gate)."""
1961
1976
  link, created = self._ensure_crib(cwd, project, want_code=True, want_docs=False)
1962
1977
  proj = project or link.project
1963
1978
  crib_file = link.root / ".crib"
@@ -1976,16 +1991,65 @@ class Crib:
1976
1991
  f"for it to finish"
1977
1992
  ),
1978
1993
  }
1979
- result = await running["task"]
1980
- return {**result, "joined": True}
1994
+ # JOIN the running sweep: bounded, or an immediate handle — a poll
1995
+ # is never an error, and a bounded join still never starts sweep 2.
1996
+ if wait_s is not None:
1997
+ started = time.monotonic()
1998
+ while (
1999
+ not running["task"].done() and time.monotonic() - started < wait_s
2000
+ ):
2001
+ await asyncio.wait({running["task"]}, timeout=_PROGRESS_EVERY_S)
2002
+ if running["task"].done():
2003
+ return {**(await running["task"]), "joined": True}
2004
+ return {
2005
+ "project": proj,
2006
+ "joined": True,
2007
+ "running": True,
2008
+ "done": (self.code.sweeps.get(proj) or {}).get("done"),
2009
+ "total": (self.code.sweeps.get(proj) or {}).get("total"),
2010
+ "resume_hint": (
2011
+ "the sweep keeps running daemon-side — poll "
2012
+ "project_status, call project_wait to re-attach, or "
2013
+ "re-invoke project_index to join"
2014
+ ),
2015
+ }
2016
+ return {
2017
+ "project": proj,
2018
+ "joined": True,
2019
+ "running": True,
2020
+ "done": (self.code.sweeps.get(proj) or {}).get("done"),
2021
+ "total": (self.code.sweeps.get(proj) or {}).get("total"),
2022
+ "resume_hint": (
2023
+ "already running — POLL project_status (never blocks, never "
2024
+ "errors); re-invoke to finish-poll; project_wait to block"
2025
+ ),
2026
+ }
1981
2027
  task = asyncio.create_task(
1982
2028
  self._project_index_now(proj, link, created, budget_s)
1983
2029
  )
2030
+ # RETAINED (not popped on finish): the poll needs the completed row
2031
+ # (complete: true + the final counts) so 'finished OK' is distinguishable
2032
+ # from 'never started'; the next sweep for this project replaces it.
1984
2033
  self.code_jobs[proj] = {"task": task, "crib_at": crib_at}
1985
- try:
1986
- return await task
1987
- finally:
1988
- self.code_jobs.pop(proj, None)
2034
+ if wait_s is None:
2035
+ # the handle-at-once half of the contract: never hold the request
2036
+ sw = self.code.sweeps.get(proj) or {}
2037
+ return {
2038
+ "project": proj,
2039
+ "started": True,
2040
+ "running": True,
2041
+ "done": sw.get("done"),
2042
+ "total": sw.get("total"),
2043
+ "resume_hint": (
2044
+ "indexing runs daemon-owned — POLL project_status (never "
2045
+ "blocks, never errors); re-invoke to join, project_wait to "
2046
+ "block for it"
2047
+ ),
2048
+ }
2049
+ started = time.monotonic()
2050
+ while not task.done() and time.monotonic() - started < wait_s:
2051
+ await asyncio.wait({task}, timeout=_PROGRESS_EVERY_S)
2052
+ return await task
1989
2053
 
1990
2054
  async def _project_index_now(
1991
2055
  self,
@@ -2029,34 +2093,59 @@ class Crib:
2029
2093
  project: str | None = None,
2030
2094
  cwd: Path | None = None,
2031
2095
  wait_s: float = 30.0,
2096
+ ctx: Any = None,
2032
2097
  ) -> dict[str, Any]:
2033
2098
  """Bounded-block on a running index job — the JOIN primitive for clients
2034
2099
  whose tool timeout is shorter than a sweep. Idle → `{running: false}`;
2035
2100
  finished within `wait_s` → the final result; still going → the live
2036
- partial state (call again to keep waiting)."""
2101
+ partial state (call again to keep waiting). While it waits it STREAMS
2102
+ PROGRESS (report_progress on the caller's context when one exists —
2103
+ `42/317 files (13%) · eta 1:50`), so a blocking join is still
2104
+ observable; `ctx` is the fastmcp Context when called over MCP."""
2037
2105
  proj = project or self._proj_from_cwd(cwd)
2038
2106
  if proj is None:
2039
2107
  raise CribUserError("project_wait: pass project= or run inside the repo")
2040
2108
  job = self.code_jobs.get(proj)
2041
2109
  if job is None or job["task"].done():
2042
2110
  return {"project": proj, "running": False}
2043
- done, _ = await asyncio.wait({job["task"]}, timeout=max(wait_s, 0.05))
2044
- if done:
2045
- return {
2046
- "project": proj,
2047
- "running": False,
2048
- "complete": True,
2049
- **job["task"].result(),
2050
- }
2051
- sw = self.code.sweeps.get(proj) or {}
2052
- return {
2053
- "project": proj,
2054
- "running": True,
2055
- "complete": False,
2056
- "done": sw.get("done"),
2057
- "total": sw.get("total"),
2058
- "resume_hint": "call project_wait again to keep waiting",
2059
- }
2111
+ started = time.monotonic()
2112
+ while True:
2113
+ remaining = max(wait_s, 0.05) - (time.monotonic() - started)
2114
+ done, _pending = await asyncio.wait(
2115
+ {job["task"]}, timeout=min(_PROGRESS_EVERY_S, max(remaining, 0.001))
2116
+ )
2117
+ if done:
2118
+ return {
2119
+ "project": proj,
2120
+ "running": False,
2121
+ "complete": True,
2122
+ **job["task"].result(),
2123
+ }
2124
+ if ctx is not None:
2125
+ sw = self.code.sweeps.get(proj) or {}
2126
+ if sw.get("total"):
2127
+ try:
2128
+ await ctx.report_progress(
2129
+ progress=sw.get("done") or 0,
2130
+ total=sw["total"],
2131
+ # pi-lens-ignore: python-empty-except
2132
+ message=f"{proj}: {format_sweep(sw)}",
2133
+ )
2134
+ except Exception: # noqa: BLE001 — progress is best-effort
2135
+ pass
2136
+ if time.monotonic() - started >= max(wait_s, 0.05):
2137
+ sw = self.code.sweeps.get(proj) or {}
2138
+ return {
2139
+ "project": proj,
2140
+ "running": True,
2141
+ "complete": False,
2142
+ "done": sw.get("done"),
2143
+ "total": sw.get("total"),
2144
+ "resume_hint": (
2145
+ "still running — POLL project_status (never blocks); "
2146
+ "call project_wait again to keep waiting"
2147
+ ),
2148
+ }
2060
2149
 
2061
2150
  async def project_cancel(
2062
2151
  self, project: str | None = None, cwd: Path | None = None
@@ -3902,7 +3991,9 @@ class Crib:
3902
3991
  "project": p,
3903
3992
  "phase": "extract+describe+embed",
3904
3993
  "running": not done,
3905
- "complete": done,
3994
+ # done but cancelled means STOPPED, never "finished OK"
3995
+ "complete": done and not meta["task"].cancelled(),
3996
+ **({"cancelled": True} if meta["task"].cancelled() else {}),
3906
3997
  "done": sw.get("done"),
3907
3998
  "total": sw.get("total"),
3908
3999
  **({"line": sw.get("line")} if sw.get("line") else {}),
crib/cli.py CHANGED
@@ -1258,6 +1258,14 @@ def build_parser() -> argparse.ArgumentParser:
1258
1258
  p = argparse.ArgumentParser(prog="crib", description="markdown memory")
1259
1259
  p.add_argument("--version", action="version", version=f"crib {__version__}")
1260
1260
  p.add_argument("--mcp", action="store_true", help="run the MCP server")
1261
+ p.add_argument(
1262
+ "--tools",
1263
+ default=None,
1264
+ help="comma-separated tool SETS to expose on this deployment "
1265
+ "(notes,designs,plans,code,learnings,projects,memory; `system` — "
1266
+ "status/ops/reconcile — always rides); default: all. Overrides "
1267
+ "config.toml [tools].expose",
1268
+ )
1261
1269
  p.add_argument("--json", action="store_true", help="machine-readable output")
1262
1270
  # transport options (apply to --mcp and `serve`; also pick the daemon the CLI
1263
1271
  # attaches to). Default to None so config `[daemon]` (host/port) wins unless
@@ -1287,6 +1295,7 @@ def build_parser() -> argparse.ArgumentParser:
1287
1295
 
1288
1296
  sv = sub.add_parser("serve", help="run the MCP server (stdio or --http)")
1289
1297
  sv.add_argument("--http", action="store_true")
1298
+ sv.add_argument("--tools", dest="tools", default=None) # same set as --mcp
1290
1299
  sv.add_argument("--host", default=None)
1291
1300
  sv.add_argument("--port", type=int, default=None)
1292
1301
  sub.add_parser("info", help="show resolved paths and available backends")
@@ -1322,13 +1331,16 @@ def build_parser() -> argparse.ArgumentParser:
1322
1331
  dest="budget_s",
1323
1332
  help="soft deadline; unfinished files are deferred",
1324
1333
  )
1325
- if _v in ("index", "wait"):
1334
+ if _v == "wait":
1335
+ # the polling contract: `project index` returns a running handle and
1336
+ # the CLI emitter follows it to completion — no --wait-s there; the
1337
+ # BLOCKING join is wait's own verb (scripts/terminals).
1326
1338
  _sp.add_argument(
1327
1339
  "--wait-s",
1328
1340
  type=float,
1329
1341
  default=None,
1330
1342
  dest="wait_s",
1331
- help="bound this CALL (the sweep keeps running "
1343
+ help="bound this WAIT (the sweep keeps running "
1332
1344
  "daemon-side); re-invoke to re-join",
1333
1345
  )
1334
1346
  proj(_sp)
@@ -2803,11 +2815,15 @@ VERBS: dict[str, Verb] = {
2803
2815
  ),
2804
2816
  "project index": Verb(
2805
2817
  "project_index",
2806
- lambda a: {"project": _proj_of(a), "wait_s": getattr(a, "wait_s", None)},
2818
+ # the polling contract: the daemon face returns a RUNNING HANDLE at
2819
+ # once (no wait_s — a blocking call can't survive proxy caps); the CLI
2820
+ # emitter follows it to completion (a terminal may block) via
2821
+ # project_wait when the handle says running.
2822
+ lambda a: {"project": _proj_of(a)},
2807
2823
  _E_project("index"),
2808
2824
  is_async=True,
2809
2825
  policy="source",
2810
- mcp=f"{_PROJ} budget_s=None wait_s=None",
2826
+ mcp=f"{_PROJ} budget_s=None",
2811
2827
  ),
2812
2828
  "project wait": Verb(
2813
2829
  "project_wait",
@@ -3491,6 +3507,19 @@ def _dispatch(args: Any) -> tuple[Verb, dict[str, Any]]:
3491
3507
  return _resolve_verb(args)
3492
3508
 
3493
3509
 
3510
+ def _resolve_tool_spec(args: Any) -> str | list[str] | None:
3511
+ """The tool-set exposure for serve: the --tools flag WINS over config.toml
3512
+ `[tools].expose`; neither = everything. (Validated at serve startup.)"""
3513
+ from .config import Config
3514
+ from .paths import Paths
3515
+
3516
+ spec = getattr(args, "tools", None)
3517
+ if spec is not None and str(spec).strip():
3518
+ return str(spec)
3519
+ cfg = Config.load(Paths.resolve().config_file)
3520
+ return cfg.tools.expose or None
3521
+
3522
+
3494
3523
  def _resolve_serve_endpoint(args: Any) -> tuple[str, int]:
3495
3524
  """Bind address for `serve`/`--mcp`: explicit flags win, else `[daemon]`."""
3496
3525
  from .config import Config
@@ -3848,8 +3877,9 @@ def main(argv: list[str] | None = None) -> int:
3848
3877
  host, port = _resolve_serve_endpoint(args)
3849
3878
  from .server import main as serve
3850
3879
 
3880
+ tools = _resolve_tool_spec(args)
3851
3881
  transport = "http" if args.http else "stdio"
3852
- serve(transport, host, port)
3882
+ serve(transport, host, port, tools)
3853
3883
  return 0
3854
3884
  if args.cmd is None:
3855
3885
  build_parser().print_help()
crib/config.py CHANGED
@@ -258,9 +258,23 @@ class DaemonConfig:
258
258
  grace_period: str = "1h" # keep warm this long after the last client
259
259
 
260
260
 
261
+ @dataclass
262
+ class ToolsConfig:
263
+ """Which tool SETS the MCP face exposes, per deployment (DESIGN: exposure).
264
+
265
+ `expose` lists set NAMES (`notes/designs/plans/code/learnings/projects/
266
+ memory`); empty = everything (the default, and what a pi session wants).
267
+ The `system` set (status/ops/project_reconcile — the poll/meta surface)
268
+ always rides along, filtered or not. The `crib serve --tools`
269
+ comma-list overrides this file setting."""
270
+
271
+ expose: list[str] = field(default_factory=list)
272
+
273
+
261
274
  @dataclass
262
275
  class Config:
263
276
  default_project: str = "default"
277
+ tools: ToolsConfig = field(default_factory=ToolsConfig)
264
278
  embed: EmbedConfig = field(default_factory=EmbedConfig)
265
279
  chunk: ChunkConfig = field(default_factory=ChunkConfig)
266
280
  retrieve: RetrieveConfig = field(default_factory=RetrieveConfig)
@@ -305,6 +319,7 @@ class Config:
305
319
  "chroma": ChromaConfig,
306
320
  "daemon": DaemonConfig,
307
321
  "generate": GenerateConfig,
322
+ "tools": ToolsConfig,
308
323
  }
309
324
  _warn_unknown(config_file, "top level", data, {f.name for f in fields(cls)})
310
325
  if "default_project" in data:
crib/server.py CHANGED
@@ -10,12 +10,10 @@ import functools
10
10
  import inspect
11
11
  import os
12
12
  import sys
13
- import time
14
13
  from pathlib import Path
15
14
  from typing import TYPE_CHECKING, Any
16
15
 
17
16
  from .app import Crib
18
- from .codestore import format_sweep
19
17
  from .errors import CribUserError
20
18
  from .session import (
21
19
  ERA_STATELESS,
@@ -311,6 +309,75 @@ TOOL_POLICY: dict[str, str] = {}
311
309
  _POLICIES = ("read", "write", "source", "session", "none")
312
310
 
313
311
 
312
+ # ── Per-deployment tool-set EXPOSURE (crib serve --tools / [tools].expose) ────
313
+ # A general-assistant deployment shows the prose facets only; a pi session gets
314
+ # everything. The mapping is the tool NAME's own family — the same grouping the
315
+ # CLI's nouns use — plus `system`: status/ops/project_reconcile (the poll/meta
316
+ # surface) always ride along, filtered or not, because polling a job needs no
317
+ # code intelligence.
318
+ TOOL_SET_NAMES = (
319
+ "notes",
320
+ "designs",
321
+ "plans",
322
+ "code",
323
+ "learnings",
324
+ "projects",
325
+ "memory",
326
+ "system",
327
+ )
328
+ _SET_FAMILIES = {
329
+ "note": "notes",
330
+ "design": "designs",
331
+ "plan": "plans",
332
+ "code": "code",
333
+ "learning": "learnings",
334
+ "project": "projects",
335
+ "memory": "memory",
336
+ }
337
+ TOOL_SETS: dict[str, str] = {} # tool name -> set name, filled as tools register
338
+ _EXPOSED: frozenset[str] | None = None # None (the default) = every set
339
+
340
+
341
+ def tool_set_of(name: str) -> str:
342
+ """The tool set a tool belongs to — the CLI noun it nests under.
343
+ `project_reconcile` is the one prefix-straddler: it sweeps EVERY project
344
+ (whole-store housekeeping), so it rides with the poll/meta `system` set,
345
+ not with a namespace's management."""
346
+ set_name = (
347
+ "system"
348
+ if name == "project_reconcile"
349
+ else _SET_FAMILIES.get(name.split("_", 1)[0], "system")
350
+ )
351
+ TOOL_SETS[name] = set_name
352
+ return set_name
353
+
354
+
355
+ def exposure(
356
+ spec: str | list[str] | None,
357
+ ) -> frozenset[str] | None:
358
+ """`--tools notes,plans` / `[tools] expose` → the exposed sets (with
359
+ `system` always added). None (everything) when the spec names nothing.
360
+ UNKNOWN set names REFUSE here — at serve startup, naming the valid list —
361
+ rather than starting a server quietly missing sets someone asked for."""
362
+ if not spec:
363
+ return None
364
+ asked = [
365
+ t.strip()
366
+ for t in (spec.split(",") if isinstance(spec, str) else spec)
367
+ if t.strip()
368
+ ]
369
+ if not asked:
370
+ return None
371
+ unknown = sorted(set(asked) - set(TOOL_SET_NAMES))
372
+ if unknown:
373
+ raise ValueError(
374
+ f"unknown tool set(s) {', '.join(unknown)} — the sets are: "
375
+ + ", ".join(TOOL_SET_NAMES)
376
+ + " (`system` always rides along)"
377
+ )
378
+ return frozenset(asked) | {"system"}
379
+
380
+
314
381
  def _switch_if_created(result: dict) -> dict:
315
382
  """Creating a project switches the session into it — referencing an existing
316
383
  one (a one-off `project` arg) does not (DESIGN §15). The switch is the ONE
@@ -323,10 +390,21 @@ def _switch_if_created(result: dict) -> dict:
323
390
  return result
324
391
 
325
392
 
326
- def build_server(crib: Crib | None = None):
393
+ def build_server(crib: Crib | None = None, tools: str | list[str] | None = None):
327
394
  from fastmcp import FastMCP # lazy
328
395
  from fastmcp.tools import FunctionTool
329
396
 
397
+ global _EXPOSED
398
+ _EXPOSED = exposure(tools)
399
+ if _EXPOSED is not None:
400
+ served = sorted(_EXPOSED - {"system"})
401
+ print(
402
+ f"[crib] MCP tool sets exposed: {', '.join(served)} (+ system); "
403
+ f"{len(TOOL_SET_NAMES) - 1 - len(served)} set(s) not exposed: "
404
+ + ", ".join(
405
+ n for n in TOOL_SET_NAMES if n not in _EXPOSED and n != "system"
406
+ )
407
+ )
330
408
  crib = crib or Crib.open()
331
409
  mcp = FastMCP(
332
410
  "cribsheet",
@@ -557,7 +635,12 @@ def build_server(crib: Crib | None = None):
557
635
  raise ValueError(f"unknown resolution policy {resolution!r}")
558
636
 
559
637
  def register(fn):
560
- TOOL_POLICY[fn.__name__] = resolution
638
+ TOOL_POLICY[fn.__name__] = resolution # the policy table is FULL, even
639
+ # when THIS deployment doesn't expose the tool (the exposure gate is
640
+ # below): the declared/reserved policy stays checkable everywhere
641
+ set_name = tool_set_of(fn.__name__)
642
+ if _EXPOSED is not None and set_name not in _EXPOSED:
643
+ return fn # not exposed on THIS deployment: never registered
561
644
  impl = (
562
645
  fn
563
646
  if resolution in ("session", "none")
@@ -841,93 +924,29 @@ def build_server(crib: Crib | None = None):
841
924
  project: str | None = None,
842
925
  project_path: str | None = None,
843
926
  budget_s: float | None = None,
844
- wait_s: float | None = None,
845
- ctx: Context | None = None,
846
927
  ) -> dict[str, Any]:
847
928
  """(Re)index a project's SOURCE CODE from its `.crib`, PLUS the prose it
848
- declares under `docs:` — those are indexed IN-SITU (searchable via note_lookup;
849
- the repo keeps the only copy). It differs from project_setup only in not
850
- COPYING files into crib-owned notes. Use to index a repo for
851
- code_lookup/code_dossier, or to refresh after edits (cheap: unchanged files
852
- are skipped). Pass
853
- `project_path=<the repo dir>` (a `.crib` is auto-created if missing); a bare
854
- `project=<name>` re-indexes an ALREADY-INDEXED project from its recorded root.
855
-
856
- Emits PROGRESS markers while the sweep runs (`<proj>: 42/317 files (13%) ·
857
- 2.1/s · eta 2:05`) — the call returns when the sweep completes; while it
858
- runs, `project_status`'s `jobs` section is the non-blocking poll.
859
- (`project_status` also carries the live `indexing` counts.) If your client
860
- enforces a hard call timeout anyway, two levers:
861
- - `wait_s=<seconds>` bounds THIS call: the final result if the sweep
862
- finished inside the budget, else a partial handle (`running: true`,
863
- done/total/eta) — the sweep KEEPS RUNNING daemon-side; re-invoke to
864
- re-join it (never a second sweep), or poll `project_status`.
865
- - `budget_s=<seconds>` bounds the WORK: files not reached are deferred
866
- (`complete=false, remaining=N`) — re-invoke to continue (finished
867
- files re-skip via the content-hash gate)."""
868
- proj = project # resolved by the `source` policy
869
- before = set(crib.code.sweeps) # sweeps already running for OTHER calls
870
- started = time.monotonic()
871
- task = asyncio.create_task(
872
- crib.project_index(proj, cwd=_cwd(project_path), budget_s=budget_s)
873
- )
874
- while not task.done():
875
- # wait, don't sleep: a quick (all-cached) reindex returns immediately
876
- # instead of eating a full progress interval
877
- await asyncio.wait({task}, timeout=_PROGRESS_EVERY_S)
878
- if task.done():
879
- break
880
- # wait_s expiry → partial handle; the sweep KEEPS RUNNING daemon-side
881
- # (create_task is independent of this call) and a re-invoke JOINS it.
882
- if wait_s is not None and time.monotonic() - started >= wait_s:
883
- picked = (
884
- (proj, crib.code.sweeps[proj])
885
- if proj and proj in crib.code.sweeps
886
- else next(
887
- (
888
- (p, v)
889
- for p, v in crib.code.sweeps.items()
890
- if p not in before
891
- ),
892
- None,
893
- )
894
- )
895
- key, sw = picked if picked else (proj or "?", {})
896
- return {
897
- "project": key,
898
- "complete": False,
899
- "running": True,
900
- "done": sw.get("done"),
901
- "total": sw.get("total"),
902
- "line": f"{key}: {format_sweep(sw)}" if sw else None,
903
- "resume_hint": (
904
- "the sweep keeps running daemon-side — poll project_status, "
905
- "call project_wait to re-attach, or re-invoke project_index "
906
- "to join"
907
- ),
908
- }
909
- # OUR sweep only: the named project's, else the one this call started
910
- # (proj is None when the repo's .crib names it) — never other projects'.
911
- picked = (
912
- (proj, crib.code.sweeps[proj])
913
- if proj and proj in crib.code.sweeps
914
- else next(
915
- ((p, v) for p, v in crib.code.sweeps.items() if p not in before),
916
- None,
917
- )
918
- )
919
- if picked and picked[1].get("total") and ctx is not None:
920
- key, sw = picked
921
- try:
922
- await ctx.report_progress(
923
- progress=sw["done"] or 0,
924
- total=sw["total"] or 0,
925
- # pi-lens-ignore: python-empty-except
926
- message=f"{key}: {format_sweep(sw)}",
927
- )
928
- except Exception: # noqa: BLE001 — progress is best-effort
929
- pass
930
- return _switch_if_created(await task)
929
+ declares under `docs:` — those are indexed IN-SITU (searchable via
930
+ note_lookup; the repo keeps the only copy). It differs from
931
+ project_setup only in not COPYING files into crib-owned notes. Use to
932
+ index a repo for code_lookup/code_dossier, or to refresh after edits
933
+ (cheap: unchanged files are skipped). Pass
934
+ `project_path=<the repo dir>` (a `.crib` is auto-created if missing); a
935
+ bare `project=<name>` re-indexes an ALREADY-INDEXED project from its
936
+ recorded root.
937
+
938
+ THE SWEEP RUNS DAEMON-OWNED and this call returns at once — a RUNNING
939
+ HANDLE (`running: true` + done/total) or, for an instant sweep, its full
940
+ result. DON'T WAIT: poll `project_status` (its `jobs` section: never
941
+ errors, never blocks, reports failed jobs); re-invoke to join; a
942
+ completed sweep's re-invoke returns its full result. `budget_s=<seconds>`
943
+ bounds the WORK (not the call): files not reached are deferred
944
+ (`complete=false, remaining=N`) — re-invoke to continue (finished files
945
+ re-skip via the content-hash gate)."""
946
+ res = await crib.project_index(
947
+ project, cwd=_cwd(project_path), budget_s=budget_s
948
+ ) # the polling contract — a RUNNING HANDLE at once (wait_s=None)
949
+ return _switch_if_created(res)
931
950
 
932
951
  @crib_tool("none")
933
952
  async def project_relocate(
@@ -966,13 +985,18 @@ def build_server(crib: Crib | None = None):
966
985
  project: str | None = None,
967
986
  project_path: str | None = None,
968
987
  wait_s: float = 30.0,
988
+ ctx: Context | None = None,
969
989
  ) -> dict[str, Any]:
970
- """Bounded-block on a running index job for this project — the JOIN
971
- primitive for clients whose tool timeout is shorter than a sweep.
972
- `{running: false}` when nothing is running; the final result if the
973
- sweep completes within wait_s; else the live partial state (call again
974
- to keep waiting). Never starts a sweep."""
975
- return await crib.project_wait(project, cwd=_cwd(project_path), wait_s=wait_s)
990
+ """PREFER POLLING (`project_status`'s `jobs` section) — a blocking wait
991
+ ties up a client request and gets cut off at proxy caps. This verb is
992
+ the JOIN primitive for scripts/terminals only: bounded-block on a
993
+ running index job for this project. The final result if the sweep
994
+ completes within wait_s; else the live partial state (a re-invoke keeps
995
+ waiting). Emits progress markers while it waits (`42/317 files (13%) ·
996
+ eta 1:50`). Never starts a sweep; `{running: false}` when idle."""
997
+ return await crib.project_wait(
998
+ project, cwd=_cwd(project_path), wait_s=wait_s, ctx=ctx
999
+ )
976
1000
 
977
1001
  @crib_tool("source")
978
1002
  async def project_cancel(
@@ -2256,10 +2280,13 @@ def _pin_legacy_era(mcp) -> None:
2256
2280
 
2257
2281
 
2258
2282
  async def _serve_async(
2259
- transport: str = "stdio", host: str = "127.0.0.1", port: int = 8787
2283
+ transport: str = "stdio",
2284
+ host: str = "127.0.0.1",
2285
+ port: int = 8787,
2286
+ tools: str | list[str] | None = None,
2260
2287
  ) -> None:
2261
2288
  crib = Crib.open()
2262
- mcp = build_server(crib)
2289
+ mcp = build_server(crib, tools=tools)
2263
2290
  # Watcher runs on THIS loop so its index_file calls share the per-path locks
2264
2291
  # with the tool calls (DESIGN §4) — correctness depends on one loop.
2265
2292
  if crib.config.watch:
@@ -2307,8 +2334,13 @@ async def _serve_async(
2307
2334
  crib.close()
2308
2335
 
2309
2336
 
2310
- def main(transport: str = "stdio", host: str = "127.0.0.1", port: int = 8787) -> None:
2311
- asyncio.run(_serve_async(transport, host, port))
2337
+ def main(
2338
+ transport: str = "stdio",
2339
+ host: str = "127.0.0.1",
2340
+ port: int = 8787,
2341
+ tools: str | list[str] | None = None,
2342
+ ) -> None:
2343
+ asyncio.run(_serve_async(transport, host, port, tools=tools))
2312
2344
 
2313
2345
 
2314
2346
  if __name__ == "__main__":
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cribsheet
3
- Version: 0.21.2-dev4
3
+ Version: 0.21.3-dev2
4
4
  Summary: Local MCP server: markdown memory with a Chroma embedding index
5
5
  Requires-Python: >=3.13
6
6
  Requires-Dist: chromadb>=0.5
@@ -1,15 +1,15 @@
1
1
  crib/__init__.py,sha256=zj2qVJwYgLInI0Ie2N4NeJQw1ltiUhCM6_umP4skhcg,1005
2
2
  crib/__main__.py,sha256=umIc03A2oA7s2oiL80Ts_QnS-0zj9fjV3IQ103AmNXg,232
3
- crib/app.py,sha256=pi8gEo5p_yhj2mPd-K9cPMtEO8-WPLz_g5Fjgy32vzo,252993
3
+ crib/app.py,sha256=08U7X_KRgZXF7wQkoFroyQsqcVdzXOArkLRwqgq224A,257871
4
4
  crib/chunk.py,sha256=GDGpmVE7JhP7zVy0TzbCBSRO0PnQUIXQISsxkC7SWKA,13653
5
5
  crib/claudemem.py,sha256=Xf4mVgTFbXHdhhqteTIRz2zirc4irf0wim8AeMybudI,4804
6
- crib/cli.py,sha256=3CbIsTe605koilnaW-KUwIS61Uc9NT9zC-zGsyRg8gc,139498
6
+ crib/cli.py,sha256=w72-MYdZBf_zY_J1ybDWZMWvo-Wvc_McI8IGVWXsu9c,140883
7
7
  crib/client.py,sha256=fjd2QwvbSNZmq9eXWFgQsMq_2o5-OLH7ZhE48xLxMNs,6602
8
8
  crib/codeindex.py,sha256=Xw-37_uOarZvIledYEUqSzc1PA-DrOVNmdx_94MvJ6E,89312
9
9
  crib/codeindexer.py,sha256=E0A9PGKJPp413-W3R_e5JlxHMnY-9g3Vg1MA9ixNA4w,33769
10
10
  crib/codequery.py,sha256=q_3rjkX9_LbNWvuCWL3u9xTEQn6PqhPFTLl0XHgf3zY,38346
11
11
  crib/codestore.py,sha256=KKgqwgweIJqY2oVy5cx_9cRd7kDgekkrduQMcQ5sOD4,20128
12
- crib/config.py,sha256=LSKizCsHuYJMQwBZXid21cupZ19Hv8C8P4zyw2Ap2S4,29263
12
+ crib/config.py,sha256=4DpHNvOaevAhg7zaRqb-cwjB1i_m2FhPLAu2iDUO4HU,29867
13
13
  crib/describe_queue.py,sha256=orr6BTq9bch5dHTR_cAxEXr8PTqqVy7_a21yc94Amrk,6644
14
14
  crib/designs.py,sha256=Sy080YchgLowJnDP3cgFPFO6YTq9hCY1BqekuiNM0yU,138997
15
15
  crib/embed.py,sha256=f5m4Sa7sKiCN0cXj9-n5x2yoLEBQix105V6xJge0h5w,10347
@@ -28,7 +28,7 @@ crib/project_services.py,sha256=dOPz7RUdw_QS9AeR18d2gcnk6Z9JzeK9nRiFafF_IuI,2112
28
28
  crib/refs.py,sha256=A42tIAg2vsgjp4r7Gdp1PyfmWm46jcnde9j_DfUpxo8,13106
29
29
  crib/retrieve.py,sha256=eeRiI1oE_02H_i_qDsS6804RvBpvh4BkwD-HYcQo35c,22149
30
30
  crib/section_index.py,sha256=nhFEZQBjlfV9y5fpB39Rp5RPFHLnp2nhZbAG8S7fUNg,8846
31
- crib/server.py,sha256=3ywaAp-q1oZq7isVjkpmShjhkQn_0wnlAcwMbh5lFRM,118399
31
+ crib/server.py,sha256=Rf96nmsCmCFHan61nzjzqpHHK4XePC4IrvrqBSTQHSY,118809
32
32
  crib/session.py,sha256=HMF_6n6ZIPY3p8mRJfMJ75iByKOoPIUvUJST1r8sSOQ,13631
33
33
  crib/sharedserver.py,sha256=SLGcF3Iax5ThPiFyCJ9ahs3movG-p5nNk0n8dahgWQo,1919
34
34
  crib/sources.py,sha256=gJNhRQeLTKC7v_KSSVGy7kaYgj_9iWJyz_Yd9W8512Q,2918
@@ -39,7 +39,7 @@ crib/tomlrec.py,sha256=ptDbYNhTLmXQeN1BrQGcy2E4wNv0hpKM7aayQ7WvkxE,3796
39
39
  crib/util.py,sha256=pf2iB3cvMC8JG5JJo7vH0t-7qy-d9ABHuSP7AJInauE,3018
40
40
  crib/versions.py,sha256=qFjPG9iFOEyRZ6K5CESM87JvbV1qf4tQoUIvqz-nADk,3621
41
41
  crib/watch.py,sha256=KpH-ipA-wkJVTxeghzM-Y9ljMAyrPxnmMumj3TNchmg,24303
42
- cribsheet-0.21.2.dev4.dist-info/METADATA,sha256=l3TJdunKdeWALa-OanzZr-3AtWGbbQYADxoCsPDt0YI,18790
43
- cribsheet-0.21.2.dev4.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
44
- cribsheet-0.21.2.dev4.dist-info/entry_points.txt,sha256=CjLxgcZdPGI6U4VRZmrwQ2kL1gUkNykYNkLzT8EQkfQ,39
45
- cribsheet-0.21.2.dev4.dist-info/RECORD,,
42
+ cribsheet-0.21.3.dev2.dist-info/METADATA,sha256=hDS4hdDe7FqYrbPwozhFL-z22wdV8RSmwuqps-MvDEQ,18790
43
+ cribsheet-0.21.3.dev2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
44
+ cribsheet-0.21.3.dev2.dist-info/entry_points.txt,sha256=CjLxgcZdPGI6U4VRZmrwQ2kL1gUkNykYNkLzT8EQkfQ,39
45
+ cribsheet-0.21.3.dev2.dist-info/RECORD,,