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
@@ -0,0 +1,386 @@
1
+ """Install ZCode autosync for the current machine.
2
+
3
+ Two pieces:
4
+
5
+ * a ZCode ``Stop`` hook, written into ``~/.zcode/cli/config.json``;
6
+ * a native scheduler entry — systemd user timer (Linux), launchd agent
7
+ (macOS), or a Task Scheduler command (Windows).
8
+
9
+ All functions accept ``home`` and ``repo_root`` so tests (and callers
10
+ that manage a non-default profile) never touch the real user config.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import re
18
+ import shutil
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Optional
22
+ from xml.sax.saxutils import escape as _xml_escape
23
+
24
+ _AT_RE = re.compile(r"^([01]?\d|2[0-3]):([0-5]\d)$")
25
+ _SERVICE_NAME = "sessionwiki-zcode.service"
26
+ _TIMER_NAME = "sessionwiki-zcode.timer"
27
+ _LAUNCHD_LABEL = "com.sessionwiki.zcode.autosync"
28
+
29
+
30
+ def _home(home: Optional[Path]) -> Path:
31
+ return Path(home) if home is not None else Path.home()
32
+
33
+
34
+ def _python(python_exe: Optional[Path | str]) -> str:
35
+ return str(Path(python_exe) if python_exe is not None else Path(sys.executable))
36
+
37
+
38
+ def _at_parts(at: str) -> tuple[int, int]:
39
+ match = _AT_RE.match(str(at).strip())
40
+ if not match:
41
+ raise ValueError(f"invalid --at value: {at!r} (expected HH:MM)")
42
+ return int(match.group(1)), int(match.group(2))
43
+
44
+
45
+ def _autosync_command(python_exe: str, *, build: bool, coalesce: bool = False) -> str:
46
+ executable = f'"{python_exe}"' if " " in python_exe else python_exe
47
+ command = f'{executable} -m sessionwiki zcode autosync'
48
+ if coalesce:
49
+ command += " --coalesce"
50
+ if build:
51
+ command += " --build"
52
+ return command
53
+
54
+
55
+ def _cmd_escape(text: str) -> str:
56
+ """Escape ``%`` for a .cmd file, where ``%name%`` expands as a variable."""
57
+ return text.replace("%", "%%")
58
+
59
+
60
+ def _hook_command(
61
+ python_exe: str, *, build: bool, coalesce: bool = False
62
+ ) -> str:
63
+ # The Stop hook fires after every reply. --lock-timeout 0 skips when a
64
+ # cycle is already running instead of queueing a process that waits up
65
+ # to 600 s; the nightly timer (no flag) is the run that waits.
66
+ base = (
67
+ _autosync_command(python_exe, build=build, coalesce=coalesce)
68
+ + " --lock-timeout 0"
69
+ )
70
+ if os.name == "nt":
71
+ return f'start "" /B {base}'
72
+ return f'nohup {base} >/dev/null 2>&1 &'
73
+
74
+
75
+ def _entry_has_autosync(entry: object) -> bool:
76
+ if not isinstance(entry, dict):
77
+ return False
78
+ hooks = entry.get("hooks")
79
+ if not isinstance(hooks, list):
80
+ return False
81
+ return any(
82
+ isinstance(hook, dict) and "zcode autosync" in str(hook.get("command", ""))
83
+ for hook in hooks
84
+ )
85
+
86
+
87
+ def _contains_autosync(entries: list) -> bool:
88
+ return any(_entry_has_autosync(entry) for entry in entries)
89
+
90
+
91
+ def install_hook(
92
+ *,
93
+ home: Optional[Path] = None,
94
+ python_exe: Optional[Path | str] = None,
95
+ repo_root: Optional[Path] = None,
96
+ build: bool = False,
97
+ coalesce: bool = False,
98
+ dry_run: bool = False,
99
+ force: bool = False,
100
+ ) -> list[str]:
101
+ """Add a ZCode ``Stop`` hook that runs autosync. Idempotent."""
102
+ home_dir = _home(home)
103
+ py = _python(python_exe)
104
+ path = home_dir / ".zcode" / "cli" / "config.json"
105
+
106
+ data: dict = {}
107
+ if path.is_file():
108
+ try:
109
+ loaded = json.loads(path.read_text(encoding="utf-8"))
110
+ except (OSError, json.JSONDecodeError) as exc:
111
+ raise ValueError(f"cannot read {path}: {exc}") from exc
112
+ if not isinstance(loaded, dict):
113
+ raise ValueError(f"{path} must contain a JSON object")
114
+ data = loaded
115
+
116
+ hooks = data.setdefault("hooks", {})
117
+ if not isinstance(hooks, dict):
118
+ raise ValueError(f"{path}: 'hooks' must be an object")
119
+ events = hooks.setdefault("events", {})
120
+ if not isinstance(events, dict):
121
+ raise ValueError(f"{path}: 'hooks.events' must be an object")
122
+ stop = events.setdefault("Stop", [])
123
+ if not isinstance(stop, list):
124
+ raise ValueError(f"{path}: 'hooks.events.Stop' must be a list")
125
+
126
+ command = _hook_command(py, build=build, coalesce=coalesce)
127
+ if _contains_autosync(stop):
128
+ if not force:
129
+ return [f"hook: already installed in {path}"]
130
+ stop[:] = [entry for entry in stop if not _entry_has_autosync(entry)]
131
+ hooks["enabled"] = True
132
+ stop.append(
133
+ {
134
+ "hooks": [
135
+ {
136
+ "type": "command",
137
+ "command": command,
138
+ "timeout": 10,
139
+ }
140
+ ]
141
+ }
142
+ )
143
+
144
+ if dry_run:
145
+ return [f"hook: would update {path}"]
146
+
147
+ path.parent.mkdir(parents=True, exist_ok=True)
148
+ path.write_text(
149
+ json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
150
+ )
151
+ return [f"hook: installed in {path}"]
152
+
153
+
154
+ def install_systemd(
155
+ *,
156
+ home: Optional[Path] = None,
157
+ python_exe: Optional[Path | str] = None,
158
+ repo_root: Optional[Path] = None,
159
+ at: str = "03:30",
160
+ build: bool = True,
161
+ coalesce: bool = False,
162
+ dry_run: bool = False,
163
+ ) -> list[str]:
164
+ """Write a systemd --user service and timer (does not enable them)."""
165
+ hour, minute = _at_parts(at)
166
+ home_dir = _home(home)
167
+ py = _python(python_exe)
168
+ root = Path(repo_root) if repo_root is not None else Path.cwd()
169
+ unit_dir = home_dir / ".config" / "systemd" / "user"
170
+ service_path = unit_dir / _SERVICE_NAME
171
+ timer_path = unit_dir / _TIMER_NAME
172
+
173
+ service = (
174
+ "[Unit]\n"
175
+ "Description=Export ZCode sessions and sync sessionwiki\n"
176
+ "After=default.target\n\n"
177
+ "[Service]\n"
178
+ "Type=oneshot\n"
179
+ f"WorkingDirectory={root}\n"
180
+ f"ExecStart={_autosync_command(py, build=build, coalesce=coalesce)}\n"
181
+ "Nice=10\n"
182
+ )
183
+ timer = (
184
+ "[Unit]\n"
185
+ "Description=Nightly sessionwiki ZCode sync\n\n"
186
+ "[Timer]\n"
187
+ f"Unit={_SERVICE_NAME}\n"
188
+ f"OnCalendar=*-*-* {hour:02d}:{minute:02d}:00\n"
189
+ "Persistent=true\n"
190
+ "RandomizedDelaySec=300\n\n"
191
+ "[Install]\n"
192
+ "WantedBy=timers.target\n"
193
+ )
194
+
195
+ if dry_run:
196
+ return [
197
+ f"systemd: would write {service_path}",
198
+ f"systemd: would write {timer_path}",
199
+ ]
200
+
201
+ unit_dir.mkdir(parents=True, exist_ok=True)
202
+ service_path.write_text(service, encoding="utf-8")
203
+ timer_path.write_text(timer, encoding="utf-8")
204
+ return [
205
+ f"systemd: wrote {service_path}",
206
+ f"systemd: wrote {timer_path}",
207
+ "systemd: enable with: systemctl --user daemon-reload && "
208
+ f"systemctl --user enable --now {_TIMER_NAME}",
209
+ ]
210
+
211
+
212
+ def install_launchd(
213
+ *,
214
+ home: Optional[Path] = None,
215
+ python_exe: Optional[Path | str] = None,
216
+ repo_root: Optional[Path] = None,
217
+ at: str = "03:30",
218
+ build: bool = True,
219
+ coalesce: bool = False,
220
+ dry_run: bool = False,
221
+ ) -> Path:
222
+ """Write a launchd agent plist and return its path."""
223
+ hour, minute = _at_parts(at)
224
+ home_dir = _home(home)
225
+ py = _python(python_exe)
226
+ root = Path(repo_root) if repo_root is not None else Path.cwd()
227
+ plist_path = home_dir / "Library" / "LaunchAgents" / f"{_LAUNCHD_LABEL}.plist"
228
+ log_dir = home_dir / ".llmwiki" / "zcode"
229
+ program = [py, "-m", "sessionwiki", "zcode", "autosync"]
230
+ if coalesce:
231
+ program.append("--coalesce")
232
+ if build:
233
+ program.append("--build")
234
+ args_xml = "\n".join(f" <string>{_xml_escape(arg)}</string>" for arg in program)
235
+ plist = (
236
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
237
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" '
238
+ '"http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
239
+ '<plist version="1.0">\n'
240
+ "<dict>\n"
241
+ f" <key>Label</key>\n <string>{_LAUNCHD_LABEL}</string>\n"
242
+ " <key>ProgramArguments</key>\n"
243
+ " <array>\n"
244
+ f"{args_xml}\n"
245
+ " </array>\n"
246
+ f" <key>WorkingDirectory</key>\n <string>{_xml_escape(str(root))}</string>\n"
247
+ f" <key>StandardOutPath</key>\n <string>{_xml_escape(str(log_dir / 'autosync.log'))}</string>\n"
248
+ f" <key>StandardErrorPath</key>\n <string>{_xml_escape(str(log_dir / 'autosync.log'))}</string>\n"
249
+ " <key>StartCalendarInterval</key>\n"
250
+ " <dict>\n"
251
+ f" <key>Hour</key>\n <integer>{hour}</integer>\n"
252
+ f" <key>Minute</key>\n <integer>{minute}</integer>\n"
253
+ " </dict>\n"
254
+ " <key>RunAtLoad</key>\n <false/>\n"
255
+ "</dict>\n"
256
+ "</plist>\n"
257
+ )
258
+ if dry_run:
259
+ return plist_path
260
+ plist_path.parent.mkdir(parents=True, exist_ok=True)
261
+ log_dir.mkdir(parents=True, exist_ok=True)
262
+ plist_path.write_text(plist, encoding="utf-8")
263
+ return plist_path
264
+
265
+
266
+ def install_windows_task(
267
+ *,
268
+ home: Optional[Path] = None,
269
+ python_exe: Optional[Path | str] = None,
270
+ repo_root: Optional[Path] = None,
271
+ at: str = "03:30",
272
+ build: bool = True,
273
+ coalesce: bool = False,
274
+ dry_run: bool = False,
275
+ ) -> list[str]:
276
+ """Write a .cmd wrapper and print the schtasks command."""
277
+ hour, minute = _at_parts(at)
278
+ home_dir = _home(home)
279
+ py = _python(python_exe)
280
+ root = Path(repo_root) if repo_root is not None else Path.cwd()
281
+ output_dir = home_dir / ".llmwiki" / "zcode"
282
+ cmd_path = output_dir / "autosync.cmd"
283
+ log_path = output_dir / "autosync.log"
284
+ command = _autosync_command(py, build=build, coalesce=coalesce)
285
+ script = (
286
+ "@echo off\r\n"
287
+ f'cd /d "{_cmd_escape(str(root))}"\r\n'
288
+ f'{_cmd_escape(command)} >> "{_cmd_escape(str(log_path))}" 2>&1\r\n'
289
+ )
290
+ # The task runs the wrapper, not python: the wrapper sets the working
291
+ # directory and appends to the log. Inside the /TR value schtasks
292
+ # wants inner quotes escaped as \" — so a path with spaces
293
+ # (C:\Users\John Doe\...) stays one argument.
294
+ task_command = (
295
+ f'schtasks /Create /F /SC DAILY /ST {hour:02d}:{minute:02d} '
296
+ f'/TN "sessionwiki-zcode-autosync" /TR "\\"{cmd_path}\\""'
297
+ )
298
+ if dry_run:
299
+ return [f"windows: would write {cmd_path}", f"windows: {task_command}"]
300
+ output_dir.mkdir(parents=True, exist_ok=True)
301
+ cmd_path.write_text(script, encoding="utf-8")
302
+ return [f"windows: wrote {cmd_path}", f"windows: run: {task_command}"]
303
+
304
+
305
+ def detect_scheduler() -> str:
306
+ """Best-effort native scheduler for this OS."""
307
+ if sys.platform.startswith("win"):
308
+ return "windows"
309
+ if sys.platform == "darwin":
310
+ return "launchd"
311
+ if sys.platform.startswith("linux") and shutil.which("systemctl"):
312
+ return "systemd"
313
+ return "none"
314
+
315
+
316
+ def install_all(
317
+ *,
318
+ scheduler: str = "auto",
319
+ home: Optional[Path] = None,
320
+ python_exe: Optional[Path | str] = None,
321
+ repo_root: Optional[Path] = None,
322
+ at: str = "03:30",
323
+ build: bool = True,
324
+ coalesce: bool = False,
325
+ hook: bool = True,
326
+ dry_run: bool = False,
327
+ force: bool = False,
328
+ ) -> list[str]:
329
+ """Install the Stop-hook and one native scheduler entry."""
330
+ chosen = detect_scheduler() if scheduler == "auto" else scheduler
331
+ if chosen not in {"systemd", "launchd", "windows", "none"}:
332
+ raise ValueError(f"unknown scheduler: {scheduler!r}")
333
+
334
+ messages: list[str] = []
335
+ if hook:
336
+ messages.extend(
337
+ install_hook(
338
+ home=home,
339
+ python_exe=python_exe,
340
+ repo_root=repo_root,
341
+ build=build,
342
+ coalesce=coalesce,
343
+ dry_run=dry_run,
344
+ force=force,
345
+ )
346
+ )
347
+ if chosen == "systemd":
348
+ messages.extend(
349
+ install_systemd(
350
+ home=home,
351
+ python_exe=python_exe,
352
+ repo_root=repo_root,
353
+ at=at,
354
+ build=build,
355
+ coalesce=coalesce,
356
+ dry_run=dry_run,
357
+ )
358
+ )
359
+ elif chosen == "launchd":
360
+ path = install_launchd(
361
+ home=home,
362
+ python_exe=python_exe,
363
+ repo_root=repo_root,
364
+ at=at,
365
+ build=build,
366
+ coalesce=coalesce,
367
+ dry_run=dry_run,
368
+ )
369
+ verb = "would write" if dry_run else "wrote"
370
+ messages.append(f"launchd: {verb} {path}")
371
+ messages.append(f"launchd: load with: launchctl load {path}")
372
+ elif chosen == "windows":
373
+ messages.extend(
374
+ install_windows_task(
375
+ home=home,
376
+ python_exe=python_exe,
377
+ repo_root=repo_root,
378
+ at=at,
379
+ build=build,
380
+ coalesce=coalesce,
381
+ dry_run=dry_run,
382
+ )
383
+ )
384
+ else:
385
+ messages.append("scheduler: none selected")
386
+ return messages