sessionwiki 2.0.0__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.
Files changed (118) hide show
  1. sessionwiki/__init__.py +74 -0
  2. sessionwiki/__main__.py +6 -0
  3. sessionwiki/_frontmatter.py +118 -0
  4. sessionwiki/_system_pages.py +44 -0
  5. sessionwiki/adapter_config.py +124 -0
  6. sessionwiki/adapters/__init__.py +134 -0
  7. sessionwiki/adapters/base.py +191 -0
  8. sessionwiki/adapters/claude_code.py +77 -0
  9. sessionwiki/adapters/codex_cli.py +226 -0
  10. sessionwiki/adapters/contrib/__init__.py +1 -0
  11. sessionwiki/adapters/contrib/chatgpt.py +252 -0
  12. sessionwiki/adapters/contrib/copilot_chat.py +121 -0
  13. sessionwiki/adapters/contrib/copilot_cli.py +115 -0
  14. sessionwiki/adapters/contrib/cursor.py +100 -0
  15. sessionwiki/adapters/contrib/gemini_cli.py +74 -0
  16. sessionwiki/adapters/contrib/obsidian.py +121 -0
  17. sessionwiki/adapters/opencode.py +169 -0
  18. sessionwiki/adapters/status.py +58 -0
  19. sessionwiki/adapters/zcode.py +45 -0
  20. sessionwiki/audit.py +174 -0
  21. sessionwiki/backlinks.py +224 -0
  22. sessionwiki/build.py +2786 -0
  23. sessionwiki/cache.py +401 -0
  24. sessionwiki/candidates.py +309 -0
  25. sessionwiki/categories.py +158 -0
  26. sessionwiki/changelog_timeline.py +422 -0
  27. sessionwiki/cli.py +1687 -0
  28. sessionwiki/compare.py +404 -0
  29. sessionwiki/completion.py +191 -0
  30. sessionwiki/confidence.py +179 -0
  31. sessionwiki/config.py +74 -0
  32. sessionwiki/config_schedule.py +77 -0
  33. sessionwiki/context_md.py +182 -0
  34. sessionwiki/convert.py +1746 -0
  35. sessionwiki/docs_pages.py +725 -0
  36. sessionwiki/doctor.py +113 -0
  37. sessionwiki/exporters.py +680 -0
  38. sessionwiki/freshness.py +153 -0
  39. sessionwiki/graph.py +1058 -0
  40. sessionwiki/graphify_bridge.py +509 -0
  41. sessionwiki/ingest_queue.py +101 -0
  42. sessionwiki/lifecycle.py +167 -0
  43. sessionwiki/link_checker.py +148 -0
  44. sessionwiki/lint/__init__.py +170 -0
  45. sessionwiki/lint/rules/__init__.py +69 -0
  46. sessionwiki/lint/rules/_helpers.py +119 -0
  47. sessionwiki/lint/rules/claim_verification.py +44 -0
  48. sessionwiki/lint/rules/content_freshness.py +41 -0
  49. sessionwiki/lint/rules/contradiction_detection.py +45 -0
  50. sessionwiki/lint/rules/duplicate_detection.py +164 -0
  51. sessionwiki/lint/rules/entity_consistency.py +29 -0
  52. sessionwiki/lint/rules/frontmatter_completeness.py +46 -0
  53. sessionwiki/lint/rules/frontmatter_count_consistency.py +61 -0
  54. sessionwiki/lint/rules/frontmatter_validity.py +71 -0
  55. sessionwiki/lint/rules/index_sync.py +68 -0
  56. sessionwiki/lint/rules/link_integrity.py +34 -0
  57. sessionwiki/lint/rules/orphan_detection.py +43 -0
  58. sessionwiki/lint/rules/stale_candidates.py +59 -0
  59. sessionwiki/lint/rules/stale_reference_detection.py +42 -0
  60. sessionwiki/lint/rules/summary_accuracy.py +36 -0
  61. sessionwiki/lint/rules/tags_topics_convention.py +58 -0
  62. sessionwiki/lint/rules/tools_consistency.py +65 -0
  63. sessionwiki/lock.py +126 -0
  64. sessionwiki/log_reader.py +129 -0
  65. sessionwiki/manifest.py +132 -0
  66. sessionwiki/mcp/__init__.py +29 -0
  67. sessionwiki/mcp/__main__.py +5 -0
  68. sessionwiki/mcp/server.py +1061 -0
  69. sessionwiki/models_page.py +291 -0
  70. sessionwiki/obsidian_output.py +208 -0
  71. sessionwiki/opencode/__init__.py +1 -0
  72. sessionwiki/opencode/autosync.py +102 -0
  73. sessionwiki/opencode/export.py +419 -0
  74. sessionwiki/opencode/install.py +152 -0
  75. sessionwiki/pipeline.py +150 -0
  76. sessionwiki/project_topics.py +213 -0
  77. sessionwiki/py.typed +0 -0
  78. sessionwiki/quarantine.py +273 -0
  79. sessionwiki/queue.py +29 -0
  80. sessionwiki/references.py +224 -0
  81. sessionwiki/render/__init__.py +20 -0
  82. sessionwiki/render/css.py +988 -0
  83. sessionwiki/render/docs_css.py +463 -0
  84. sessionwiki/render/js.py +1337 -0
  85. sessionwiki/schema.py +270 -0
  86. sessionwiki/search_facets.py +150 -0
  87. sessionwiki/search_tree.py +184 -0
  88. sessionwiki/serve.py +91 -0
  89. sessionwiki/session_export.py +333 -0
  90. sessionwiki/skill_installer.py +112 -0
  91. sessionwiki/sync/__init__.py +13 -0
  92. sessionwiki/sync/status.py +120 -0
  93. sessionwiki/synth/__init__.py +14 -0
  94. sessionwiki/synth/agent_delegate.py +327 -0
  95. sessionwiki/synth/base.py +125 -0
  96. sessionwiki/synth/cli_helpers.py +98 -0
  97. sessionwiki/synth/estimate.py +146 -0
  98. sessionwiki/synth/ollama.py +379 -0
  99. sessionwiki/synth/openai_compat.py +325 -0
  100. sessionwiki/synth/pipeline.py +1489 -0
  101. sessionwiki/tag_utils.py +62 -0
  102. sessionwiki/tags.py +359 -0
  103. sessionwiki/vault.py +347 -0
  104. sessionwiki/viz_heatmap.py +305 -0
  105. sessionwiki/viz_tokens.py +429 -0
  106. sessionwiki/viz_tools.py +241 -0
  107. sessionwiki/watch.py +154 -0
  108. sessionwiki/zcode/__init__.py +43 -0
  109. sessionwiki/zcode/autosync.py +150 -0
  110. sessionwiki/zcode/export.py +568 -0
  111. sessionwiki/zcode/install.py +386 -0
  112. sessionwiki-2.0.0.dist-info/METADATA +303 -0
  113. sessionwiki-2.0.0.dist-info/RECORD +118 -0
  114. sessionwiki-2.0.0.dist-info/WHEEL +5 -0
  115. sessionwiki-2.0.0.dist-info/entry_points.txt +2 -0
  116. sessionwiki-2.0.0.dist-info/licenses/LICENSE +22 -0
  117. sessionwiki-2.0.0.dist-info/licenses/NOTICE +14 -0
  118. sessionwiki-2.0.0.dist-info/top_level.txt +1 -0
