diffpilot 0.0.1__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.
diffpilot/cli.py ADDED
@@ -0,0 +1,731 @@
1
+ """diffpilot command line: Typer parses, then everything runs inside one asyncio event loop."""
2
+
3
+ import asyncio
4
+ import inspect
5
+ import json
6
+ import logging
7
+ import re
8
+ import sys
9
+ from collections.abc import Awaitable, Callable
10
+ from contextlib import nullcontext
11
+ from pathlib import Path
12
+ from typing import Annotated, Any
13
+
14
+ import typer
15
+ from pydantic_ai import Agent
16
+ from rich.console import Console
17
+ from rich.logging import RichHandler
18
+ from rich.markup import escape
19
+
20
+ from diffpilot import __version__, agentsmd, bootstrap, config, core, events, gitdiff, verify
21
+ from diffpilot.config import CONFIG_NAME, Config, DPError
22
+ from diffpilot.index import Index
23
+ from diffpilot.jev import Jev, rank
24
+ from diffpilot.llm import Engine
25
+ from diffpilot.ops import import_doc, open_index
26
+
27
+ out = Console(highlight=False, soft_wrap=True)
28
+ err = Console(stderr=True, highlight=False)
29
+ log = logging.getLogger('diffpilot')
30
+
31
+ HELP = """\
32
+ Project memory for coding agents. diffpilot keeps product requirements, design rationale, project rules and the
33
+ changelog in Markdown stores, and answers questions about them with citations. Records describe what was decided
34
+ before; the user's current request always takes precedence.
35
+
36
+ \b
37
+ typical workflow:
38
+ diffpilot brief "<task>" before a non-trivial task: relevant requirements, decisions, rules, tensions
39
+ diffpilot note "<what and why>" during work, at each decision / gotcha / new user rule (instant, no LLM)
40
+ diffpilot finish end of task: notes + git diff -> stores, reviewed (takes minutes)
41
+ diffpilot ask "<question>" any time: requirements, why something is built a certain way, how to do X
42
+
43
+ \b
44
+ instant lookups (no LLM): outline, show <ref>, search "<terms>", log
45
+ setup / maintenance: init [--bootstrap], coverage <doc>, import <doc>, verify, update_agentsmd,
46
+ git_diff_changelog_summary, doctor, sync, inbox
47
+
48
+ \b
49
+ Long input: pass "-" and pipe text on stdin. Every command supports --json.
50
+ exit codes: 0 ok, 1 usage/config, 2 Codex auth (run `codex login`), 3 LLM failure (input kept: `inbox --process`),
51
+ 4 invalid model output (nothing written), 5 lock busy
52
+ """
53
+
54
+ app = typer.Typer(
55
+ help=HELP,
56
+ no_args_is_help=True,
57
+ add_completion=False,
58
+ rich_markup_mode=None,
59
+ pretty_exceptions_enable=False,
60
+ context_settings={'help_option_names': ['-h', '--help'], 'max_content_width': 120},
61
+ )
62
+
63
+ Text = Annotated[
64
+ str | None, typer.Argument(metavar='TEXT', help='The text, or - to read it from stdin.', show_default=False)
65
+ ]
66
+ FromFile = Annotated[
67
+ Path | None, typer.Option('--from-file', metavar='PATH', help='Read the text from a file.', show_default=False)
68
+ ]
69
+ Files = Annotated[
70
+ list[str] | None,
71
+ typer.Option('--files', metavar='PATH', help='Related code path (repeatable).', show_default=False),
72
+ ]
73
+ NoCache = Annotated[bool, typer.Option('--no-cache', help='Ignore the cached answer.')]
74
+
75
+ _OPTIONS = [
76
+ inspect.Parameter(
77
+ 'as_json',
78
+ inspect.Parameter.KEYWORD_ONLY,
79
+ default=False,
80
+ annotation=Annotated[bool, typer.Option('--json', help='Machine-readable output.')],
81
+ ),
82
+ inspect.Parameter(
83
+ 'quiet',
84
+ inspect.Parameter.KEYWORD_ONLY,
85
+ default=False,
86
+ annotation=Annotated[
87
+ bool, typer.Option('--quiet', '-q', help='Print only the first result line; errors only on stderr.')
88
+ ],
89
+ ),
90
+ ]
91
+
92
+
93
+ # --- output ----------------------------------------------------------------
94
+
95
+
96
+ def emit(text: str) -> None:
97
+ out.print(text, markup=False)
98
+
99
+
100
+ def busy(msg: str) -> Any:
101
+ return err.status(msg) if err.is_terminal else nullcontext()
102
+
103
+
104
+ def render_lines(res: dict) -> None:
105
+ for line in res.get('lines', []):
106
+ emit(line)
107
+ for w in res.get('warnings', []):
108
+ emit(f'Warning {w}')
109
+ for c in res.get('code_comments', []):
110
+ emit(f'Suggested code comment (optional): {c}')
111
+
112
+
113
+ def _cited(items: list[dict]) -> str:
114
+ return '\n'.join(
115
+ f'- {c["ref"]} — {c["text"]}' + (f' [updated {c["updated"]}]' if c.get('updated') else '') for c in items
116
+ )
117
+
118
+
119
+ def render_ask(res: dict) -> None:
120
+ parts = [f'Answer: {res["answer"]}']
121
+ if res.get('records'):
122
+ parts.append(f'Recorded context:\n{_cited(res["records"])}')
123
+ if res.get('gaps'):
124
+ parts.append('Gaps: ' + '; '.join(res['gaps']))
125
+ parts.append(f'Confidence: {res["confidence"]}' + (' (cached)' if res.get('cached') else ''))
126
+ emit('\n\n'.join(parts))
127
+
128
+
129
+ def render_brief(res: dict) -> None:
130
+ sections = (
131
+ ('requirements', 'Relevant requirements'),
132
+ ('decisions', 'Relevant decisions & gotchas'),
133
+ ('instructions', 'Applicable instructions'),
134
+ )
135
+ parts = [f'{title}:\n{_cited(res[key])}' for key, title in sections if res.get(key)]
136
+ lists = (
137
+ ('tensions', 'Possible tensions (information, not requirements)'),
138
+ ('consider_recording', 'After implementing, consider recording'),
139
+ )
140
+ parts += [f'{title}:\n' + '\n'.join(f'- {t}' for t in res[key]) for key, title in lists if res.get(key)]
141
+ if res.get('gaps'):
142
+ parts.append('Not recorded: ' + '; '.join(res['gaps']))
143
+ emit('\n\n'.join(parts) or 'Nothing relevant is recorded for this task.')
144
+
145
+
146
+ def render_init(res: dict) -> None:
147
+ render_lines(res)
148
+ if not (b := res.get('bootstrap')):
149
+ return
150
+ emit(
151
+ f'Bootstrap: {b["sources"]} sources ({b["skipped_unchanged"]} unchanged), {b["chunks"]} new chunks, '
152
+ f'{b["facts"]} facts ({b["dropped"]} dropped: quote not found)'
153
+ + (f', {b["triaged"]} chunks skipped by Jev (no durable knowledge)' if b.get('triaged') else '')
154
+ + (f', {b["recorded"]} facts already recorded' if b.get('recorded') else '')
155
+ )
156
+ render_lines(b)
157
+ if b['conflicts']:
158
+ emit('Conflicts (not written):\n' + '\n'.join(f'- {c}' for c in b['conflicts']))
159
+ if b['orphaned']:
160
+ emit('Orphaned (source deleted): ' + ', '.join(b['orphaned']))
161
+ if b['events']:
162
+ emit('Events ' + ', '.join(b['events']))
163
+
164
+
165
+ def render_search(res: dict) -> None:
166
+ emit('\n'.join(f'- {h["ref"]} | {h["heading"]} | {h["summary"]}' for h in res['hits']) or 'No hits.')
167
+
168
+
169
+ def render_log(res: dict) -> None:
170
+ rows = [f'{e["ts"][:16]} {e["id"]} {e["command"]:<9} {e.get("summary", "")}' for e in res['events']]
171
+ emit('\n'.join(rows) or 'No events.')
172
+
173
+
174
+ def render_agentsmd(res: dict) -> None:
175
+ render_lines(res)
176
+ if res.get('changed') and res.get('resume'):
177
+ emit(f'\n## diffpilot - resume\n\n{res["resume"]}')
178
+
179
+
180
+ # --- runtime ---------------------------------------------------------------
181
+
182
+
183
+ def setup_logging(cfg: Config, quiet: bool = False) -> None:
184
+ """Apply the configured level to diffpilot's own logger; libraries (HTTP clients) log only at debug."""
185
+ level = 'ERROR' if quiet else cfg.logging.level.upper()
186
+ logging.basicConfig(format='%(message)s', handlers=[RichHandler(console=err, show_path=False, show_time=False)])
187
+ logging.getLogger().setLevel(level if level == 'DEBUG' else max(logging.WARNING, logging.getLevelName(level)))
188
+ log.setLevel(level)
189
+
190
+
191
+ async def execute(
192
+ name: str,
193
+ fn: Callable[..., Awaitable[dict]],
194
+ kwargs: dict,
195
+ render: Callable[[dict], None],
196
+ as_json: bool,
197
+ quiet: bool,
198
+ ) -> int:
199
+ try:
200
+ cfg = config.load()
201
+ setup_logging(cfg, quiet)
202
+ res = await fn(cfg, **kwargs)
203
+ except DPError as e:
204
+ if as_json:
205
+ out.print_json(data={'ok': False, 'error': str(e), 'code': e.code})
206
+ else:
207
+ err.print(f'[red]diffpilot error:[/red] {escape(str(e))}')
208
+ if e.code == 3 and name in WRITE_STORES:
209
+ err.print('Your input is saved; retry later with `diffpilot inbox --process`.')
210
+ return e.code
211
+ if name not in ('note', 'finish', 'init') and not as_json and (pending := len(events.notes(cfg))):
212
+ err.print(f'diffpilot: {pending} unprocessed note(s) — run `diffpilot finish` at the end of the task.')
213
+ if as_json:
214
+ out.print_json(json.dumps(res, ensure_ascii=False, default=str))
215
+ elif quiet and res.get('lines'):
216
+ emit(res['lines'][0])
217
+ else:
218
+ render(res)
219
+ return 0 if res.get('ok', True) else 1
220
+
221
+
222
+ def command(name: str, *aliases: str, render: Callable[[dict], None] = render_lines) -> Callable:
223
+ """Register `async def fn(cfg, ...) -> dict` as a Typer command (plus hidden aliases) with --json / -q."""
224
+
225
+ def deco(fn: Callable[..., Awaitable[dict]]) -> Callable[..., Awaitable[dict]]:
226
+ params = [p for p in inspect.signature(fn).parameters.values() if p.name != 'cfg']
227
+
228
+ def run(**kwargs: Any) -> None:
229
+ as_json, quiet = kwargs.pop('as_json'), kwargs.pop('quiet')
230
+ try:
231
+ code = asyncio.run(execute(name, fn, kwargs, render, as_json, quiet))
232
+ except KeyboardInterrupt:
233
+ code = 130
234
+ raise typer.Exit(code)
235
+
236
+ run.__signature__ = inspect.Signature([*params, *_OPTIONS]) # type: ignore[attr-defined]
237
+ run.__doc__ = fn.__doc__
238
+ short = (fn.__doc__ or '').strip().split('\n')[0]
239
+ app.command(name, short_help=short)(run)
240
+ for alias in aliases:
241
+ app.command(alias, hidden=True)(run)
242
+ return fn
243
+
244
+ return deco
245
+
246
+
247
+ def read_input(text: str | None, from_file: Path | None, required: bool = True) -> str:
248
+ if from_file:
249
+ return from_file.read_text(encoding='utf-8')
250
+ if text == '-' or (text is None and required and not sys.stdin.isatty()):
251
+ return sys.stdin.read()
252
+ if not text and required:
253
+ raise DPError('no input given (pass text, `-` for stdin, or --from-file)')
254
+ return text or ''
255
+
256
+
257
+ def version_callback(value: bool) -> None:
258
+ if value:
259
+ emit(f'diffpilot {__version__}')
260
+ raise typer.Exit()
261
+
262
+
263
+ @app.callback()
264
+ def main_options(
265
+ version: Annotated[
266
+ bool, typer.Option('--version', callback=version_callback, is_eager=True, help='Show the version.')
267
+ ] = False,
268
+ ) -> None:
269
+ pass
270
+
271
+
272
+ # --- commands --------------------------------------------------------------
273
+
274
+
275
+ @command('init', render=render_init)
276
+ async def init(
277
+ cfg: Config,
278
+ with_bootstrap: Annotated[
279
+ bool, typer.Option('--bootstrap', help='Seed the stores from existing project docs.')
280
+ ] = False,
281
+ include: Annotated[list[str] | None, typer.Option(help='Bootstrap: only these globs (repeatable).')] = None,
282
+ exclude: Annotated[list[str] | None, typer.Option(help='Bootstrap: skip these globs (repeatable).')] = None,
283
+ max_files: Annotated[int, typer.Option(help='Bootstrap: at most this many source files.')] = 200,
284
+ force: Annotated[bool, typer.Option(help='Bootstrap: re-read unchanged sources too.')] = False,
285
+ ) -> dict:
286
+ """Create the global and project diffpilot.toml, the stores and the ## diffpilot section of AGENTS.md.
287
+
288
+ --bootstrap also studies the existing docs (README, docs/, AGENTS.md, ...) and seeds the stores. Safe to re-run:
289
+ unchanged sources are skipped, explicitly recorded knowledge is never overwritten.
290
+ """
291
+ lines = []
292
+ glob = cfg.home / CONFIG_NAME
293
+ if not glob.exists():
294
+ cfg.home.mkdir(parents=True, exist_ok=True)
295
+ glob.write_text(config.GLOBAL_TOML, encoding='utf-8')
296
+ glob.chmod(0o600) # holds credentials
297
+ lines.append(f'Created {glob} (global settings, shared by all projects)')
298
+ if not (cfg.root / CONFIG_NAME).exists():
299
+ (cfg.root / CONFIG_NAME).write_text(config.DEFAULT_TOML, encoding='utf-8')
300
+ lines.append(f'Created {CONFIG_NAME}')
301
+ lines += [f'Created {p}' for p in core.ensure_stores(cfg)]
302
+ gi = cfg.state / '.gitignore'
303
+ if not gi.exists():
304
+ cfg.state.mkdir(parents=True, exist_ok=True)
305
+ gi.write_text('cache/\nruns/\nruns.jsonl\ninbox.jsonl\nnotes.jsonl\nlock\n', encoding='utf-8')
306
+ lines.append(f'Created {cfg.rel(gi)}')
307
+ if not cfg.store_path('changelog').exists():
308
+ events.refresh_unreleased(cfg)
309
+ lines.append(f'Created {cfg.paths.changelog}')
310
+ if agentsmd.write_tool_section(cfg):
311
+ lines.append(f'Updated {cfg.paths.agents_md} (## diffpilot section)')
312
+ open_index(cfg)
313
+ res: dict = {'ok': True, 'lines': lines or ['Already initialized.']}
314
+ if with_bootstrap:
315
+ with busy('Bootstrapping from project docs…'):
316
+ res['bootstrap'] = await bootstrap.run(cfg, include or [], exclude or [], max_files, force)
317
+ return res
318
+
319
+
320
+ @command('brief', render=render_brief)
321
+ async def brief(
322
+ cfg: Config, text: Text = None, from_file: FromFile = None, files: Files = None, no_cache: NoCache = False
323
+ ) -> dict:
324
+ """Pre-flight brief for a task you are about to implement.
325
+
326
+ Example: diffpilot brief "Add seasonal offers to the shop"
327
+ """
328
+ with busy('Thinking…'):
329
+ return await core.query(
330
+ cfg, 'brief', read_input(text, from_file), core.code_paths(cfg, files or []), not no_cache
331
+ )
332
+
333
+
334
+ @command('ask', render=render_ask)
335
+ async def ask(
336
+ cfg: Config, text: Text = None, from_file: FromFile = None, files: Files = None, no_cache: NoCache = False
337
+ ) -> dict:
338
+ """Answer a question about the project from the stores (and code), with citations.
339
+
340
+ Example: diffpilot ask "Why is the shop grid fixed at 3 columns?"
341
+ """
342
+ with busy('Thinking…'):
343
+ return await core.query(
344
+ cfg, 'ask', read_input(text, from_file), core.code_paths(cfg, files or []), not no_cache
345
+ )
346
+
347
+
348
+ @command('note')
349
+ async def note(cfg: Config, text: Text = None, from_file: FromFile = None, files: Files = None) -> dict:
350
+ """Append a work note (instant, no LLM); integrated into the stores by finish.
351
+
352
+ Example: diffpilot note "Shop grid fixed at 3 columns: the legacy UI scaler breaks at 4" --files src/shop.ts
353
+ """
354
+ return events.note(cfg, read_input(text, from_file), core.code_paths(cfg, files or []))
355
+
356
+
357
+ @command('finish')
358
+ async def finish(
359
+ cfg: Config,
360
+ text: Text = None,
361
+ from_file: FromFile = None,
362
+ files: Files = None,
363
+ no_diff: Annotated[
364
+ bool, typer.Option('--no-diff', help='Do not run git diff: notes only, --files as code context.')
365
+ ] = False,
366
+ ) -> dict:
367
+ """Integrate pending notes and the task git diff into the stores (end of task).
368
+
369
+ Optional text is added as a final note. Later notes win over earlier ones; the diff is evidence only.
370
+ """
371
+ with busy('Integrating notes…'):
372
+ text_ = read_input(text, from_file, required=False)
373
+ return await core.finish(cfg, text_, core.code_paths(cfg, files or []), not no_diff)
374
+
375
+
376
+ WRITE_STORES = {'record': None, 'prd': 'prd', 'impl': 'impl', 'instruct': 'instructions'}
377
+ WRITE_HELP = {
378
+ 'record': 'Write knowledge to the stores immediately (routed to the right store; slow, reviewed).\n\n'
379
+ 'Prefer note + finish during normal work.',
380
+ 'prd': 'Like record, but only product requirements (prd and its categories).',
381
+ 'impl': 'Like record, but only implementation notes (how and why).',
382
+ 'instruct': 'Like record, but only project instructions (rules).',
383
+ }
384
+
385
+
386
+ def _write_command(name: str) -> None:
387
+ async def write(cfg: Config, text: Text = None, from_file: FromFile = None, files: Files = None) -> dict:
388
+ with busy('Recording…'):
389
+ files_ = core.code_paths(cfg, files or [])
390
+ return await core.record(cfg, read_input(text, from_file), WRITE_STORES[name], files_, name)
391
+
392
+ write.__doc__ = WRITE_HELP[name]
393
+ command(name, *(['instructions'] if name == 'instruct' else []))(write)
394
+
395
+
396
+ for _name in WRITE_STORES:
397
+ _write_command(_name)
398
+
399
+
400
+ @command('outline', render=lambda res: emit(res['outline']))
401
+ async def outline(
402
+ cfg: Config,
403
+ store: Annotated[str | None, typer.Argument(help='prd, impl, instructions or a PRD category (prd.<name>).')] = None,
404
+ depth: Annotated[int, typer.Option(help='Heading levels to show (0 = all).')] = 0,
405
+ grep: Annotated[str, typer.Option(help='Only sections whose ref, heading or summary contains this.')] = '',
406
+ ) -> dict:
407
+ """Section tree with refs and one-line summaries (no LLM)."""
408
+ idx = open_index(cfg)
409
+ stores = cfg.family(store) if store else cfg.stores
410
+ if not stores:
411
+ raise DPError(f'unknown store {store!r}; stores: {", ".join(cfg.stores)}')
412
+ return {
413
+ 'outline': idx.outline(stores, depth, grep),
414
+ 'sections': {r: idx.sections[r] for r, v in idx.views.items() if v.store in stores},
415
+ }
416
+
417
+
418
+ @command('show', render=lambda res: emit(res['text']))
419
+ async def show(
420
+ cfg: Config,
421
+ refs: Annotated[list[str], typer.Argument(help='Section refs, unique ref prefixes or exact headings.')],
422
+ ) -> dict:
423
+ """Print sections by ref, e.g. prd:shop.cards, a unique prefix (prd:shop.ca) or a heading ("Shop cards")."""
424
+ idx = open_index(cfg)
425
+ found: list[str] = []
426
+ missing: list[str] = []
427
+ ambiguous: list[str] = []
428
+ for q in refs:
429
+ match = idx.resolve(q)
430
+ if len(match) == 1:
431
+ found.append(match[0])
432
+ else:
433
+ (ambiguous if match else missing).append(q)
434
+ if match:
435
+ ambiguous[-1] += ' → ' + ', '.join(match[:8]) + (' …' if len(match) > 8 else '')
436
+ text = '\n\n'.join(idx.show(r) for r in found)
437
+ if missing:
438
+ text += ('\n\n' if text else '') + 'Not found: ' + ', '.join(missing) + ' (try `diffpilot search`)'
439
+ if ambiguous:
440
+ text += ('\n\n' if text else '') + 'Ambiguous: ' + '; '.join(ambiguous)
441
+ return {
442
+ 'text': text,
443
+ 'sections': {r: {'body': idx.views[r].body, **idx.sections[r]} for r in found},
444
+ 'missing': missing,
445
+ 'ambiguous': ambiguous,
446
+ }
447
+
448
+
449
+ @command('search', render=render_search)
450
+ async def search(
451
+ cfg: Config,
452
+ terms: Annotated[str, typer.Argument(help='What to look for.')],
453
+ limit: Annotated[int, typer.Option(help='Maximum number of hits.')] = 8,
454
+ rerank: Annotated[bool, typer.Option(help='Rerank by relevance with Jev (needs an OpenRouter key).')] = False,
455
+ store: Annotated[str | None, typer.Option(help='Only this store and its categories, e.g. prd.')] = None,
456
+ ) -> dict:
457
+ """Keyword search over all sections (no LLM; --rerank adds one fast Jev request)."""
458
+ idx = open_index(cfg)
459
+ jev = Jev(cfg) if rerank else None
460
+ if jev and not jev.available:
461
+ raise DPError('--rerank needs [auth].openrouter_api_key in diffpilot.toml (or $OPENROUTER_API_KEY)')
462
+ stores = cfg.family(store) if store else cfg.stores
463
+ if not stores:
464
+ raise DPError(f'unknown store {store!r}; stores: {", ".join(cfg.stores)}')
465
+ hits = await rank(jev, idx, terms, limit, stores, cfg.jev.threshold)
466
+ return {
467
+ 'hits': [
468
+ {'ref': r, 'heading': idx.views[r].path, 'summary': idx.summary(r), 'score': round(s, 2)} for r, s in hits
469
+ ]
470
+ }
471
+
472
+
473
+ @command('log', render=render_log)
474
+ async def log_(
475
+ cfg: Config,
476
+ n: Annotated[int, typer.Option('-n', help='Number of events.')] = 20,
477
+ since: Annotated[str | None, typer.Option(help='Event id or ISO date.')] = None,
478
+ ) -> dict:
479
+ """Recent change events (no LLM)."""
480
+ rows = events.events(cfg)
481
+ if since:
482
+ ids = [e['id'] for e in rows]
483
+ rows = rows[ids.index(since) + 1 :] if since in ids else [e for e in rows if e['ts'] >= since]
484
+ return {'events': rows[-n:]}
485
+
486
+
487
+ @command('git_diff_changelog_summary', 'git-diff-changelog-summary')
488
+ async def changelog(
489
+ cfg: Config,
490
+ base: Annotated[str | None, typer.Option(help='Diff from this ref to the working tree.')] = None,
491
+ range_: Annotated[str | None, typer.Option('--range', help='Explicit range A..B.')] = None,
492
+ staged: Annotated[bool, typer.Option(help='Only staged changes.')] = False,
493
+ write: Annotated[bool, typer.Option(help='Insert into the changelog and mark events released.')] = False,
494
+ version: Annotated[str | None, typer.Option('--version', help='Release version for the entry title.')] = None,
495
+ ) -> dict:
496
+ """One changelog entry from the git diff and recorded changes.
497
+
498
+ Default range: since the last --write release, else the last tag, else uncommitted changes.
499
+ """
500
+ with busy('Summarizing changes…'):
501
+ return await gitdiff.summarize(cfg, base, range_, staged, write, version)
502
+
503
+
504
+ @command('coverage')
505
+ async def coverage(
506
+ cfg: Config,
507
+ paths: Annotated[list[str], typer.Argument(metavar='PATH', help='Documents to check, e.g. docs/design.md.')],
508
+ fix: Annotated[bool, typer.Option(help='Merge the missing and partial facts into the stores.')] = False,
509
+ into: Annotated[
510
+ str | None, typer.Option(help='--fix: write only to this store (and its categories), e.g. instructions.')
511
+ ] = None,
512
+ ) -> dict:
513
+ """How much of a document's durable knowledge the stores already hold (fast model + Jev).
514
+
515
+ Extracts the facts of each document, checks every fact against the stores (Jev, then the fast model for unsure
516
+ ones) and lists what is missing or partial. Use it before deleting a document the stores are meant to replace:
517
+ `coverage <doc> --fix` merges the gaps; re-run until nothing important is missing.
518
+ """
519
+ with busy('Checking coverage…'):
520
+ return await bootstrap.coverage(cfg, core.code_paths(cfg, paths), fix, into)
521
+
522
+
523
+ @command('import')
524
+ async def import_(
525
+ cfg: Config,
526
+ path: Annotated[str, typer.Argument(metavar='PATH', help='Document to move, e.g. docs/ui-style.md.')],
527
+ into: Annotated[str, typer.Option(help='Target store, or store:<parent-id> to nest under a section.')],
528
+ ) -> dict:
529
+ """Move a document into a store verbatim (no LLM): text and headings kept, headings demoted, refs added.
530
+
531
+ Unlike `coverage --fix`, nothing is rewritten, so exact numbers and names survive. The source file is left in
532
+ place; check the result with `show`, then delete the source.
533
+ """
534
+ return import_doc(cfg, core.code_paths(cfg, [path])[0], into)
535
+
536
+
537
+ @command('verify')
538
+ async def verify_(
539
+ cfg: Config,
540
+ targets: Annotated[
541
+ list[str] | None, typer.Argument(metavar='STORE|REF', help='Stores or sections to check (default: all).')
542
+ ] = None,
543
+ show_all: Annotated[bool, typer.Option('--all', help='Also list matches and unresolved claims.')] = False,
544
+ ) -> dict:
545
+ """Check numbers the stores state against the data files in [verify].data (no LLM, never writes).
546
+
547
+ A claim is a key next to a number (`cards: 4`, `goal 22`, `FORMAT is 9`, `40%` = 0.4), read inside the block of
548
+ the entry the line names (backticked id, bold name, table cell, else the heading). History sections are skipped.
549
+ """
550
+ res = verify.verify(cfg, open_index(cfg), targets or [])
551
+ if show_all:
552
+ res['lines'] += [
553
+ f'- {c["status"]:<10} {c["ref"]} [{c["line"]}] {c["entry"]} {c["key"]} = {c["value"]}'
554
+ + (f', data: {c["data"]} [{c["where"]}]' if c['where'] else '')
555
+ + f' ({c["note"]})'
556
+ for c in res['claims']
557
+ if c['status'] != 'mismatch'
558
+ ]
559
+ return res
560
+
561
+
562
+ @command('update_agentsmd', 'update-agentsmd', render=render_agentsmd)
563
+ async def update_agentsmd(
564
+ cfg: Config, force: Annotated[bool, typer.Option(help='Run even if nothing changed.')] = False
565
+ ) -> dict:
566
+ """Refresh the ## diffpilot and ## diffpilot - resume sections of AGENTS.md.
567
+
568
+ Run it rarely (developer-driven). The resume is rewritten from the stores without repeating what AGENTS.md
569
+ already says; manual edits to the resume are kept when still accurate.
570
+ """
571
+ with busy('Reviewing AGENTS.md…'):
572
+ return await core.update_agentsmd(cfg, force)
573
+
574
+
575
+ @command('sync')
576
+ async def sync(cfg: Config) -> dict:
577
+ """Re-index the stores after manual edits (no LLM)."""
578
+ before = len(events.events(cfg))
579
+ open_index(cfg)
580
+ after = events.events(cfg)
581
+ line = f'Recorded manual edits: {after[-1]["summary"]}' if len(after) > before else 'Index up to date.'
582
+ return {'ok': True, 'lines': [line]}
583
+
584
+
585
+ @command('doctor')
586
+ async def doctor(
587
+ cfg: Config, offline: Annotated[bool, typer.Option(help='Skip the Codex and Jev requests.')] = False
588
+ ) -> dict:
589
+ """Check config, Codex auth, models, Jev and stores."""
590
+ glob = cfg.home / CONFIG_NAME
591
+ auth = cfg.codex_home / 'auth.json'
592
+ jev_state = 'disabled' if not cfg.jev.enabled else 'on' if cfg.openrouter_key else 'off (no OpenRouter key)'
593
+ checks = [
594
+ (
595
+ 'config',
596
+ f'{cfg.root / CONFIG_NAME}' + ('' if cfg.file_exists else ' (missing, using defaults)'),
597
+ cfg.file_exists,
598
+ ),
599
+ ('codex auth', str(auth), auth.exists() or bool(cfg.openrouter_key)),
600
+ ('global config', str(glob), glob.exists()),
601
+ ('jev', f'{cfg.jev.model}: {jev_state}', True),
602
+ ]
603
+ idx = open_index(cfg)
604
+ checks += [(f'store {st}', _store_size(cfg, idx, st), cfg.store_path(st).exists()) for st in cfg.stores]
605
+ docs = _doc_checks(cfg, idx)
606
+ checks += [(n, c.pop('detail'), n == 'history paths' or not c['items']) for n, c in docs.items()]
607
+ pending = events.inbox(cfg)
608
+ checks += [
609
+ ('index', f'{len(idx.views)} sections, {len(idx.stale())} without summary', True),
610
+ ('inbox', f'{len(pending)} pending input(s)', not pending),
611
+ ('notes', f'{len(events.notes(cfg))} unprocessed note(s)', True),
612
+ ]
613
+ if not offline:
614
+ checks += await _ping(cfg)
615
+ return {
616
+ 'ok': all(ok for _, _, ok in checks[:2]),
617
+ 'checks': [{'name': n, 'detail': d, 'ok': o, **docs.get(n, {})} for n, d, o in checks],
618
+ 'lines': [f'{_label(name, ok)} {name}: {detail}' for name, detail, ok in checks],
619
+ }
620
+
621
+
622
+ def _store_size(cfg: Config, idx: Index, st: str) -> str:
623
+ views = [v for v in idx.views.values() if v.store == st]
624
+ big = max(views, key=lambda v: v.tokens, default=None)
625
+ size = f'{len(views)} sections, ~{sum(v.tokens for v in views)}t'
626
+ return f'{cfg.rel(cfg.store_path(st))} ({size}' + (f'; largest {big.ref} ~{big.tokens}t)' if big else ')')
627
+
628
+
629
+ WARN_ONLY = {'paths', 'stray stores', 'unread docs'}
630
+
631
+
632
+ def _label(name: str, ok: bool) -> str:
633
+ return 'ok ' if ok else 'warn' if name in WARN_ONLY else 'FAIL'
634
+
635
+
636
+ BACKTICK_PATH = re.compile(r'`([\w.-]+(?:/[\w.-]+)+/?)(?::\d[\d-]*)?`')
637
+
638
+
639
+ def _doc_checks(cfg: Config, idx: Index) -> dict[str, dict]:
640
+ """Warnings (not failures), with the full item lists for --json: dead paths, stray dp:id files, unread docs.
641
+
642
+ A path counts only when its first segment is a top-level entry of the repository (`crates/x.rs`, not
643
+ `08a1/08a2` or `Contents/Info.plist`) and it is not git-ignored; dead paths in history sections are listed apart.
644
+ """
645
+ top = {p.name for p in cfg.root.iterdir()}
646
+ found = {
647
+ (m.group(1).rstrip('/'), r)
648
+ for r, v in idx.views.items()
649
+ for m in BACKTICK_PATH.finditer(v.body)
650
+ if m.group(1).split('/')[0] in top and not (cfg.root / m.group(1)).exists()
651
+ }
652
+ ignored = config.git_ignored(cfg, sorted({p for p, _ in found}))
653
+ dead = sorted((p, r) for p, r in found if p not in ignored)
654
+ docs = bootstrap.inventory(cfg, [], cfg.doctor.ignore, 10_000)
655
+ stray = [d for d in docs if '<!-- dp:id=' in (cfg.root / d).read_text(encoding='utf-8', errors='replace')]
656
+ man = bootstrap.Manifest(cfg).data
657
+ unread = [
658
+ d
659
+ for d in docs
660
+ if d not in stray
661
+ and not man['files'].get(d, {}).get('chunks')
662
+ and d not in man.get('coverage', {})
663
+ and re.sub(r'(?m)^#.*$', '', bootstrap.read_source(cfg, d)).strip() # headings only: nothing to cover
664
+ ]
665
+
666
+ def check(items: list[str], what: str) -> dict:
667
+ shown = ': ' + ', '.join(items[:10]) + (f' … (+{len(items) - 10}, see --json)' if len(items) > 10 else '')
668
+ return {'detail': f'{len(items)} {what}' + (shown if items else ''), 'items': items}
669
+
670
+ current = [f'{p} ({r})' for p, r in dead if not idx.is_history(r)]
671
+ past = [f'{p} ({r})' for p, r in dead if idx.is_history(r)]
672
+ return {
673
+ 'paths': check(current, 'missing path(s) cited in current sections'),
674
+ 'history paths': check(past, 'missing path(s) cited in history sections (expected to age)'),
675
+ 'stray stores': check(stray, 'non-store file(s) with dp:id markers'),
676
+ 'unread docs': check(unread, 'doc(s) neither bootstrapped nor measured by `coverage` ([doctor].ignore)'),
677
+ }
678
+
679
+
680
+ async def _ping(cfg: Config) -> list[tuple[str, str, bool]]:
681
+ checks = []
682
+ ping = Agent(instructions='Reply with exactly: OK')
683
+ try:
684
+ async with Engine(cfg, 'doctor') as engine:
685
+ with busy(f'Contacting {engine.backend}…'):
686
+ for fast in (False, True):
687
+ reply = await engine.run(ping, 'ping', fast=fast)
688
+ name = (cfg.llm.fast_model if fast else '') or cfg.llm.model
689
+ checks.append((
690
+ f'model {name}',
691
+ 'responds' if 'OK' in reply else f'unexpected: {reply[:60]}',
692
+ 'OK' in reply,
693
+ ))
694
+ except DPError as e:
695
+ checks.append(('codex', str(e), False))
696
+ jev = Jev(cfg)
697
+ if jev.available:
698
+ with busy('Contacting Jev…'):
699
+ probs = await jev.probabilities('The sky is blue.', {'color': 'Does the text name a color?'})
700
+ ok = bool(probs and probs['color'] >= 0.5)
701
+ checks.append(('jev request', f'P(yes)={probs["color"]:.2f}' if probs else 'failed (see warnings)', ok))
702
+ return checks
703
+
704
+
705
+ @command('inbox')
706
+ async def inbox(cfg: Config, process: Annotated[bool, typer.Option(help='Retry the saved inputs.')] = False) -> dict:
707
+ """List or retry inputs saved after a failed LLM call."""
708
+ rows = events.inbox(cfg)
709
+ if not process:
710
+ return {
711
+ 'inbox': rows,
712
+ 'lines': [f'{r["id"]} {r["command"]}: {r["input"][:100]}' for r in rows] or ['Inbox empty.'],
713
+ }
714
+ lines = []
715
+ for r in rows:
716
+ if r['command'] not in WRITE_STORES:
717
+ events.inbox_remove(cfg, r['id'])
718
+ continue
719
+ res = await core.record(
720
+ cfg, r['input'], WRITE_STORES[r['command']], r['args'].get('files', []), r['command'], inbox_id=r['id']
721
+ )
722
+ lines += res['lines']
723
+ return {'ok': True, 'lines': lines or ['Inbox empty.']}
724
+
725
+
726
+ def main() -> None:
727
+ app(prog_name='diffpilot')
728
+
729
+
730
+ if __name__ == '__main__':
731
+ main()