sessionwiki/cli.py ADDED
@@ -0,0 +1,1687 @@
1
+ """sessionwiki CLI.
2
+
3
+ Usage:
4
+ python3 -m sessionwiki <subcommand> [options]
5
+
6
+ Subcommands:
7
+ init Scaffold raw/, wiki/, site/ directories
8
+ sync Convert new .jsonl sessions to markdown
9
+ build Compile static HTML site from raw/ + wiki/
10
+ serve Start local HTTP server
11
+ adapters List available session-store adapters
12
+ graph Build the knowledge graph (graph/graph.json + graph.html)
13
+ export Export AI-consumable formats: llms-txt, llms-full-txt, jsonld, sitemap, rss, robots, ai-readme, marp
14
+ lint Run lint rules against the wiki
15
+ candidates List / promote / merge / discard candidate pages
16
+ synthesize Synthesize wiki source pages from raw sessions via LLM
17
+ all Run the full pipeline: build → graph → export all → lint
18
+ (optional: synthesize first with --with-synth)
19
+ version Print version and exit
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import sys
26
+ from pathlib import Path
27
+ from typing import Any, Optional
28
+
29
+ from sessionwiki import __version__, REPO_ROOT
30
+ from sessionwiki.adapters import REGISTRY, discover_adapters
31
+ # #v1378-review (#691 follow-up): hoist these re-exports from mid-module
32
+ # to here so the file passes E402 cleanly. They re-export business
33
+ # logic that lives in the proper domain modules now (#611) — kept here
34
+ # for any caller still importing from sessionwiki.cli.
35
+ from sessionwiki.adapters.status import adapter_status as _adapter_status # noqa: F401
36
+ from sessionwiki.synth.estimate import synthesize_estimate_report # noqa: F401
37
+ # #691 / #arch-h8: extracted business logic moves out of cli.py.
38
+ # cli.py keeps thin re-export wrappers for back-compat with anyone
39
+ # doing `from sessionwiki.cli import cmd_all, cmd_sync_status, ...`.
40
+ from sessionwiki.config_schedule import ( # noqa: F401
41
+ load_schedule_config as _load_schedule_config,
42
+ should_run_after_sync as _should_run_after_sync,
43
+ )
44
+ from sessionwiki.pipeline import run_pipeline as _run_pipeline
45
+ from sessionwiki.sync.status import ( # noqa: F401
46
+ cmd_sync_status,
47
+ resolve_key_exists as _resolve_key_exists,
48
+ )
49
+ from sessionwiki.synth.cli_helpers import ( # noqa: F401
50
+ complete as _synthesize_complete,
51
+ list_pending as _synthesize_list_pending,
52
+ )
53
+
54
+
55
+ def cmd_version(args: argparse.Namespace) -> int:
56
+ print(f"sessionwiki {__version__}")
57
+ return 0
58
+
59
+
60
+ def cmd_all(args: argparse.Namespace) -> int:
61
+ """Run the full wiki pipeline end-to-end: build → graph → export all → lint.
62
+
63
+ Thin shim — the implementation lives in ``sessionwiki.pipeline`` (#691).
64
+ """
65
+ return _run_pipeline(args)
66
+
67
+
68
+ def cmd_init(args: argparse.Namespace) -> int:
69
+ """Create raw/, wiki/, site/ directory structure."""
70
+ for name in ("raw/sessions", "wiki/sources", "wiki/entities", "wiki/concepts", "wiki/syntheses", "site"):
71
+ p = REPO_ROOT / name
72
+ p.mkdir(parents=True, exist_ok=True)
73
+ keep = p / ".gitkeep"
74
+ if not keep.exists() and not any(p.iterdir()):
75
+ keep.touch()
76
+ print(f" {p.relative_to(REPO_ROOT)}/")
77
+
78
+ # Also create hot/ for per-project caches
79
+ hot_dir = REPO_ROOT / "wiki" / "hot"
80
+ hot_dir.mkdir(parents=True, exist_ok=True)
81
+ keep = hot_dir / ".gitkeep"
82
+ if not keep.exists():
83
+ keep.touch()
84
+
85
+ # Seed index/log/overview + navigation files if not present
86
+ seeds = {
87
+ "wiki/index.md": (
88
+ "# Wiki Index\n\n"
89
+ "<!-- #387 U6: each section heading carries a (count) so the index\n"
90
+ "stays scannable as the wiki grows past ~50 pages. Update the count\n"
91
+ "in the heading when adding/removing pages. The index is otherwise\n"
92
+ "kept flat (no nested folders) so a single grep/scan can find any\n"
93
+ "page without descending into a tree. -->\n\n"
94
+ "## Overview (1)\n- [Overview](overview.md)\n\n"
95
+ "## Sources (0)\n\n"
96
+ "## Entities (0)\n\n"
97
+ "## Projects (0)\n\n"
98
+ "## Concepts (0)\n\n"
99
+ "## Syntheses (0)\n"
100
+ ),
101
+ "wiki/overview.md": '---\ntitle: "Overview"\ntype: synthesis\nsources: []\nlast_updated: ""\n---\n\n# Overview\n\n*This page is maintained by your coding agent.*\n',
102
+ "wiki/log.md": "# Wiki Log\n\nAppend-only chronological record of all operations.\n\nFormat: `## [YYYY-MM-DD] <operation> | <title>`\n\n---\n",
103
+ "wiki/hints.md": '---\ntitle: "Navigation Hints"\ntype: navigation\nlast_updated: ""\n---\n\n# Hints\n\nWriting conventions, entity naming rules, and navigation guidance.\nCustomize this file for your project.\n',
104
+ "wiki/hot.md": '---\ntitle: "Hot Cache"\ntype: navigation\nlast_updated: ""\nauto_maintained: true\n---\n\n# Hot Cache\n\n*Auto-maintained. Last 10 session summaries.*\n',
105
+ "wiki/MEMORY.md": '---\ntitle: "Cross-Session Memory"\ntype: navigation\nlast_updated: ""\nmax_lines: 200\n---\n\n# MEMORY\n\n*200-line cap. Auto-consolidated by Auto Dream.*\n\n## User\n\n## Feedback\n\n## Project\n\n## Reference\n',
106
+ "wiki/SOUL.md": '---\ntitle: "Wiki Identity"\ntype: navigation\nlast_updated: ""\n---\n\n# SOUL\n\nThis wiki compiles raw session transcripts into structured, interlinked pages.\nCustomize this file to set your wiki\'s voice and purpose.\n',
107
+ "wiki/CRITICAL_FACTS.md": '---\ntitle: "Critical Facts"\ntype: navigation\nlast_updated: ""\n---\n\n# Critical Facts\n\n- raw/ is immutable — never modify files under raw/\n- Wiki uses Obsidian-style double-bracket syntax for cross-references\n- Confidence: 0.0-1.0, 4-factor formula\n- Lifecycle: draft > reviewed > verified > stale > archived\n',
108
+ }
109
+
110
+ # v1.0 (#153): seed dashboard.md from examples/wiki_dashboard.md template
111
+ dashboard_template = REPO_ROOT / "examples" / "wiki_dashboard.md"
112
+ dashboard_target = REPO_ROOT / "wiki" / "dashboard.md"
113
+ if dashboard_template.is_file() and not dashboard_target.is_file():
114
+ dashboard_target.write_text(
115
+ dashboard_template.read_text(encoding="utf-8"),
116
+ encoding="utf-8",
117
+ )
118
+ print(f" seeded wiki/dashboard.md")
119
+ for rel, content in seeds.items():
120
+ p = REPO_ROOT / rel
121
+ if not p.exists():
122
+ p.write_text(content, encoding="utf-8")
123
+ print(f" seeded {p.relative_to(REPO_ROOT)}")
124
+ return 0
125
+
126
+
127
+ def _maybe_export_zcode(args: argparse.Namespace) -> None:
128
+ """Refresh the ZCode JSONL corpus before a sync, when applicable.
129
+
130
+ ZCode sessions live in a live SQLite database; the sessionwiki adapter
131
+ reads a flat JSONL export. Without this step `sessionwiki sync` (and the
132
+ MCP ``wiki_sync`` tool, which shells out to it) would silently miss
133
+ new sessions. The export is incremental, so an unchanged store costs
134
+ one read-only scan.
135
+
136
+ Failures are warnings, not sync failures: the existing JSONL corpus
137
+ is still usable.
138
+ """
139
+ if not getattr(args, "zcode_export", False):
140
+ return
141
+
142
+ try:
143
+ config = _load_run_config()
144
+ except Exception:
145
+ config = {}
146
+ zcode_cfg = config.get("zcode") if isinstance(config, dict) else None
147
+
148
+ adapters = getattr(args, "adapter", None)
149
+ if adapters:
150
+ from sessionwiki.adapters import discover_adapters, resolve_adapter_name
151
+
152
+ discover_adapters()
153
+ selected = {resolve_adapter_name(name) for name in adapters}
154
+ if "zcode" not in selected:
155
+ return
156
+ elif isinstance(zcode_cfg, dict) and zcode_cfg.get("enabled") is False:
157
+ # Auto-selection follows the config toggle. An explicit
158
+ # `--adapter zcode` overrides it, matching convert_all().
159
+ return
160
+
161
+ project_roots = None
162
+ if isinstance(zcode_cfg, dict):
163
+ configured_roots = zcode_cfg.get("project_roots")
164
+ if isinstance(configured_roots, list):
165
+ project_roots = configured_roots
166
+
167
+ from sessionwiki.zcode.export import (
168
+ DEFAULT_DB,
169
+ DEFAULT_OUT_DIR,
170
+ parse_since,
171
+ run_export,
172
+ )
173
+
174
+ db = Path(getattr(args, "zcode_db", None) or DEFAULT_DB).expanduser()
175
+ if not db.is_file():
176
+ return
177
+ out_dir = Path(getattr(args, "zcode_out_dir", None) or DEFAULT_OUT_DIR).expanduser()
178
+
179
+ try:
180
+ since_ms = parse_since(getattr(args, "since", None))
181
+ except ValueError as exc:
182
+ print(f" warning: zcode export skipped: {exc}", file=sys.stderr)
183
+ return
184
+
185
+ print(f" zcode export: {db} -> {out_dir}")
186
+ try:
187
+ stats = run_export(
188
+ db,
189
+ out_dir,
190
+ since=since_ms,
191
+ project=getattr(args, "project", None),
192
+ include_subagents=False,
193
+ dry_run=bool(getattr(args, "dry_run", False)),
194
+ project_roots=project_roots,
195
+ )
196
+ except Exception as exc: # noqa: BLE001 - sync must survive a bad DB
197
+ print(f" warning: zcode export failed: {exc}", file=sys.stderr)
198
+ return
199
+
200
+ print(
201
+ (
202
+ f" zcode export (dry-run): {stats.get('exported', 0)} would change, "
203
+ f"{stats.get('unchanged', 0)} unchanged"
204
+ if getattr(args, "dry_run", False)
205
+ else f" zcode export: {stats.get('exported', 0)} exported, "
206
+ f"{stats.get('unchanged', 0)} unchanged"
207
+ )
208
+ )
209
+ if stats.get("errors"):
210
+ print(
211
+ f" warning: zcode export finished with {stats['errors']} error(s)",
212
+ file=sys.stderr,
213
+ )
214
+
215
+
216
+ def _maybe_export_opencode(args: argparse.Namespace) -> None:
217
+ """Refresh the OpenCode JSONL corpus before a sync, when applicable.
218
+
219
+ OpenCode V2 sessions live in a live SQLite database; the sessionwiki
220
+ adapter reads a JSONL export. Without this step ``sessionwiki sync``
221
+ would silently miss new OpenCode sessions. The export is incremental,
222
+ so an unchanged store costs one read-only scan.
223
+
224
+ Failures are warnings, not sync failures: the existing JSONL corpus
225
+ is still usable.
226
+ """
227
+ if not getattr(args, "opencode_export", False):
228
+ return
229
+
230
+ try:
231
+ config = _load_run_config()
232
+ except Exception:
233
+ config = {}
234
+ opencode_cfg = config.get("opencode") if isinstance(config, dict) else None
235
+
236
+ adapters = getattr(args, "adapter", None)
237
+ if adapters:
238
+ from sessionwiki.adapters import discover_adapters, resolve_adapter_name
239
+
240
+ discover_adapters()
241
+ selected = {resolve_adapter_name(name) for name in adapters}
242
+ if "opencode" not in selected:
243
+ return
244
+ elif isinstance(opencode_cfg, dict) and opencode_cfg.get("enabled") is False:
245
+ return
246
+
247
+ from sessionwiki.opencode.export import (
248
+ DEFAULT_DB,
249
+ DEFAULT_OUT_DIR,
250
+ parse_since,
251
+ run_export,
252
+ )
253
+
254
+ db = Path(getattr(args, "opencode_db", None) or DEFAULT_DB).expanduser()
255
+ if not db.is_file():
256
+ return
257
+ out_dir = Path(DEFAULT_OUT_DIR).expanduser()
258
+
259
+ try:
260
+ since_ms = parse_since(getattr(args, "since", None))
261
+ except ValueError as exc:
262
+ print(f" warning: opencode export skipped: {exc}", file=sys.stderr)
263
+ return
264
+
265
+ print(f" opencode export: {db} -> {out_dir}")
266
+ try:
267
+ stats = run_export(
268
+ db,
269
+ out_dir,
270
+ since=since_ms,
271
+ project=getattr(args, "project", None),
272
+ include_subagents=False,
273
+ dry_run=bool(getattr(args, "dry_run", False)),
274
+ )
275
+ except Exception as exc: # noqa: BLE001 - sync must survive a bad DB
276
+ print(f" warning: opencode export failed: {exc}", file=sys.stderr)
277
+ return
278
+
279
+ print(
280
+ (
281
+ f" opencode export (dry-run): {stats.get('exported', 0)} would change, "
282
+ f"{stats.get('unchanged', 0)} unchanged"
283
+ if getattr(args, "dry_run", False)
284
+ else f" opencode export: {stats.get('exported', 0)} exported, "
285
+ f"{stats.get('unchanged', 0)} unchanged"
286
+ )
287
+ )
288
+ if stats.get("errors"):
289
+ print(
290
+ f" warning: opencode export finished with {stats['errors']} error(s)",
291
+ file=sys.stderr,
292
+ )
293
+
294
+
295
+ def cmd_sync(args: argparse.Namespace) -> int:
296
+ """Convert .jsonl sessions to markdown using the enabled adapters."""
297
+ # G-03 (#289): `sync --status` short-circuits into the status reporter.
298
+ if getattr(args, "status", False):
299
+ return cmd_sync_status(args)
300
+
301
+ from sessionwiki.convert import convert_all, DEFAULT_OUT_DIR, DEFAULT_STATE_FILE
302
+
303
+ # v1.2 (#54): vault-overlay mode — resolve the vault early so bad
304
+ # paths fail before we spend time converting sessions.
305
+ # #470: actually wire the resolved vault root through to convert_all.
306
+ # Previously this block printed a banner and then called convert_all
307
+ # with no vault/out_dir argument, so all 500+ sessions wrote to the
308
+ # repo's raw/sessions/ instead of the vault. The summary line said
309
+ # "507 converted" but the vault directory was empty.
310
+ vault_path = getattr(args, "vault", None)
311
+ out_dir = DEFAULT_OUT_DIR
312
+ state_file = DEFAULT_STATE_FILE
313
+ if vault_path:
314
+ from sessionwiki.vault import describe_vault, resolve_vault
315
+ try:
316
+ vault = resolve_vault(vault_path)
317
+ except (FileNotFoundError, NotADirectoryError) as exc:
318
+ print(f"error: {exc}", file=sys.stderr)
319
+ return 2
320
+ print(f"==> {describe_vault(vault)}")
321
+ if args.allow_overwrite:
322
+ print(" --allow-overwrite: existing vault pages may be clobbered")
323
+ # Route writes into the vault so a vault-mode sync actually
324
+ # populates the vault. State file co-located with the vault so
325
+ # two different vaults don't share idempotency state (same
326
+ # principle as #420 for synth state).
327
+ out_dir = vault.root / "raw" / "sessions"
328
+ state_file = vault.root / ".llmwiki-state.json"
329
+
330
+ dry_run = bool(getattr(args, "dry_run", False))
331
+ _maybe_export_opencode(args)
332
+ _maybe_export_zcode(args)
333
+
334
+ rc = convert_all(
335
+ adapters=args.adapter,
336
+ out_dir=out_dir,
337
+ state_file=state_file,
338
+ since=args.since,
339
+ project=args.project,
340
+ include_current=args.include_current,
341
+ force=args.force,
342
+ dry_run=dry_run,
343
+ )
344
+
345
+ # v1.0 (#157): auto-build and auto-lint after sync.
346
+ # --no-build and --no-lint let users opt out.
347
+ # #470: when --vault was given, point the auto-build at the vault's
348
+ # site/ tree too — otherwise the build silently writes to the
349
+ # repo's site/ and the user's vault stays empty.
350
+ if rc == 0 and not dry_run:
351
+ schedule = _load_schedule_config()
352
+ site_root = (vault.root / "site") if vault_path else (REPO_ROOT / "site")
353
+ if args.auto_build and _should_run_after_sync(schedule.get("build", "on-sync")):
354
+ print(" auto-build: regenerating site/...")
355
+ from sessionwiki.build import build_site
356
+ # #414: sync has explicit user opt-in to mutate wiki/, so it's
357
+ # the right place to seed project stubs.
358
+ build_site(out_dir=site_root, seed_project_stubs=True)
359
+ if args.auto_lint and _should_run_after_sync(schedule.get("lint", "manual")):
360
+ print(" auto-lint: running wiki lint...")
361
+ from sessionwiki.lint import load_pages, run_all, summarize
362
+ # #470: lint the vault's wiki/, not the repo's, when in
363
+ # vault-overlay mode.
364
+ wiki_dir = (vault.root / "wiki") if vault_path else None
365
+ pages = load_pages(wiki_dir) if wiki_dir else load_pages()
366
+ issues = run_all(pages)
367
+ summary = summarize(issues)
368
+ print(f" lint: {sum(summary.values())} issues "
369
+ f"({summary.get('error', 0)} errors, "
370
+ f"{summary.get('warning', 0)} warnings)")
371
+ return rc
372
+
373
+
374
+ # _load_schedule_config + _should_run_after_sync moved to
375
+ # sessionwiki/config_schedule.py and re-exported at top of file (#691).
376
+
377
+
378
+ def cmd_build(args: argparse.Namespace) -> int:
379
+ """Build the static HTML site."""
380
+ from sessionwiki.build import build_site
381
+
382
+ # v1.2 (#54): vault-overlay mode. Validate the path up front so a
383
+ # typo fails fast before the build walks raw/.
384
+ if getattr(args, "vault", None):
385
+ from sessionwiki.vault import describe_vault, resolve_vault
386
+ try:
387
+ vault = resolve_vault(args.vault)
388
+ except (FileNotFoundError, NotADirectoryError) as exc:
389
+ print(f"error: {exc}", file=sys.stderr)
390
+ return 2
391
+ print(f"==> {describe_vault(vault)}")
392
+
393
+ return build_site(
394
+ out_dir=args.out,
395
+ synthesize=args.synthesize,
396
+ claude_path=args.claude,
397
+ search_mode=args.search_mode,
398
+ seed_project_stubs=getattr(args, "seed_project_stubs", False),
399
+ )
400
+
401
+
402
+ def cmd_serve(args: argparse.Namespace) -> int:
403
+ """Serve the built site via a local HTTP server."""
404
+ from sessionwiki.serve import serve_site
405
+ return serve_site(directory=args.dir, port=args.port, host=args.host, open_browser=args.open)
406
+
407
+
408
+ def cmd_adapters(args: argparse.Namespace) -> int:
409
+ """List available adapters and their config state.
410
+
411
+ G-01 (#287): ``configured`` column now shows ``auto``/``explicit``/
412
+ ``off`` (not ``-``/``enabled``/``disabled``) and a new
413
+ ``will_fire`` column says whether the next ``sync`` will pick the
414
+ adapter up.
415
+
416
+ G-02 (#288): ``--wide`` disables the description cap.
417
+ """
418
+ import shutil as _shutil
419
+
420
+ discover_adapters()
421
+ if not REGISTRY:
422
+ print("No adapters registered.")
423
+ return 0
424
+
425
+ # Load the same layered config `sync` uses, so a local override
426
+ # that disables an adapter is reflected in this table.
427
+ config = _load_run_config()
428
+
429
+ # Description column width: 40 by default, full line with --wide,
430
+ # or auto-fit to terminal (minus the four fixed columns + gutters).
431
+ # #387 U2: column names renamed from default/configured/will_fire to
432
+ # present/enabled/active — they read at a glance without needing the
433
+ # legend below.
434
+ wide = bool(getattr(args, "wide", False))
435
+ if wide:
436
+ desc_width: Optional[int] = None # no cap
437
+ else:
438
+ term_cols = _shutil.get_terminal_size(fallback=(80, 24)).columns
439
+ # Layout: " name(16) present(8) enabled(10) active(7) desc"
440
+ desc_width = max(30, term_cols - 55)
441
+
442
+ print("Registered adapters:")
443
+ dash = "-"
444
+ header = (
445
+ f" {'name':<16} {'present':<8} {'enabled':<10} "
446
+ f"{'active':<7} description"
447
+ )
448
+ print(header)
449
+ sep_desc = "-" * (desc_width if desc_width is not None else len("description"))
450
+ print(
451
+ f" {dash * 16} {dash * 8} {dash * 10} {dash * 7} {sep_desc}"
452
+ )
453
+ for name, adapter_cls in sorted(REGISTRY.items()):
454
+ present = "yes" if adapter_cls.is_available() else "no"
455
+ enabled, active = _adapter_status(name, adapter_cls, config)
456
+ desc = adapter_cls.description()
457
+ if desc_width is not None and len(desc) > desc_width:
458
+ desc = desc[: max(desc_width - 3, 1)] + "..."
459
+ print(
460
+ f" {name:<16} {present:<8} {enabled:<10} "
461
+ f"{active:<7} {desc}"
462
+ )
463
+
464
+ print()
465
+ print("Columns:")
466
+ print(" present — is the adapter's session store visible on disk?")
467
+ print(" enabled — auto (default), explicit (enabled:true in config), off (enabled:false)")
468
+ print(" active — yes/no — will `sync` pick this adapter up on its next run?")
469
+ if not wide:
470
+ print()
471
+ print("Pass --wide to see untruncated descriptions.")
472
+ return 0
473
+
474
+
475
+ def cmd_zcode_export(args: argparse.Namespace) -> int:
476
+ """Export ZCode's SQLite store to JSONL for the zcode adapter."""
477
+ if getattr(args, "zcode_command", None) != "export":
478
+ print("usage: sessionwiki zcode export [options]", file=sys.stderr)
479
+ return 2
480
+
481
+ from sessionwiki.zcode import export as zcode_export
482
+
483
+ argv: list[str] = [
484
+ "--db",
485
+ str(args.db),
486
+ "--out-dir",
487
+ str(args.out_dir),
488
+ ]
489
+ if getattr(args, "state_file", None):
490
+ argv.extend(["--state-file", str(args.state_file)])
491
+ if getattr(args, "since", None):
492
+ argv.extend(["--since", str(args.since)])
493
+ if getattr(args, "project", None):
494
+ argv.extend(["--project", str(args.project)])
495
+ for root in getattr(args, "project_roots", None) or []:
496
+ argv.extend(["--project-root", str(root)])
497
+ if getattr(args, "include_subagents", False):
498
+ argv.append("--include-subagents")
499
+ if getattr(args, "keep_stale", False):
500
+ argv.append("--keep-stale")
501
+ if getattr(args, "strict", False):
502
+ argv.append("--strict")
503
+ if getattr(args, "dry_run", False):
504
+ argv.append("--dry-run")
505
+ return zcode_export.main(argv)
506
+
507
+
508
+ def cmd_zcode_autosync(args: argparse.Namespace) -> int:
509
+ """Run one portable autosync cycle (export → convert → optional build)."""
510
+ if getattr(args, "zcode_command", None) != "autosync":
511
+ print("usage: sessionwiki zcode autosync [options]", file=sys.stderr)
512
+ return 2
513
+
514
+ from sessionwiki.zcode.autosync import run_autosync
515
+
516
+ return run_autosync(
517
+ db_path=args.db,
518
+ out_dir=args.out_dir,
519
+ project=args.project,
520
+ build=bool(getattr(args, "build", False)),
521
+ coalesce=bool(getattr(args, "coalesce", False)),
522
+ lock_timeout=float(getattr(args, "lock_timeout", 600)),
523
+ log_path=getattr(args, "log", None),
524
+ quiet=bool(getattr(args, "quiet", False)),
525
+ )
526
+
527
+
528
+ def cmd_zcode_install(args: argparse.Namespace) -> int:
529
+ """Install the ZCode Stop-hook and a native scheduler entry."""
530
+ if getattr(args, "zcode_command", None) != "install":
531
+ print("usage: sessionwiki zcode install [options]", file=sys.stderr)
532
+ return 2
533
+
534
+ from sessionwiki.zcode.install import install_all
535
+
536
+ try:
537
+ messages = install_all(
538
+ scheduler=args.scheduler,
539
+ python_exe=getattr(args, "python_exe", None),
540
+ repo_root=getattr(args, "repo_root", None) or REPO_ROOT,
541
+ at=args.at,
542
+ build=not bool(getattr(args, "no_build", False)),
543
+ coalesce=bool(getattr(args, "coalesce", False)),
544
+ hook=not bool(getattr(args, "no_hook", False)),
545
+ dry_run=bool(getattr(args, "dry_run", False)),
546
+ force=bool(getattr(args, "force", False)),
547
+ )
548
+ except (OSError, ValueError) as exc:
549
+ print(f"error: {exc}", file=sys.stderr)
550
+ return 2
551
+
552
+ for message in messages:
553
+ print(message)
554
+ return 0
555
+
556
+
557
+ def cmd_opencode_export(args: argparse.Namespace) -> int:
558
+ """Export OpenCode V2's SQLite store to JSONL for the opencode adapter."""
559
+ if getattr(args, "opencode_command", None) != "export":
560
+ print("usage: sessionwiki opencode export [options]", file=sys.stderr)
561
+ return 2
562
+
563
+ import sqlite3
564
+
565
+ from sessionwiki.opencode.export import SchemaError, parse_since, run_export
566
+
567
+ try:
568
+ since_ms = parse_since(getattr(args, "since", None))
569
+ except ValueError as exc:
570
+ print(f"error: {exc}", file=sys.stderr)
571
+ return 2
572
+
573
+ try:
574
+ stats = run_export(
575
+ db_path=args.db,
576
+ out_dir=args.out_dir,
577
+ state_file=getattr(args, "state_file", None),
578
+ since=since_ms,
579
+ project=getattr(args, "project", None),
580
+ include_subagents=bool(getattr(args, "include_subagents", False)),
581
+ dry_run=bool(getattr(args, "dry_run", False)),
582
+ project_roots=getattr(args, "project_roots", None),
583
+ prune_stale=not bool(getattr(args, "keep_stale", False)),
584
+ )
585
+ except (SchemaError, sqlite3.Error, OSError, RuntimeError) as exc:
586
+ print(f"error: {exc}", file=sys.stderr)
587
+ return 1
588
+
589
+ print("OpenCode export")
590
+ print(f" db: {args.db}")
591
+ print(f" out: {args.out_dir}")
592
+ print(
593
+ f" sessions: {stats['total_sessions']} total, "
594
+ f"{stats['selected']} selected"
595
+ )
596
+ print(
597
+ " skipped: "
598
+ f"{stats['skipped_subagents']} subagent, "
599
+ f"{stats['skipped_project']} project, "
600
+ f"{stats['skipped_since']} since"
601
+ )
602
+ print(
603
+ f" exported: {stats['exported']}, unchanged: {stats['unchanged']}, "
604
+ f"empty: {stats['empty']}, errors: {stats['errors']}"
605
+ )
606
+ if args.dry_run:
607
+ print(" dry-run: no files written")
608
+ else:
609
+ print(f" written: {stats['written']} files")
610
+ if stats.get("stale"):
611
+ print(
612
+ f" stale: {stats['stale']} removed "
613
+ f"({stats['stale_deleted']} files deleted)"
614
+ )
615
+ if stats.get("errors") and getattr(args, "strict", False):
616
+ return 1
617
+ return 0
618
+
619
+
620
+ def cmd_opencode_autosync(args: argparse.Namespace) -> int:
621
+ """Run one OpenCode autosync cycle (export → convert → optional build)."""
622
+ if getattr(args, "opencode_command", None) != "autosync":
623
+ print("usage: sessionwiki opencode autosync [options]", file=sys.stderr)
624
+ return 2
625
+
626
+ from sessionwiki.opencode.autosync import run_autosync
627
+
628
+ return run_autosync(
629
+ db_path=args.db,
630
+ out_dir=args.out_dir,
631
+ project=args.project,
632
+ build=bool(getattr(args, "build", False)),
633
+ lock_timeout=float(getattr(args, "lock_timeout", 600)),
634
+ log_path=getattr(args, "log", None),
635
+ quiet=bool(getattr(args, "quiet", False)),
636
+ )
637
+
638
+
639
+ def cmd_opencode_install(args: argparse.Namespace) -> int:
640
+ """Install the OpenCode autosync plugin."""
641
+ if getattr(args, "opencode_command", None) != "install":
642
+ print("usage: sessionwiki opencode install [options]", file=sys.stderr)
643
+ return 2
644
+
645
+ from sessionwiki.opencode.install import install_all
646
+
647
+ try:
648
+ build = bool(getattr(args, "build", False)) and not bool(
649
+ getattr(args, "no_build", False)
650
+ )
651
+ messages = install_all(
652
+ python_exe=getattr(args, "python_exe", None),
653
+ repo_root=getattr(args, "repo_root", None) or REPO_ROOT,
654
+ build=build,
655
+ dry_run=bool(getattr(args, "dry_run", False)),
656
+ force=bool(getattr(args, "force", False)),
657
+ )
658
+ except (OSError, ValueError) as exc:
659
+ print(f"error: {exc}", file=sys.stderr)
660
+ return 2
661
+
662
+ for message in messages:
663
+ print(message)
664
+ return 0
665
+
666
+
667
+ def cmd_query(args: argparse.Namespace) -> int:
668
+ """Query the knowledge graph with a natural language question."""
669
+ from sessionwiki.graphify_bridge import is_available, query_graph
670
+ if not is_available():
671
+ print("error: graphify not installed. Run: pip install sessionwiki[graph]", file=sys.stderr)
672
+ return 2
673
+ question = " ".join(args.question)
674
+ result = query_graph(question, depth=args.depth, token_budget=args.budget)
675
+ print(result)
676
+ return 0
677
+
678
+
679
+ def cmd_graph(args: argparse.Namespace) -> int:
680
+ """Build the knowledge graph from wiki/ wikilinks.
681
+
682
+ #488: graphify-engine failures (uninstalled, crashes, empty
683
+ result) ALL fall back to the builtin engine so the user always
684
+ gets *some* graph. Only the builtin engine's exit code is
685
+ authoritative for the CLI return value.
686
+ """
687
+ engine = getattr(args, "engine", "graphify")
688
+ if engine == "graphify":
689
+ from sessionwiki.graphify_bridge import is_available, build_graphify_graph
690
+ if not is_available():
691
+ print(" graphify not installed — falling back to builtin engine", file=sys.stderr)
692
+ print(" install with: pip install sessionwiki[graph]", file=sys.stderr)
693
+ engine = "builtin"
694
+ else:
695
+ try:
696
+ result = build_graphify_graph()
697
+ except Exception as e:
698
+ # #488: uncaught graphify exception used to surface as a
699
+ # bare stack trace + non-zero exit. Now we log a warning
700
+ # and fall through to the builtin engine.
701
+ print(f" graphify engine crashed ({type(e).__name__}: {e}) — "
702
+ f"falling back to builtin", file=sys.stderr)
703
+ engine = "builtin"
704
+ else:
705
+ if result.get("graph") is not None:
706
+ return 0
707
+ # #488: empty-result early-return used to fail with rc=1
708
+ # without trying builtin. graphify can legitimately
709
+ # return None for tiny corpora (no edges); the builtin
710
+ # engine handles the same input gracefully.
711
+ print(" graphify returned no graph — falling back to builtin",
712
+ file=sys.stderr)
713
+ engine = "builtin"
714
+
715
+ from sessionwiki.graph import build_and_report
716
+ write_json = args.format in ("json", "both")
717
+ write_html = args.format in ("html", "both")
718
+ return build_and_report(write_json_flag=write_json, write_html_flag=write_html)
719
+
720
+
721
+ # cmd_sync_status + _resolve_key_exists moved to sessionwiki/sync/status.py
722
+ # and re-exported at top of file (#691).
723
+
724
+
725
+ def cmd_export(args: argparse.Namespace) -> int:
726
+ """Export AI-consumable formats from the compiled wiki."""
727
+ import sys as _sys
728
+ from sessionwiki.exporters import (
729
+ write_llms_txt,
730
+ write_llms_full_txt,
731
+ write_graph_jsonld,
732
+ write_sitemap,
733
+ write_rss,
734
+ write_robots_txt,
735
+ write_ai_readme,
736
+ write_marp,
737
+ export_all,
738
+ )
739
+ from sessionwiki.build import discover_sources, group_by_project, RAW_SESSIONS
740
+
741
+ out_dir = args.out if args.out else REPO_ROOT / "site"
742
+ out_dir.mkdir(parents=True, exist_ok=True)
743
+
744
+ sources = discover_sources(RAW_SESSIONS)
745
+ if not sources:
746
+ print("error: no sources found. Run 'sessionwiki sync' first.", file=_sys.stderr)
747
+ return 2
748
+ groups = group_by_project(sources)
749
+
750
+ format_ = args.format
751
+ if format_ == "all":
752
+ paths = export_all(out_dir, groups, sources)
753
+ for name, p in sorted(paths.items()):
754
+ print(f" wrote {p.relative_to(REPO_ROOT) if p.is_relative_to(REPO_ROOT) else p}")
755
+ return 0
756
+
757
+ topic = getattr(args, "topic", "") or ""
758
+ mapping = {
759
+ "llms-txt": lambda: write_llms_txt(out_dir, groups, len(sources)),
760
+ "llms-full-txt": lambda: write_llms_full_txt(out_dir, sources),
761
+ "jsonld": lambda: write_graph_jsonld(out_dir, groups, sources),
762
+ "sitemap": lambda: write_sitemap(out_dir, groups, sources),
763
+ "rss": lambda: write_rss(out_dir, sources),
764
+ "robots": lambda: write_robots_txt(out_dir),
765
+ "ai-readme": lambda: write_ai_readme(out_dir, groups, len(sources)),
766
+ "marp": lambda: write_marp(out_dir, sources, topic=topic),
767
+ }
768
+ fn = mapping.get(format_)
769
+ if not fn:
770
+ print(f"error: unknown format {format_!r}. Valid: {sorted(mapping.keys())} or 'all'", file=_sys.stderr)
771
+ return 2
772
+ p = fn()
773
+ print(f" wrote {p.relative_to(REPO_ROOT) if p.is_relative_to(REPO_ROOT) else p}")
774
+ return 0
775
+
776
+
777
+ def cmd_lint(args: argparse.Namespace) -> int:
778
+ """Run every registered lint rule against the wiki and print a report."""
779
+ from sessionwiki.lint import REGISTRY, load_pages, run_all, summarize # noqa: F401
780
+
781
+ wiki_dir = args.wiki_dir or (REPO_ROOT / "wiki")
782
+ if not wiki_dir.is_dir():
783
+ print(f"error: wiki directory not found: {wiki_dir}", file=sys.stderr)
784
+ return 2
785
+
786
+ pages = load_pages(wiki_dir)
787
+ if not pages:
788
+ print(f" no pages found in {wiki_dir}")
789
+ return 0
790
+
791
+ selected = args.rules.split(",") if args.rules else None
792
+ issues = run_all(
793
+ pages,
794
+ include_llm=args.include_llm,
795
+ selected=selected,
796
+ )
797
+
798
+ summary = summarize(issues)
799
+
800
+ if args.json:
801
+ import json as _json
802
+ print(_json.dumps({
803
+ "summary": summary,
804
+ "issues": issues,
805
+ "total_pages": len(pages),
806
+ }, indent=2))
807
+ else:
808
+ print(f" scanned {len(pages)} pages")
809
+ print(f" {sum(summary.values())} issues: "
810
+ f"{summary.get('error', 0)} errors, "
811
+ f"{summary.get('warning', 0)} warnings, "
812
+ f"{summary.get('info', 0)} info")
813
+ print()
814
+ if issues:
815
+ by_rule: dict[str, list[dict[str, str]]] = {}
816
+ for i in issues:
817
+ by_rule.setdefault(i["rule"], []).append(i)
818
+ for rule, rule_issues in sorted(by_rule.items()):
819
+ print(f"## {rule} ({len(rule_issues)})")
820
+ for i in rule_issues[:20]:
821
+ print(f" [{i['severity']}] {i['page']}: {i['message']}")
822
+ if len(rule_issues) > 20:
823
+ print(f" ... and {len(rule_issues) - 20} more")
824
+ print()
825
+
826
+ if args.fail_on_errors and summary.get("error", 0) > 0:
827
+ return 1
828
+ return 0
829
+
830
+
831
+ def _load_run_config() -> dict:
832
+ """Load the shared example plus gitignored per-checkout overrides.
833
+
834
+ Order: ``examples/sessions_config.json`` → ``config.json`` →
835
+ ``config.local.json``. Machine settings (backend URLs, API keys,
836
+ redaction patterns) belong in an override, not in the shared example.
837
+ """
838
+ from sessionwiki.config import resolve_config
839
+
840
+ return resolve_config(REPO_ROOT)
841
+
842
+
843
+ def _config_int(value: Any, default: int, *, minimum: int = 1) -> int:
844
+ try:
845
+ parsed = int(value)
846
+ except (TypeError, ValueError):
847
+ return default
848
+ return max(minimum, parsed)
849
+
850
+
851
+ def _config_bool(value: Any, default: bool) -> bool:
852
+ if isinstance(value, bool):
853
+ return value
854
+ if isinstance(value, str):
855
+ return value.strip().lower() not in {"", "0", "false", "no", "off"}
856
+ if value is None:
857
+ return default
858
+ return bool(value)
859
+
860
+
861
+ def cmd_synthesize(args: argparse.Namespace) -> int:
862
+ """Synthesize wiki source pages from raw sessions (v1.1.0 · #35).
863
+
864
+ Uses the backend selected via ``synthesis.backend`` in the config
865
+ (dummy | ollama | openai | agent). ``--check`` prints backend
866
+ availability without running synthesis — useful for diagnosing a
867
+ server before a long sync. ``--estimate`` prints a cached-vs-fresh
868
+ token + dollar breakdown before spending money (#50).
869
+
870
+ Config resolution: ``examples/sessions_config.json``, then the
871
+ gitignored ``config.json`` and ``config.local.json`` overrides.
872
+ """
873
+ from sessionwiki.synth.pipeline import resolve_backend, synthesize_new_sessions
874
+
875
+ config: dict = _load_run_config()
876
+
877
+ if args.estimate:
878
+ return _synthesize_estimate(config)
879
+
880
+ # #316: agent-delegate operations that don't need a backend.
881
+ if args.list_pending:
882
+ return _synthesize_list_pending()
883
+ if args.complete:
884
+ return _synthesize_complete(args)
885
+
886
+ coalesce_only = bool(getattr(args, "coalesce_only", False))
887
+ if coalesce_only:
888
+ backend = None
889
+ print("Backend: none (coalesce-only)")
890
+ else:
891
+ backend = resolve_backend(config)
892
+ print(f"Backend: {backend.name}")
893
+ synth_cfg = config.get("synthesis", {}) or {}
894
+ max_workers = _config_int(synth_cfg.get("max_concurrency"), 1)
895
+ coalesce_low_signal = _config_bool(synth_cfg.get("coalesce_low_signal"), False)
896
+ if coalesce_only:
897
+ coalesce_low_signal = True
898
+ coalesce_min_group = _config_int(synth_cfg.get("coalesce_min_group"), 3)
899
+ coalesce_window = str(synth_cfg.get("coalesce_window", "all") or "all")
900
+ strip_links = _config_bool(synth_cfg.get("strip_unresolved_wikilinks"), True)
901
+ raw_lock_patterns = synth_cfg.get("lock_skip_patterns")
902
+ lock_skip_patterns = (
903
+ [str(pattern) for pattern in raw_lock_patterns]
904
+ if isinstance(raw_lock_patterns, list)
905
+ else None
906
+ )
907
+ if max_workers > 1:
908
+ print(f"Concurrency: {max_workers}")
909
+ if coalesce_low_signal:
910
+ print(
911
+ f"Coalesce low-signal sessions: on "
912
+ f"(min group {coalesce_min_group}, window {coalesce_window})"
913
+ )
914
+
915
+ if args.check:
916
+ available = backend.is_available()
917
+ print(f"Available: {available}")
918
+ return 0 if available else 1
919
+
920
+ # #420: vault-overlay mode isolates raw/wiki/state to the vault root.
921
+ vault_path = getattr(args, "vault", None)
922
+ raw_dir = wiki_sources_dir = state_file = None
923
+ if vault_path:
924
+ from sessionwiki.vault import resolve_vault
925
+ try:
926
+ vault = resolve_vault(vault_path)
927
+ except (FileNotFoundError, NotADirectoryError) as exc:
928
+ print(f"error: {exc}", file=sys.stderr)
929
+ return 2
930
+ # Post-final-review: Vault is a frozen dataclass with no
931
+ # __truediv__ — `vault / "raw"` raises TypeError. cmd_sync at
932
+ # line 205 correctly uses `vault.root / "raw"`; this site was
933
+ # the missed copy. Caught by the multi-agent code review.
934
+ raw_dir = vault.root / "raw" / "sessions"
935
+ wiki_sources_dir = vault.root / "wiki" / "sources"
936
+ state_file = vault.root / ".llmwiki-synth-state.json"
937
+
938
+ summary = synthesize_new_sessions(
939
+ backend=backend,
940
+ force=args.force,
941
+ raw_dir=raw_dir,
942
+ wiki_sources_dir=wiki_sources_dir,
943
+ state_file=state_file,
944
+ max_workers=max_workers,
945
+ coalesce_low_signal=coalesce_low_signal,
946
+ coalesce_min_group=coalesce_min_group,
947
+ coalesce_window=coalesce_window,
948
+ lock_skip_patterns=lock_skip_patterns,
949
+ coalesce_only=coalesce_only,
950
+ strip_unresolved_wikilinks=strip_links,
951
+ )
952
+ print(
953
+ f"Scanned {summary['total_scanned']}, new {summary['new_files']}, "
954
+ f"synthesized {summary['synthesized']}, skipped {summary['skipped']}"
955
+ )
956
+ if summary["errors"]:
957
+ for err in summary["errors"]:
958
+ print(f" ! {err}", file=sys.stderr)
959
+ return 1
960
+ return 0
961
+
962
+
963
+ # ─── #316 agent-delegate CLI helpers ─────────────────────────────────
964
+ # _synthesize_list_pending + _synthesize_complete moved to
965
+ # sessionwiki/synth/cli_helpers.py and re-exported at top of file (#691).
966
+
967
+
968
+ def _synthesize_estimate(config: dict | None = None) -> int:
969
+ """Print the G-07 incremental-vs-full-force cost report (v1.1.0 · #50 · #293).
970
+
971
+ Transparency over one-liner: reads the state file so the user sees
972
+ exactly which bucket gets billed next. The old ``--estimate`` printed
973
+ a single number without saying whether it covered the whole corpus
974
+ or just the delta.
975
+ """
976
+ from sessionwiki.cache import MODEL_PRICING
977
+
978
+ synth = (config or {}).get("synthesis", {}) or {}
979
+ backend = str(synth.get("backend") or "dummy")
980
+ model = str(synth.get("model") or "")
981
+ priced = model in MODEL_PRICING
982
+
983
+ if backend not in {"anthropic", "claude"} or (model and not priced):
984
+ print(
985
+ f"note: cost estimate uses Claude API pricing; "
986
+ f"backend {backend!r} may bill differently "
987
+ f"(local models are usually free)."
988
+ )
989
+
990
+ report = synthesize_estimate_report(model=model if priced else None)
991
+
992
+ for w in report["warnings"]:
993
+ print(f"warning: {w}")
994
+
995
+ print(f"Corpus: {report['corpus']:>6} sessions in raw/sessions/")
996
+ print(f"Already synthesized: {report['synthesized']:>6} pages in wiki/sources/")
997
+ print(f"New since last run: {report['new']:>6}")
998
+ print()
999
+ print(f"Prefix: {report['prefix_tokens']:,} tok Model: {report['model']}")
1000
+ print()
1001
+ if report["new"] == 0:
1002
+ print(f"Incremental sync: $0.0000 (nothing new — this is a no-op)")
1003
+ else:
1004
+ print(
1005
+ f"Incremental sync: ${report['incremental_usd']:.4f} "
1006
+ f"(synthesize the {report['new']} new session(s))"
1007
+ )
1008
+ print(
1009
+ f"Full re-synth: ${report['full_force_usd']:.4f} "
1010
+ f"(--force — {report['corpus']} session(s), 1 cache write + {max(report['corpus'] - 1, 0)} hits)"
1011
+ )
1012
+ return 0
1013
+
1014
+
1015
+ def cmd_candidates(args: argparse.Namespace) -> int:
1016
+ """List / promote / merge / discard candidate pages (v1.1.0 · #51)."""
1017
+ import json as _json
1018
+ from sessionwiki.candidates import (
1019
+ list_candidates,
1020
+ promote,
1021
+ merge as merge_candidate,
1022
+ discard,
1023
+ stale_candidates,
1024
+ )
1025
+
1026
+ wiki_dir = args.wiki_dir or (REPO_ROOT / "wiki")
1027
+ if not wiki_dir.is_dir():
1028
+ print(f"error: wiki directory not found: {wiki_dir}", file=sys.stderr)
1029
+ return 2
1030
+
1031
+ action = args.action
1032
+
1033
+ if action == "list":
1034
+ items = (
1035
+ stale_candidates(wiki_dir, threshold_days=args.stale_days)
1036
+ if args.stale else list_candidates(wiki_dir)
1037
+ )
1038
+ if args.json:
1039
+ # Path isn't JSON-serializable — drop it for the output
1040
+ cleaned = [{k: v for k, v in c.items() if k != "abs_path"} for c in items]
1041
+ print(_json.dumps(cleaned, indent=2))
1042
+ else:
1043
+ label = "stale" if args.stale else "pending"
1044
+ print(f" {len(items)} {label} candidate(s):")
1045
+ for c in items:
1046
+ age = f"{c['age_days']}d" if c["created"] else "unknown age"
1047
+ print(f" [{c['kind']:9}] {c['slug']} ({age}) — {c['title']}")
1048
+ return 0
1049
+
1050
+ if action == "promote":
1051
+ if not args.slug:
1052
+ print("error: --slug is required for promote", file=sys.stderr)
1053
+ return 2
1054
+ path = promote(args.slug, wiki_dir, kind=args.kind)
1055
+ print(f" promoted → {path.relative_to(wiki_dir)}")
1056
+ return 0
1057
+
1058
+ if action == "merge":
1059
+ if not args.slug or not args.into:
1060
+ print("error: both --slug and --into are required for merge", file=sys.stderr)
1061
+ return 2
1062
+ path = merge_candidate(args.slug, wiki_dir, into_slug=args.into, kind=args.kind)
1063
+ print(f" merged into → {path.relative_to(wiki_dir)}")
1064
+ return 0
1065
+
1066
+ if action == "discard":
1067
+ if not args.slug:
1068
+ print("error: --slug is required for discard", file=sys.stderr)
1069
+ return 2
1070
+ path = discard(args.slug, wiki_dir, reason=args.reason, kind=args.kind)
1071
+ print(f" discarded → {path.relative_to(wiki_dir)}")
1072
+ return 0
1073
+
1074
+ print(f"error: unknown action {action!r}", file=sys.stderr)
1075
+ return 2
1076
+
1077
+
1078
+ def _add_vault_arg(parser: argparse.ArgumentParser, *, role: str) -> None:
1079
+ """#arch-m8 (#620): single source of truth for the ``--vault`` flag.
1080
+
1081
+ All three subcommands that accept ``--vault`` (sync, build, synthesize)
1082
+ used to declare it independently with subtly different help text and
1083
+ behaviour. The semantics differ legitimately by subcommand (sync
1084
+ WRITES into the vault; build READS from it; synthesize isolates the
1085
+ state file under it), so we keep the role-specific help string per
1086
+ site, but the flag spelling, type, default, and metavar are unified
1087
+ here so a future refactor changes them in one place.
1088
+ """
1089
+ parser.add_argument(
1090
+ "--vault", type=Path, default=None, metavar="PATH",
1091
+ help={
1092
+ "sync": "Vault-overlay mode (#54): write new pages inside an "
1093
+ "existing Obsidian / Logseq vault instead of the "
1094
+ "repo's wiki/ directory.",
1095
+ "build": "Vault-overlay mode (#54): build from an existing "
1096
+ "Obsidian / Logseq vault. Still writes site output to "
1097
+ "--out.",
1098
+ "synthesize": "(#420) Vault-overlay mode: read raw/ + write "
1099
+ "wiki/sources/ under the vault root, and isolate "
1100
+ "the synth state file to the vault. Without this "
1101
+ "flag the state file lives at the repo root, so "
1102
+ "two vaults synthesised against the same repo "
1103
+ "silently share idempotency state.",
1104
+ "all": "(#383) With --with-synth: run synthesize against the "
1105
+ "vault's raw/ + wiki/sources/ (same semantics as "
1106
+ "`sessionwiki synthesize --vault`).",
1107
+ }[role],
1108
+ )
1109
+
1110
+
1111
+ def build_parser() -> argparse.ArgumentParser:
1112
+ p = argparse.ArgumentParser(
1113
+ prog="sessionwiki",
1114
+ description="LLM-powered knowledge base from Claude Code and Codex CLI sessions.",
1115
+ )
1116
+ p.add_argument("--version", action="version", version=f"sessionwiki {__version__}")
1117
+
1118
+ sub = p.add_subparsers(dest="cmd", metavar="COMMAND")
1119
+
1120
+ # init
1121
+ init = sub.add_parser("init", help="Scaffold raw/, wiki/, site/ directories")
1122
+ init.set_defaults(func=cmd_init)
1123
+
1124
+ # sync
1125
+ sync = sub.add_parser("sync", help="Convert new .jsonl sessions to markdown")
1126
+ sync.add_argument("--adapter", nargs="*", default=None, help="Adapter(s) to run; default: all available")
1127
+ sync.add_argument("--since", type=str, help="Only sessions on or after YYYY-MM-DD")
1128
+ sync.add_argument("--project", type=str, help="Substring filter on project slug")
1129
+ sync.add_argument("--include-current", action="store_true", help="Don't skip live sessions (<60 min)")
1130
+ sync.add_argument("--force", action="store_true", help="Ignore state file, reconvert everything")
1131
+ sync.add_argument(
1132
+ "--dry-run", action="store_true",
1133
+ help="Preview conversions without writing raw/ or refreshing the ZCode/OpenCode exports",
1134
+ )
1135
+ sync.add_argument(
1136
+ "--zcode-export", action=argparse.BooleanOptionalAction, default=True,
1137
+ help="Refresh the ZCode JSONL corpus before converting "
1138
+ "(default: on when the ZCode database exists; pass "
1139
+ "--no-zcode-export to skip)",
1140
+ )
1141
+ sync.add_argument(
1142
+ "--zcode-db", type=Path, default=None,
1143
+ help="Path to ZCode db.sqlite (default: ~/.zcode/cli/db/db.sqlite)",
1144
+ )
1145
+ sync.add_argument(
1146
+ "--opencode-export", action=argparse.BooleanOptionalAction, default=True,
1147
+ help="Refresh the OpenCode JSONL corpus before converting "
1148
+ "(default: on when the OpenCode database exists; pass "
1149
+ "--no-opencode-export to skip)",
1150
+ )
1151
+ sync.add_argument(
1152
+ "--opencode-db", type=Path, default=None,
1153
+ help="Path to OpenCode opencode.db "
1154
+ "(default: ~/.local/share/opencode/opencode.db)",
1155
+ )
1156
+ sync.add_argument(
1157
+ "--auto-build", action=argparse.BooleanOptionalAction, default=True,
1158
+ help="After sync, rebuild the site when sessions_config.json's "
1159
+ "schedule.build is 'on-sync' (default: on; pass --no-auto-build to skip)",
1160
+ )
1161
+ sync.add_argument(
1162
+ "--auto-lint", action=argparse.BooleanOptionalAction, default=True,
1163
+ help="After sync, run lint when sessions_config.json's "
1164
+ "schedule.lint is 'on-sync' (default: on; pass --no-auto-lint to skip)",
1165
+ )
1166
+ _add_vault_arg(sync, role="sync")
1167
+ sync.add_argument(
1168
+ "--allow-overwrite", action="store_true",
1169
+ help="With --vault: allow clobbering existing vault pages "
1170
+ "(default: refuse, append under ## Connections instead)",
1171
+ )
1172
+ sync.add_argument(
1173
+ "--status", action="store_true",
1174
+ help="Show last-sync time + per-adapter counters + quarantine "
1175
+ "(G-03 · #289). Does not run a sync.",
1176
+ )
1177
+ sync.add_argument(
1178
+ "--recent", type=int, default=0,
1179
+ help="With --status: also show last N recent log entries.",
1180
+ )
1181
+ sync.set_defaults(func=cmd_sync)
1182
+
1183
+ # build
1184
+ build = sub.add_parser("build", help="Compile static HTML site from raw/ + wiki/")
1185
+ build.add_argument("--out", type=Path, default=REPO_ROOT / "site", help="Output dir (default: site/)")
1186
+ build.add_argument("--synthesize", action="store_true", help="Call claude CLI for overview synthesis")
1187
+ build.add_argument(
1188
+ "--claude", type=str, default="",
1189
+ help="Path to claude CLI (#421: defaults to `shutil.which('claude')` "
1190
+ "so PATH-based / brew / nvm / Windows installs all work)",
1191
+ )
1192
+ build.add_argument(
1193
+ "--search-mode", choices=["auto", "tree", "flat"], default="auto",
1194
+ help="Search index mode (#53): auto picks tree vs flat from heading depth",
1195
+ )
1196
+ _add_vault_arg(build, role="build")
1197
+ build.add_argument(
1198
+ "--seed-project-stubs", action="store_true", dest="seed_project_stubs",
1199
+ help="(#414) Auto-create wiki/projects/<slug>.md stubs for any "
1200
+ "newly-discovered project that doesn't have a metadata file. "
1201
+ "Off by default — `build` is read-only on wiki/. Use `sync` "
1202
+ "(which already mutates wiki/) for routine seeding, or pass "
1203
+ "this flag to opt in from CI/scripts.",
1204
+ )
1205
+ build.set_defaults(func=cmd_build)
1206
+
1207
+ # serve
1208
+ serve = sub.add_parser("serve", help="Start local HTTP server")
1209
+ serve.add_argument("--dir", type=Path, default=REPO_ROOT / "site", help="Directory to serve (default: site/)")
1210
+ serve.add_argument("--port", type=int, default=8765)
1211
+ serve.add_argument("--host", type=str, default="127.0.0.1")
1212
+ serve.add_argument("--open", action="store_true", help="Open browser after starting")
1213
+ serve.set_defaults(func=cmd_serve)
1214
+
1215
+ # adapters
1216
+ ads = sub.add_parser("adapters", help="List available adapters")
1217
+ ads.add_argument(
1218
+ "--wide",
1219
+ action="store_true",
1220
+ help="Show untruncated adapter descriptions (G-02 · #288).",
1221
+ )
1222
+ ads.set_defaults(func=cmd_adapters)
1223
+
1224
+ # doctor — install diagnostics for a fresh machine
1225
+ from sessionwiki.doctor import cmd_doctor as _cmd_doctor
1226
+
1227
+ doctor = sub.add_parser(
1228
+ "doctor",
1229
+ help="Check Python, dependencies, config, and ZCode paths on this machine",
1230
+ )
1231
+ doctor.set_defaults(func=_cmd_doctor)
1232
+
1233
+ # audit — pre-publish privacy check
1234
+ from sessionwiki.audit import cmd_audit as _cmd_audit
1235
+
1236
+ audit = sub.add_parser(
1237
+ "audit",
1238
+ help="Scan raw/, wiki/, and site/ for usernames and secrets",
1239
+ )
1240
+ audit.add_argument(
1241
+ "--path", action="append", type=Path, default=None,
1242
+ help="file or directory to scan (repeatable; default: raw/ wiki/ site/)",
1243
+ )
1244
+ audit.add_argument(
1245
+ "--username", default=None,
1246
+ help="username to search for (default: redaction.real_username or $USER)",
1247
+ )
1248
+ audit.add_argument("--json", action="store_true", help="emit a JSON report")
1249
+ audit.add_argument(
1250
+ "--fail-on-findings", action="store_true",
1251
+ help="exit 1 when anything is found (for a publish gate)",
1252
+ )
1253
+ audit.set_defaults(func=_cmd_audit)
1254
+
1255
+ # zcode (ZCode session-store integration)
1256
+ zcode = sub.add_parser("zcode", help="ZCode session-store export")
1257
+ zcode_sub = zcode.add_subparsers(dest="zcode_command", metavar="COMMAND")
1258
+ zcode_export = zcode_sub.add_parser(
1259
+ "export", help="Export ~/.zcode/cli/db/db.sqlite to JSONL"
1260
+ )
1261
+ from sessionwiki.zcode.export import DEFAULT_DB as _ZCODE_DB
1262
+ from sessionwiki.zcode.export import DEFAULT_OUT_DIR as _ZCODE_OUT
1263
+
1264
+ zcode_export.add_argument(
1265
+ "--db", type=Path, default=_ZCODE_DB, help="path to ZCode db.sqlite"
1266
+ )
1267
+ zcode_export.add_argument(
1268
+ "--out-dir", type=Path, default=_ZCODE_OUT, help="JSONL output directory"
1269
+ )
1270
+ zcode_export.add_argument(
1271
+ "--state-file", type=Path, default=None, help="incremental state file"
1272
+ )
1273
+ zcode_export.add_argument(
1274
+ "--since", default=None, help="only sessions updated on/after YYYY-MM-DD"
1275
+ )
1276
+ zcode_export.add_argument(
1277
+ "--project", default=None,
1278
+ help="case-insensitive project path or slug substring",
1279
+ )
1280
+ zcode_export.add_argument(
1281
+ "--project-root",
1282
+ dest="project_roots",
1283
+ action="append",
1284
+ type=Path,
1285
+ default=None,
1286
+ help="treat this directory as a project root (repeatable)",
1287
+ )
1288
+ zcode_export.add_argument(
1289
+ "--include-subagents", action="store_true",
1290
+ help="include subagent_child sessions",
1291
+ )
1292
+ zcode_export.add_argument(
1293
+ "--keep-stale", action="store_true",
1294
+ help="do not remove JSONL for sessions deleted from the database",
1295
+ )
1296
+ zcode_export.add_argument(
1297
+ "--strict", action="store_true",
1298
+ help="exit 1 when any session fails, even if others exported",
1299
+ )
1300
+ zcode_export.add_argument(
1301
+ "--dry-run", action="store_true",
1302
+ help="show counters without writing files",
1303
+ )
1304
+ zcode_export.set_defaults(func=cmd_zcode_export)
1305
+
1306
+ autosync = zcode_sub.add_parser(
1307
+ "autosync",
1308
+ help="Export, convert, and optionally build (portable scheduler entry point)",
1309
+ )
1310
+ autosync.add_argument(
1311
+ "--db", type=Path, default=_ZCODE_DB, help="path to ZCode db.sqlite"
1312
+ )
1313
+ autosync.add_argument(
1314
+ "--out-dir", type=Path, default=_ZCODE_OUT, help="JSONL output directory"
1315
+ )
1316
+ autosync.add_argument(
1317
+ "--project", default=None,
1318
+ help="case-insensitive project path or slug substring",
1319
+ )
1320
+ autosync.add_argument(
1321
+ "--build", action="store_true",
1322
+ help="rebuild site/ after converting",
1323
+ )
1324
+ autosync.add_argument(
1325
+ "--coalesce", action="store_true",
1326
+ help="run deterministic low-signal coalescing after sync",
1327
+ )
1328
+ autosync.add_argument(
1329
+ "--lock-timeout", type=float, default=600,
1330
+ help="seconds to wait for another autosync (default: 600)",
1331
+ )
1332
+ autosync.add_argument(
1333
+ "--log", type=Path, default=None,
1334
+ help="log file (default: ~/.llmwiki/zcode/autosync.log)",
1335
+ )
1336
+ autosync.add_argument(
1337
+ "--quiet", action="store_true",
1338
+ help="write only to the log file",
1339
+ )
1340
+ autosync.set_defaults(func=cmd_zcode_autosync)
1341
+
1342
+ install = zcode_sub.add_parser(
1343
+ "install",
1344
+ help="Install the Stop-hook and a native autosync scheduler",
1345
+ )
1346
+ install.add_argument(
1347
+ "--scheduler",
1348
+ choices=["auto", "systemd", "launchd", "windows", "none"],
1349
+ default="auto",
1350
+ help="Native scheduler (default: auto-detect)",
1351
+ )
1352
+ install.add_argument("--at", default="03:30", help="daily start time HH:MM")
1353
+ install.add_argument(
1354
+ "--python",
1355
+ dest="python_exe",
1356
+ default=None,
1357
+ help="Python interpreter for the scheduled command (default: current)",
1358
+ )
1359
+ install.add_argument(
1360
+ "--repo-root",
1361
+ type=Path,
1362
+ default=None,
1363
+ help="sessionwiki checkout used as WorkingDirectory (default: this repo)",
1364
+ )
1365
+ install.add_argument("--no-build", action="store_true", help="do not rebuild site/")
1366
+ install.add_argument(
1367
+ "--coalesce", action="store_true",
1368
+ help="also run deterministic low-signal coalescing",
1369
+ )
1370
+ install.add_argument("--no-hook", action="store_true", help="skip the ZCode Stop hook")
1371
+ install.add_argument("--dry-run", action="store_true", help="print changes only")
1372
+ install.add_argument(
1373
+ "--force", action="store_true", help="replace an existing autosync hook"
1374
+ )
1375
+ install.set_defaults(func=cmd_zcode_install)
1376
+
1377
+ # opencode (OpenCode session-store integration)
1378
+ opencode = sub.add_parser(
1379
+ "opencode", help="OpenCode session-store export"
1380
+ )
1381
+ opencode_sub = opencode.add_subparsers(
1382
+ dest="opencode_command", metavar="COMMAND"
1383
+ )
1384
+ opencode_export = opencode_sub.add_parser(
1385
+ "export", help="Export ~/.local/share/opencode/opencode.db to JSONL"
1386
+ )
1387
+ from sessionwiki.opencode.export import DEFAULT_DB as _OPENCODE_DB
1388
+ from sessionwiki.opencode.export import DEFAULT_OUT_DIR as _OPENCODE_OUT
1389
+
1390
+ opencode_export.add_argument(
1391
+ "--db", type=Path, default=_OPENCODE_DB,
1392
+ help="path to OpenCode opencode.db",
1393
+ )
1394
+ opencode_export.add_argument(
1395
+ "--out-dir", type=Path, default=_OPENCODE_OUT,
1396
+ help="JSONL output directory",
1397
+ )
1398
+ opencode_export.add_argument(
1399
+ "--state-file", type=Path, default=None,
1400
+ help="incremental state file",
1401
+ )
1402
+ opencode_export.add_argument(
1403
+ "--since", default=None,
1404
+ help="only sessions updated on/after YYYY-MM-DD",
1405
+ )
1406
+ opencode_export.add_argument(
1407
+ "--project", default=None,
1408
+ help="case-insensitive project path or slug substring",
1409
+ )
1410
+ opencode_export.add_argument(
1411
+ "--project-root",
1412
+ dest="project_roots",
1413
+ action="append",
1414
+ type=Path,
1415
+ default=None,
1416
+ help="treat this directory as a project root (repeatable)",
1417
+ )
1418
+ opencode_export.add_argument(
1419
+ "--include-subagents", action="store_true",
1420
+ help="include child/subagent sessions",
1421
+ )
1422
+ opencode_export.add_argument(
1423
+ "--keep-stale", action="store_true",
1424
+ help="do not remove JSONL for sessions deleted from the database",
1425
+ )
1426
+ opencode_export.add_argument(
1427
+ "--strict", action="store_true",
1428
+ help="exit 1 when any session fails, even if others exported",
1429
+ )
1430
+ opencode_export.add_argument(
1431
+ "--dry-run", action="store_true",
1432
+ help="show counters without writing files",
1433
+ )
1434
+ opencode_export.set_defaults(func=cmd_opencode_export)
1435
+
1436
+ opencode_autosync = opencode_sub.add_parser(
1437
+ "autosync",
1438
+ help="Export, convert, and optionally build (portable scheduler entry point)",
1439
+ )
1440
+ opencode_autosync.add_argument(
1441
+ "--db", type=Path, default=_OPENCODE_DB,
1442
+ help="path to OpenCode opencode.db",
1443
+ )
1444
+ opencode_autosync.add_argument(
1445
+ "--out-dir", type=Path, default=_OPENCODE_OUT,
1446
+ help="JSONL output directory",
1447
+ )
1448
+ opencode_autosync.add_argument(
1449
+ "--project", default=None,
1450
+ help="case-insensitive project path or slug substring",
1451
+ )
1452
+ opencode_autosync.add_argument(
1453
+ "--build", action="store_true",
1454
+ help="rebuild site/ after converting",
1455
+ )
1456
+ opencode_autosync.add_argument(
1457
+ "--lock-timeout", type=float, default=600,
1458
+ help="seconds to wait for another autosync (default: 600)",
1459
+ )
1460
+ opencode_autosync.add_argument(
1461
+ "--log", type=Path, default=None,
1462
+ help="log file (default: ~/.llmwiki/opencode/autosync.log)",
1463
+ )
1464
+ opencode_autosync.add_argument(
1465
+ "--quiet", action="store_true",
1466
+ help="write only to the log file",
1467
+ )
1468
+ opencode_autosync.set_defaults(func=cmd_opencode_autosync)
1469
+
1470
+ opencode_install = opencode_sub.add_parser(
1471
+ "install",
1472
+ help="Install the OpenCode autosync plugin",
1473
+ )
1474
+ opencode_install.add_argument(
1475
+ "--python",
1476
+ dest="python_exe",
1477
+ default=None,
1478
+ help="Python interpreter for the plugin command (default: current)",
1479
+ )
1480
+ opencode_install.add_argument(
1481
+ "--repo-root",
1482
+ type=Path,
1483
+ default=None,
1484
+ help="sessionwiki checkout used as the plugin working directory (default: this repo)",
1485
+ )
1486
+ opencode_install.add_argument(
1487
+ "--build", action="store_true",
1488
+ help="rebuild site/ after each autosync (default: off)",
1489
+ )
1490
+ opencode_install.add_argument(
1491
+ "--no-build", action="store_true", help="do not rebuild site/"
1492
+ )
1493
+ opencode_install.add_argument(
1494
+ "--dry-run", action="store_true", help="print changes only"
1495
+ )
1496
+ opencode_install.add_argument(
1497
+ "--force", action="store_true", help="replace an existing plugin"
1498
+ )
1499
+ opencode_install.set_defaults(func=cmd_opencode_install)
1500
+
1501
+ # graph
1502
+ graph = sub.add_parser("graph", help="Build the knowledge graph (graph/graph.json + graph.html)")
1503
+ graph.add_argument("--format", choices=["json", "html", "both"], default="both")
1504
+ graph.add_argument(
1505
+ "--engine", choices=["builtin", "graphify"], default="graphify",
1506
+ help="Graph engine: 'graphify' (AI-powered, default) or 'builtin' (stdlib wikilinks fallback)",
1507
+ )
1508
+ graph.set_defaults(func=cmd_graph)
1509
+
1510
+ # export (v0.4)
1511
+ exp2 = sub.add_parser(
1512
+ "export",
1513
+ help="Export AI-consumable formats: llms-txt, llms-full-txt, jsonld, sitemap, rss, robots, ai-readme, marp (or 'all')",
1514
+ )
1515
+ exp2.add_argument(
1516
+ "format",
1517
+ choices=["llms-txt", "llms-full-txt", "jsonld", "sitemap", "rss", "robots", "ai-readme", "marp", "all"],
1518
+ help="Export format",
1519
+ )
1520
+ exp2.add_argument("--out", type=Path, default=None, help="Output directory (default: site/)")
1521
+ exp2.add_argument("--topic", type=str, default="", help="Topic filter for marp slide generation")
1522
+ exp2.set_defaults(func=cmd_export)
1523
+
1524
+ # lint (v1.0, #155) — live count via the rule registry (currently 15)
1525
+ from sessionwiki.lint import REGISTRY as _LINT_REG
1526
+ from sessionwiki.lint import rules as _lint_rules # noqa: F401 — force registration
1527
+ lint = sub.add_parser(
1528
+ "lint",
1529
+ help=f"Run all {len(_LINT_REG)} lint rules against the wiki",
1530
+ )
1531
+ lint.add_argument("--wiki-dir", type=Path, default=None,
1532
+ help="Wiki directory (default: ./wiki)")
1533
+ lint.add_argument("--rules", type=str, default=None,
1534
+ help="Comma-separated rule names (default: all applicable)")
1535
+ lint.add_argument("--include-llm", action="store_true",
1536
+ help="Also run LLM-powered rules (requires --llm-callback)")
1537
+ lint.add_argument("--json", action="store_true", help="JSON output")
1538
+ lint.add_argument("--fail-on-errors", action="store_true",
1539
+ help="Exit non-zero if any error-severity issues found")
1540
+ lint.set_defaults(func=cmd_lint)
1541
+
1542
+ # candidates (v1.1, #51) — approval workflow
1543
+ cand = sub.add_parser(
1544
+ "candidates",
1545
+ help="List / promote / merge / discard candidate wiki pages (approval workflow)",
1546
+ )
1547
+ cand.add_argument(
1548
+ "action", choices=["list", "promote", "merge", "discard"],
1549
+ help="What to do with candidates",
1550
+ )
1551
+ cand.add_argument("--slug", type=str, default=None,
1552
+ help="Candidate slug (required for promote/merge/discard)")
1553
+ cand.add_argument("--into", type=str, default=None,
1554
+ help="For merge: slug of the page to merge into")
1555
+ cand.add_argument("--reason", type=str, default="",
1556
+ help="For discard: why the candidate is being rejected")
1557
+ cand.add_argument("--kind", type=str, default=None,
1558
+ choices=["entities", "concepts", "sources", "syntheses"],
1559
+ help="Subtree (auto-detected if omitted)")
1560
+ cand.add_argument("--wiki-dir", type=Path, default=None,
1561
+ help="Wiki directory (default: ./wiki)")
1562
+ cand.add_argument("--stale", action="store_true",
1563
+ help="For list: only show stale candidates")
1564
+ cand.add_argument("--stale-days", type=int, default=30,
1565
+ help="Staleness threshold in days (default 30)")
1566
+ cand.add_argument("--json", action="store_true", help="JSON output for list")
1567
+ cand.set_defaults(func=cmd_candidates)
1568
+
1569
+ # synthesize (v1.1, #35) — LLM-backed wiki page synthesis
1570
+ syn = sub.add_parser(
1571
+ "synthesize",
1572
+ help="Synthesize wiki source pages from raw sessions via LLM backend",
1573
+ )
1574
+ # #arch-h7 (#610): the four "what should this invocation do?" flags
1575
+ # used to be independently set-able. argparse silently honoured the
1576
+ # first one in `cmd_synthesize`'s if/elif chain, so e.g.
1577
+ # `synthesize --check --estimate` ran --check and silently dropped
1578
+ # --estimate. Use a mutually-exclusive group so the parser rejects
1579
+ # the combination loudly with a useful error.
1580
+ syn_mode = syn.add_mutually_exclusive_group()
1581
+ syn_mode.add_argument(
1582
+ "--check", action="store_true",
1583
+ help="Probe backend availability and exit (exit 0 if reachable)",
1584
+ )
1585
+ syn_mode.add_argument(
1586
+ "--estimate", action="store_true",
1587
+ help="Print cached-vs-fresh token + dollar estimate without calling a backend (#50)",
1588
+ )
1589
+ # #316 — agent-delegate backend helpers (mutually-exclusive with the
1590
+ # default synthesize-all flow + with --check / --estimate above).
1591
+ syn_mode.add_argument(
1592
+ "--list-pending", action="store_true",
1593
+ help="List pending prompts awaiting agent synthesis (agent-delegate backend, #316)",
1594
+ )
1595
+ syn_mode.add_argument(
1596
+ "--complete", metavar="UUID", default=None,
1597
+ help="Complete a pending synthesis: read body from --body or stdin, rewrite --page in place (#316)",
1598
+ )
1599
+ syn_mode.add_argument(
1600
+ "--coalesce-only", action="store_true",
1601
+ help="Run deterministic low-signal coalescing only; no LLM backend needed",
1602
+ )
1603
+ # --force is orthogonal (modifies the default re-synthesize-all flow)
1604
+ # and stays outside the exclusion group so callers can pass
1605
+ # `synthesize --force` for a forced full re-run.
1606
+ syn.add_argument(
1607
+ "--force", action="store_true",
1608
+ help="Ignore state file, re-synthesize all sessions",
1609
+ )
1610
+ syn.add_argument(
1611
+ "--page", metavar="PATH", default=None,
1612
+ help="Target wiki source page for --complete (path relative to repo root or absolute)",
1613
+ )
1614
+ syn.add_argument(
1615
+ "--body", metavar="PATH", default=None,
1616
+ help="Read synthesized body from this file for --complete (default: stdin)",
1617
+ )
1618
+ _add_vault_arg(syn, role="synthesize")
1619
+ syn.set_defaults(func=cmd_synthesize)
1620
+
1621
+ # query — natural-language graph query
1622
+ qry = sub.add_parser("query", help="Query the knowledge graph with a question")
1623
+ qry.add_argument("question", nargs="+", help="The question to ask")
1624
+ qry.add_argument("--depth", type=int, default=3, help="BFS traversal depth (default: 3)")
1625
+ qry.add_argument("--budget", type=int, default=2000, help="Max output tokens (default: 2000)")
1626
+ qry.set_defaults(func=cmd_query)
1627
+
1628
+ # version
1629
+ ver = sub.add_parser("version", help="Print version")
1630
+ ver.set_defaults(func=cmd_version)
1631
+
1632
+ # all — run build + graph + export all + lint in sequence
1633
+ all_p = sub.add_parser(
1634
+ "all",
1635
+ help="Run the full pipeline: build → graph → export all → lint "
1636
+ "(add --with-synth to run synthesize first)",
1637
+ )
1638
+ all_p.add_argument(
1639
+ "--out", type=Path, default=REPO_ROOT / "site",
1640
+ help="Output dir for build + export (default: site/)",
1641
+ )
1642
+ all_p.add_argument(
1643
+ "--search-mode", choices=["auto", "tree", "flat"], default="auto",
1644
+ help="Search index mode passed through to build (default: auto)",
1645
+ )
1646
+ all_p.add_argument(
1647
+ "--graph-engine", choices=["builtin", "graphify"], default="graphify",
1648
+ help="Graph engine passed through to graph (default: graphify)",
1649
+ )
1650
+ all_p.add_argument(
1651
+ "--skip-graph", action="store_true",
1652
+ help="Skip the graph step (useful when graphify is not installed)",
1653
+ )
1654
+ all_p.add_argument(
1655
+ "--fail-fast", action="store_true",
1656
+ help="Stop at the first non-zero step (default: continue, report worst exit code)",
1657
+ )
1658
+ all_p.add_argument(
1659
+ "--strict", action="store_true",
1660
+ help="Exit 2 if lint reports any errors/warnings",
1661
+ )
1662
+ all_p.add_argument(
1663
+ "--with-synth", action="store_true",
1664
+ help="Run `synthesize` before build (fills wiki/sources/ from raw/; "
1665
+ "may invoke LLM — default off for cost discipline, #383)",
1666
+ )
1667
+ all_p.add_argument(
1668
+ "--synth-force", action="store_true",
1669
+ help="With --with-synth: pass --force to synthesize (re-synthesize all sessions)",
1670
+ )
1671
+ _add_vault_arg(all_p, role="all")
1672
+ all_p.set_defaults(func=cmd_all)
1673
+
1674
+ return p
1675
+
1676
+
1677
+ def main(argv: list[str] | None = None) -> int:
1678
+ parser = build_parser()
1679
+ args = parser.parse_args(argv)
1680
+ if not hasattr(args, "func"):
1681
+ parser.print_help()
1682
+ return 0
1683
+ return args.func(args)
1684
+
1685
+
1686
+ if __name__ == "__main__":
1687
+ sys.exit(main())