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,1337 @@
1
+ """Inline JavaScript for the static site viewer (v1.1 · #217).
2
+
3
+ Extracted from ``sessionwiki/build.py`` in the #217 refactor. Byte-identical
4
+ to the pre-refactor constant — verified by ``sessionwiki build`` hash.
5
+
6
+ Vanilla JS, no framework. Handles:
7
+ - Theme toggle (light/dark/system) with localStorage persistence
8
+ - Cmd+K command palette + fuzzy search against search-index.json
9
+ - Keyboard shortcuts (/, g h/p/s, j/k, ?)
10
+ - Copy-as-markdown + copy-code buttons
11
+ - Reading progress bar on long pages
12
+ - Sticky table headers on the sessions index
13
+ - Filter bar on sessions table (project/model/date/text)
14
+ - Mobile bottom nav
15
+ - Hover-to-preview wikilinks
16
+ - Deep-link anchors on headings
17
+ - Related pages panel
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ JS = r"""// sessionwiki viewer — theme + copy + search palette + keyboard shortcuts + progress bar + filter bar
23
+ // Vanilla JS, no framework.
24
+
25
+ // ─── Theme toggle ─────────────────────────────────────────────────────────
26
+ (function () {
27
+ const root = document.documentElement;
28
+ // v0.5: Keep the highlight.js theme in sync with the page theme by
29
+ // swapping which stylesheet is "disabled". Runs on page load and on every
30
+ // toggle. Falls back silently if the tags are absent.
31
+ function syncHljsTheme() {
32
+ const light = document.getElementById("hljs-light");
33
+ const dark = document.getElementById("hljs-dark");
34
+ if (!light || !dark) return;
35
+ let active = root.getAttribute("data-theme");
36
+ if (!active) {
37
+ active = (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light";
38
+ }
39
+ const isDark = active === "dark";
40
+ light.disabled = isDark;
41
+ dark.disabled = !isDark;
42
+ }
43
+ // #ui-h4 (#566): localStorage access can throw in Safari Private Mode,
44
+ // sandboxed iframes, and some embedded browsers. Wrap reads + writes
45
+ // in try/catch so a thrown SecurityError doesn't kill the whole
46
+ // theme + hljs-sync wiring.
47
+ let saved = null;
48
+ try { saved = localStorage.getItem("sessionwiki-theme"); } catch (e) { /* private mode */ }
49
+ if (saved === "dark" || saved === "light") root.setAttribute("data-theme", saved);
50
+ // `system` and the missing-key case both mean "follow OS preference"
51
+ // — leave data-theme unset so the @media (prefers-color-scheme)
52
+ // rules in css.py drive the palette.
53
+ syncHljsTheme();
54
+ // #ui-h6 (#567): keep the page palette in sync if the OS theme
55
+ // changes WHILE we're on `system` mode. Without this listener, a
56
+ // user who toggles their OS dark mode mid-session sees the page
57
+ // stay on whatever it was rendered with.
58
+ if (window.matchMedia) {
59
+ try {
60
+ window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", function () {
61
+ let s = null;
62
+ try { s = localStorage.getItem("sessionwiki-theme"); } catch (e) {}
63
+ if (s !== "dark" && s !== "light") syncHljsTheme();
64
+ });
65
+ } catch (e) { /* old Safari uses addListener */ }
66
+ }
67
+ document.addEventListener("DOMContentLoaded", function () {
68
+ syncHljsTheme();
69
+ const btn = document.getElementById("theme-toggle");
70
+ if (!btn) return;
71
+ // #ui-h8 (#568): aria state mirrors the current cycle position so
72
+ // assistive tech announces what's pinned, not just "pressed".
73
+ // #v1378-review: aria-pressed collapses 3 states (system / dark /
74
+ // light) to 2 (true|false) — both "system" and "light" mapped to
75
+ // "false", so a screen-reader user couldn't tell which state they
76
+ // were in. Switched to a dynamic aria-label describing the
77
+ // current theme + the next-tap action. aria-pressed is also kept
78
+ // for back-compat with anything reading the binary signal.
79
+ function syncAriaState() {
80
+ let stored = null;
81
+ try { stored = localStorage.getItem("sessionwiki-theme"); } catch (e) {}
82
+ const isDark = (root.getAttribute("data-theme") || (
83
+ (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light"
84
+ )) === "dark";
85
+ btn.setAttribute("aria-pressed", isDark ? "true" : "false");
86
+ const labels = {
87
+ dark: "Theme: dark — click for light",
88
+ light: "Theme: light — click for system default",
89
+ };
90
+ const systemLabel = "Theme: follows system — click for dark";
91
+ btn.setAttribute(
92
+ "aria-label",
93
+ labels[stored] || systemLabel,
94
+ );
95
+ }
96
+ const syncAriaPressed = syncAriaState; // alias kept for older call sites
97
+ syncAriaPressed();
98
+ btn.addEventListener("click", function () {
99
+ // #ui-h6 (#567): tri-state toggle. The cycle is:
100
+ // system → dark → light → system → ...
101
+ // `system` means: data-theme attribute removed, palette follows
102
+ // @media (prefers-color-scheme). Pinning a value moves out of
103
+ // system mode; clicking back to system clears the localStorage
104
+ // entry so a fresh tab also follows the OS.
105
+ let stored = null;
106
+ try { stored = localStorage.getItem("sessionwiki-theme"); } catch (e) {}
107
+ let next;
108
+ if (stored !== "dark" && stored !== "light") {
109
+ // Currently following system → pin to dark.
110
+ next = "dark";
111
+ } else if (stored === "dark") {
112
+ next = "light";
113
+ } else {
114
+ // stored === "light" → return to system.
115
+ next = null;
116
+ }
117
+ if (next === null) {
118
+ root.removeAttribute("data-theme");
119
+ try { localStorage.removeItem("sessionwiki-theme"); } catch (e) {}
120
+ } else {
121
+ root.setAttribute("data-theme", next);
122
+ try { localStorage.setItem("sessionwiki-theme", next); } catch (e) {}
123
+ }
124
+ syncHljsTheme();
125
+ syncAriaPressed();
126
+ });
127
+ });
128
+ // Also respond to the mobile bottom nav theme button (bound later in script.js).
129
+ window.__sessionwikiSyncHljsTheme = syncHljsTheme;
130
+ })();
131
+
132
+ // ─── #460: Mobile/tablet hamburger nav drawer ─────────────────────────────
133
+ // Wires the hamburger button to toggle the drawer with proper aria state.
134
+ // ESC closes and returns focus to the hamburger. Click-outside closes.
135
+ // Drawer items are real <a>; tabbing flows naturally. No focus trap needed
136
+ // because the drawer is non-modal — the rest of the page is still
137
+ // interactive when it's open.
138
+ (function () {
139
+ document.addEventListener("DOMContentLoaded", function () {
140
+ const btn = document.getElementById("nav-hamburger");
141
+ const drawer = document.getElementById("nav-drawer");
142
+ if (!btn || !drawer) return;
143
+ function setOpen(open) {
144
+ btn.setAttribute("aria-expanded", open ? "true" : "false");
145
+ // #v1378-review: aria-label was static "Open navigation menu"
146
+ // even when the drawer was already open; screen readers
147
+ // announced the wrong action. Toggle it alongside aria-expanded.
148
+ btn.setAttribute(
149
+ "aria-label",
150
+ open ? "Close navigation menu" : "Open navigation menu",
151
+ );
152
+ if (open) drawer.removeAttribute("hidden");
153
+ else drawer.setAttribute("hidden", "");
154
+ }
155
+ btn.addEventListener("click", function () {
156
+ setOpen(btn.getAttribute("aria-expanded") !== "true");
157
+ });
158
+ document.addEventListener("keydown", function (e) {
159
+ if (e.key === "Escape" && btn.getAttribute("aria-expanded") === "true") {
160
+ setOpen(false);
161
+ btn.focus();
162
+ }
163
+ });
164
+ // Click outside the drawer closes it.
165
+ document.addEventListener("click", function (e) {
166
+ if (btn.getAttribute("aria-expanded") !== "true") return;
167
+ if (drawer.contains(e.target) || btn.contains(e.target)) return;
168
+ setOpen(false);
169
+ });
170
+ // Close after navigating to one of the drawer items so the next page
171
+ // doesn't briefly render with the drawer still open above the fold.
172
+ drawer.querySelectorAll("a").forEach(function (a) {
173
+ a.addEventListener("click", function () { setOpen(false); });
174
+ });
175
+ });
176
+ })();
177
+
178
+ // ─── Reading progress bar ────────────────────────────────────────────────
179
+ (function () {
180
+ const bar = document.getElementById("progress-bar");
181
+ if (!bar) return;
182
+ function update() {
183
+ const h = document.documentElement;
184
+ const scrolled = h.scrollTop || document.body.scrollTop;
185
+ const height = (h.scrollHeight || document.body.scrollHeight) - h.clientHeight;
186
+ const pct = height > 0 ? (scrolled / height) * 100 : 0;
187
+ bar.style.width = Math.min(100, Math.max(0, pct)) + "%";
188
+ }
189
+ window.addEventListener("scroll", update, { passive: true });
190
+ update();
191
+ })();
192
+
193
+ // ─── Reading position persistence (session pages only, localStorage) ─────
194
+ (function () {
195
+ const CAP_KEY = "sessionwiki-scroll-log";
196
+ const MAX_ENTRIES = 30;
197
+ const article = document.querySelector(".content[itemscope]");
198
+ if (!article) return;
199
+ const key = location.pathname;
200
+ let log = {};
201
+ try { log = JSON.parse(localStorage.getItem(CAP_KEY) || "{}") || {}; } catch (e) { log = {}; }
202
+
203
+ function restore() {
204
+ // Restore only if deep into page (5%-95%) and no URL hash override
205
+ if (location.hash || !log[key] || typeof log[key].pct !== "number") return;
206
+ const pct = log[key].pct;
207
+ if (pct <= 0.05 || pct >= 0.95) return;
208
+ const h = document.documentElement;
209
+ const height = h.scrollHeight - h.clientHeight;
210
+ window.scrollTo(0, Math.max(0, height * pct));
211
+ }
212
+ // Restore after `load` so images/fonts are in and scrollHeight is accurate.
213
+ // If the document is already loaded (e.g. script injected late), run now.
214
+ if (document.readyState === "complete") restore();
215
+ else window.addEventListener("load", restore);
216
+
217
+ let timer = null;
218
+ function save() {
219
+ const h = document.documentElement;
220
+ const height = h.scrollHeight - h.clientHeight;
221
+ const pct = height > 0 ? h.scrollTop / height : 0;
222
+ log[key] = { pct: Math.round(pct * 10000) / 10000, t: Date.now() };
223
+ const entries = Object.entries(log);
224
+ if (entries.length > MAX_ENTRIES) {
225
+ entries.sort(function (a, b) { return (b[1].t || 0) - (a[1].t || 0); });
226
+ log = {};
227
+ entries.slice(0, MAX_ENTRIES).forEach(function (e) { log[e[0]] = e[1]; });
228
+ }
229
+ try { localStorage.setItem(CAP_KEY, JSON.stringify(log)); } catch (e) { /* quota exceeded */ }
230
+ }
231
+ window.addEventListener("scroll", function () {
232
+ if (timer) return;
233
+ timer = setTimeout(function () { timer = null; save(); }, 400);
234
+ }, { passive: true });
235
+ })();
236
+
237
+ // ─── TOC sidebar + scroll-spy (session pages only, desktop only) ─────────
238
+ (function () {
239
+ document.addEventListener("DOMContentLoaded", function () {
240
+ const article = document.querySelector(".content[itemscope]");
241
+ if (!article) return;
242
+ const headings = article.querySelectorAll("h2[id], h3[id], h4[id]");
243
+ if (headings.length < 3) return;
244
+ const aside = document.createElement("aside");
245
+ aside.className = "toc-sidebar";
246
+ aside.setAttribute("aria-label", "Page contents");
247
+ const title = document.createElement("div");
248
+ title.className = "toc-title";
249
+ title.textContent = "On this page";
250
+ aside.appendChild(title);
251
+ const ul = document.createElement("ul");
252
+ const linkMap = new Map();
253
+ headings.forEach(function (h) {
254
+ const li = document.createElement("li");
255
+ li.className = "toc-" + h.tagName.toLowerCase();
256
+ const a = document.createElement("a");
257
+ a.href = "#" + h.id;
258
+ a.className = "toc-link";
259
+ // The `toc` markdown extension appends a permalink anchor; strip its text.
260
+ const clean = (h.textContent || "").replace(/\u00b6\s*$/, "").trim();
261
+ a.textContent = clean;
262
+ a.title = clean;
263
+ li.appendChild(a);
264
+ ul.appendChild(li);
265
+ linkMap.set(h.id, a);
266
+ });
267
+ aside.appendChild(ul);
268
+ document.body.appendChild(aside);
269
+ // Scroll-spy via IntersectionObserver
270
+ if (!("IntersectionObserver" in window)) return;
271
+ const visible = new Set();
272
+ function clearActive() { linkMap.forEach(function (a) { a.classList.remove("active"); }); }
273
+ function setActive(id) {
274
+ const link = linkMap.get(id);
275
+ if (link) link.classList.add("active");
276
+ }
277
+ function applySpy() {
278
+ clearActive();
279
+ // Near-bottom fallback: the rootMargin creates a dead zone at the bottom
280
+ // of the page, so the last heading would otherwise never activate.
281
+ const doc = document.documentElement;
282
+ const atBottom = (window.innerHeight + window.scrollY) >= (doc.scrollHeight - 24);
283
+ if (atBottom) {
284
+ setActive(headings[headings.length - 1].id);
285
+ return;
286
+ }
287
+ if (visible.size > 0) {
288
+ for (const h of headings) {
289
+ if (visible.has(h.id)) { setActive(h.id); return; }
290
+ }
291
+ }
292
+ }
293
+ const obs = new IntersectionObserver(function (entries) {
294
+ entries.forEach(function (e) {
295
+ if (e.isIntersecting) visible.add(e.target.id);
296
+ else visible.delete(e.target.id);
297
+ });
298
+ applySpy();
299
+ }, { rootMargin: "-80px 0px -70% 0px", threshold: 0 });
300
+ headings.forEach(function (h) { obs.observe(h); });
301
+ // Scroll listener handles the bottom-of-page edge case.
302
+ window.addEventListener("scroll", applySpy, { passive: true });
303
+ });
304
+ })();
305
+
306
+ // ─── Mobile bottom nav active-state + button wiring ──────────────────────
307
+ (function () {
308
+ document.addEventListener("DOMContentLoaded", function () {
309
+ // Mark the active link based on current path
310
+ const path = location.pathname;
311
+ document.querySelectorAll(".mobile-bottom-nav .mbn-link[data-page]").forEach(function (a) {
312
+ const page = a.getAttribute("data-page");
313
+ if (page === "home" && (path.endsWith("/") || path.endsWith("/index.html"))) a.classList.add("active");
314
+ else if (page === "projects" && path.indexOf("/projects/") !== -1) a.classList.add("active");
315
+ else if (page === "sessions" && path.indexOf("/sessions/") !== -1) a.classList.add("active");
316
+ });
317
+ // Wire the search button — delegate to the header palette trigger so that
318
+ // the existing openPalette() runs (clears input, loads index, renders).
319
+ const searchBtn = document.getElementById("mbn-search");
320
+ if (searchBtn) {
321
+ searchBtn.addEventListener("click", function () {
322
+ const trigger = document.getElementById("open-palette");
323
+ if (trigger) trigger.click();
324
+ });
325
+ }
326
+ // Wire the theme button to toggle
327
+ const themeBtn = document.getElementById("mbn-theme");
328
+ if (themeBtn) {
329
+ // #v1378-review: same dynamic aria-label treatment as the
330
+ // desktop button — aria-pressed alone collapses the tri-state
331
+ // (system / dark / light) into a binary signal. The label
332
+ // describes the current state plus the next-tap action.
333
+ function _mbnSyncPressed() {
334
+ let stored = null;
335
+ try { stored = localStorage.getItem("sessionwiki-theme"); } catch (e) { /* private mode */ }
336
+ const isDark = (document.documentElement.getAttribute("data-theme") || (
337
+ (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light"
338
+ )) === "dark";
339
+ themeBtn.setAttribute("aria-pressed", isDark ? "true" : "false");
340
+ const labels = {
341
+ dark: "Theme: dark — tap for light",
342
+ light: "Theme: light — tap for system default",
343
+ };
344
+ const systemLabel = "Theme: follows system — tap for dark";
345
+ themeBtn.setAttribute("aria-label", labels[stored] || systemLabel);
346
+ }
347
+ _mbnSyncPressed();
348
+ themeBtn.addEventListener("click", function () {
349
+ // Post-final-review: mirror the desktop tri-state cycle
350
+ // (system → dark → light → system) instead of a binary
351
+ // dark/light flip. The old binary path would silently move
352
+ // the user out of "system" mode on the first tap and there
353
+ // was no way back from the mobile menu — desktop and mobile
354
+ // diverged behaviorally. Cycle source-of-truth is desktop.
355
+ const root = document.documentElement;
356
+ let stored = null;
357
+ try { stored = localStorage.getItem("sessionwiki-theme"); } catch (e) { /* private mode */ }
358
+ let next;
359
+ if (stored !== "dark" && stored !== "light") {
360
+ next = "dark";
361
+ } else if (stored === "dark") {
362
+ next = "light";
363
+ } else {
364
+ next = null; // back to system
365
+ }
366
+ if (next === null) {
367
+ root.removeAttribute("data-theme");
368
+ try { localStorage.removeItem("sessionwiki-theme"); } catch (e) { /* private mode */ }
369
+ } else {
370
+ root.setAttribute("data-theme", next);
371
+ try { localStorage.setItem("sessionwiki-theme", next); } catch (e) { /* private mode */ }
372
+ }
373
+ if (window.__sessionwikiSyncHljsTheme) window.__sessionwikiSyncHljsTheme();
374
+ _mbnSyncPressed();
375
+ });
376
+ }
377
+ });
378
+ })();
379
+
380
+ // ─── Copy-as-markdown (inline handler) ───────────────────────────────────
381
+ function copyMarkdown(btn) {
382
+ const ta = btn.parentElement.querySelector(".md-source");
383
+ if (!ta) return;
384
+ const text = ta.value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
385
+ const finish = function (ok) {
386
+ btn.textContent = ok ? "Copied!" : "Failed";
387
+ btn.classList.add("copied");
388
+ setTimeout(function () { btn.textContent = "Copy as markdown"; btn.classList.remove("copied"); }, 1800);
389
+ };
390
+ if (navigator.clipboard && navigator.clipboard.writeText) {
391
+ navigator.clipboard.writeText(text).then(function () { finish(true); }, function () { finish(false); });
392
+ } else {
393
+ const tmp = document.createElement("textarea");
394
+ tmp.value = text; tmp.style.position = "fixed"; tmp.style.left = "-9999px";
395
+ document.body.appendChild(tmp); tmp.select();
396
+ try { document.execCommand("copy"); finish(true); } catch (e) { finish(false); }
397
+ document.body.removeChild(tmp);
398
+ }
399
+ }
400
+
401
+ // ─── Copy-code buttons on every <pre> ────────────────────────────────────
402
+ document.addEventListener("DOMContentLoaded", function () {
403
+ document.querySelectorAll(".content pre").forEach(function (pre) {
404
+ if (pre.parentElement && pre.parentElement.classList.contains("code-wrap")) return;
405
+ const wrap = document.createElement("div"); wrap.className = "code-wrap";
406
+ pre.parentNode.insertBefore(wrap, pre);
407
+ wrap.appendChild(pre);
408
+ const btn = document.createElement("button");
409
+ btn.className = "copy-code-btn"; btn.type = "button"; btn.textContent = "Copy";
410
+ btn.addEventListener("click", function () {
411
+ const code = pre.querySelector("code");
412
+ const text = code ? code.innerText : pre.innerText;
413
+ const finish = function (ok) {
414
+ btn.textContent = ok ? "Copied!" : "Failed"; btn.classList.add("copied");
415
+ setTimeout(function () { btn.textContent = "Copy"; btn.classList.remove("copied"); }, 1500);
416
+ };
417
+ if (navigator.clipboard && navigator.clipboard.writeText) {
418
+ navigator.clipboard.writeText(text).then(function () { finish(true); }, function () { finish(false); });
419
+ } else {
420
+ const tmp = document.createElement("textarea");
421
+ tmp.value = text; tmp.style.position = "fixed"; tmp.style.left = "-9999px";
422
+ document.body.appendChild(tmp); tmp.select();
423
+ try { document.execCommand("copy"); finish(true); } catch (e) { finish(false); }
424
+ document.body.removeChild(tmp);
425
+ }
426
+ });
427
+ wrap.appendChild(btn);
428
+ });
429
+ });
430
+
431
+ // ─── Auto-collapse long tool results into <details> ──────────────────────
432
+ // #476: the summary used to read "Tool results (544 chars) — click to
433
+ // expand" — pure char-count, no signal. Now extracts the first non-
434
+ // blank line as a preview, detects ok/error from a leading `(ok)` or
435
+ // `(ERROR)` marker the markdown emit puts in, and counts result lines.
436
+ // Renders as a richer card: `[ok] preview text · 412 lines · click to
437
+ // expand`. Keeps the same <details>/<summary> structure so existing CSS
438
+ // + a11y plumbing continues to work.
439
+ document.addEventListener("DOMContentLoaded", function () {
440
+ const markers = document.querySelectorAll(".content p strong");
441
+ markers.forEach(function (s) {
442
+ const text = (s.textContent || "").trim();
443
+ if (text !== "Tool results:") return;
444
+ const p = s.closest("p");
445
+ if (!p) return;
446
+ let next = p.nextElementSibling;
447
+ if (!next) return;
448
+ const combinedText = (next.innerText || "").trim();
449
+ if (combinedText.length < 500) return;
450
+
451
+ // Outcome detection: the markdown emit prepends "→ result (ok):" or
452
+ // "→ result (ERROR):" to each block. First match wins.
453
+ const outcome = /\(ERROR\)/.test(combinedText) ? "error" : "ok";
454
+ // Preview: first non-blank line, stripped of "→ result (ok):" prefix
455
+ // and arrow indent. Truncate at 80 chars on a word boundary.
456
+ const lines = combinedText.split(/\r?\n/);
457
+ let preview = "";
458
+ for (const raw of lines) {
459
+ const line = raw.replace(/^\s*→\s*result\s*\((?:ok|ERROR)\):\s*/, "").trim();
460
+ if (line) { preview = line; break; }
461
+ }
462
+ if (preview.length > 80) {
463
+ const cut = preview.lastIndexOf(" ", 77);
464
+ preview = (cut > 40 ? preview.slice(0, cut) : preview.slice(0, 77)) + "...";
465
+ }
466
+ const lineCount = lines.length;
467
+
468
+ // Wrap next element in a <details>.
469
+ const det = document.createElement("details");
470
+ det.className = "collapsible-result outcome-" + outcome;
471
+ const sum = document.createElement("summary");
472
+ // Build the summary as DOM nodes (not innerHTML) so a malicious
473
+ // preview can't inject markup.
474
+ const badge = document.createElement("span");
475
+ badge.className = "tool-result-badge tool-result-" + outcome;
476
+ badge.textContent = outcome === "error" ? "ERROR" : "ok";
477
+ sum.appendChild(badge);
478
+ if (preview) {
479
+ const previewEl = document.createElement("span");
480
+ previewEl.className = "tool-result-preview";
481
+ previewEl.textContent = " " + preview;
482
+ sum.appendChild(previewEl);
483
+ }
484
+ const meta = document.createElement("span");
485
+ meta.className = "tool-result-meta muted";
486
+ meta.textContent = " · " + lineCount + (lineCount === 1 ? " line" : " lines") +
487
+ " · " + combinedText.length + " chars";
488
+ sum.appendChild(meta);
489
+ det.appendChild(sum);
490
+ next.parentNode.insertBefore(det, next);
491
+ det.appendChild(next);
492
+ });
493
+ });
494
+
495
+ // ─── Command palette (Cmd+K) + search index loader ─────────────────────
496
+ (function () {
497
+ let idx = null;
498
+ let idxPromise = null;
499
+ let metaEntries = null; // project + page entries (loaded first, fast)
500
+ let activeIdx = 0;
501
+ let currentResults = [];
502
+
503
+ // Lazy-chunked loader (#47): loads the small meta index first (projects +
504
+ // static pages), then fetches per-project session chunks in parallel on
505
+ // first demand. Backwards-compatible with the old flat-array format.
506
+ function loadIndex() {
507
+ if (idx) return Promise.resolve(idx);
508
+ if (idxPromise) return idxPromise;
509
+ const url = window.LLMWIKI_INDEX_URL || "search-index.json";
510
+ const base = url.substring(0, url.lastIndexOf("/") + 1);
511
+ idxPromise = fetch(url)
512
+ .then(function (r) { return r.ok ? r.json() : []; })
513
+ .then(function (data) {
514
+ // Old format: flat array → return as-is
515
+ if (Array.isArray(data)) { idx = data; return idx; }
516
+ // New format: {entries: [...], _chunks: ["search-chunks/foo.json", ...]}
517
+ metaEntries = data.entries || [];
518
+ var chunkUrls = data._chunks || [];
519
+ if (!chunkUrls.length) { idx = metaEntries; return idx; }
520
+ return Promise.all(chunkUrls.map(function (cu) {
521
+ return fetch(base + cu)
522
+ .then(function (r) { return r.ok ? r.json() : []; })
523
+ .catch(function () { return []; });
524
+ })).then(function (chunks) {
525
+ idx = metaEntries.slice();
526
+ chunks.forEach(function (c) {
527
+ if (Array.isArray(c)) { for (var i = 0; i < c.length; i++) idx.push(c[i]); }
528
+ });
529
+ return idx;
530
+ });
531
+ })
532
+ .catch(function () { idx = []; return idx; });
533
+ return idxPromise;
534
+ }
535
+ // Expose the shared loader so wikilink-preview + related-pages can reuse it
536
+ window.__sessionwikiLoadIndex = loadIndex;
537
+
538
+ // Return the meta entries (projects + pages) synchronously if available,
539
+ // otherwise trigger a full load. Used for instant palette rendering before
540
+ // session chunks arrive.
541
+ function getMetaSync() { return metaEntries || idx || []; }
542
+
543
+ function score(entry, query) {
544
+ if (!query) return 0;
545
+ const q = query.toLowerCase();
546
+ const title = (entry.title || "").toLowerCase();
547
+ const project = (entry.project || "").toLowerCase();
548
+ const body = (entry.body || "").toLowerCase();
549
+ let s = 0;
550
+ if (title === q) s += 100;
551
+ else if (title.indexOf(q) === 0) s += 60;
552
+ else if (title.indexOf(q) !== -1) s += 40;
553
+ if (project.indexOf(q) !== -1) s += 20;
554
+ if (body.indexOf(q) !== -1) s += 10;
555
+ // Token match
556
+ const tokens = q.split(/\s+/).filter(Boolean);
557
+ let allMatch = true;
558
+ tokens.forEach(function (t) {
559
+ if (title.indexOf(t) === -1 && project.indexOf(t) === -1 && body.indexOf(t) === -1) allMatch = false;
560
+ });
561
+ if (allMatch && tokens.length > 1) s += 30;
562
+ return s;
563
+ }
564
+
565
+ // v0.8 (#97): Dataview-style structured queries. Users can type
566
+ // key:value pairs alongside free text to filter by metadata:
567
+ // type:session project:llm-wiki model:claude date:>2026-03-01 sort:date rust
568
+ // Supported keys: type, project, model, date (range with > / <), tags, sort
569
+ // Anything that doesn't match key:value is treated as free-text fuzzy search.
570
+ function parseStructuredQuery(raw) {
571
+ var filters = {};
572
+ var freeText = [];
573
+ var tokens = raw.split(/\s+/).filter(Boolean);
574
+ tokens.forEach(function (t) {
575
+ var m = t.match(/^(type|project|model|date|tags|sort):(.+)$/i);
576
+ if (m) { filters[m[1].toLowerCase()] = m[2]; }
577
+ else { freeText.push(t); }
578
+ });
579
+ return { filters: filters, freeText: freeText.join(" ") };
580
+ }
581
+
582
+ function matchesFilters(entry, filters) {
583
+ if (filters.type && (entry.type || "").toLowerCase() !== filters.type.toLowerCase()) return false;
584
+ if (filters.project && (entry.project || "").toLowerCase().indexOf(filters.project.toLowerCase()) === -1) return false;
585
+ if (filters.model && (entry.model || "").toLowerCase().indexOf(filters.model.toLowerCase()) === -1) return false;
586
+ if (filters.tags) {
587
+ var want = filters.tags.toLowerCase();
588
+ var entryBody = ((entry.body || "") + " " + (entry.title || "")).toLowerCase();
589
+ if (entryBody.indexOf(want) === -1) return false;
590
+ }
591
+ if (filters.date) {
592
+ var d = entry.date || "";
593
+ var op = filters.date.charAt(0);
594
+ if (op === ">" && d <= filters.date.substring(1)) return false;
595
+ if (op === "<" && d >= filters.date.substring(1)) return false;
596
+ if (op !== ">" && op !== "<" && d.indexOf(filters.date) === -1) return false;
597
+ }
598
+ return true;
599
+ }
600
+
601
+ function search(query) {
602
+ if (!idx) return [];
603
+ if (!query) return idx.slice(0, 10);
604
+ var parsed = parseStructuredQuery(query);
605
+ var filtered = idx;
606
+ if (Object.keys(parsed.filters).length > 0) {
607
+ filtered = idx.filter(function (e) { return matchesFilters(e, parsed.filters); });
608
+ }
609
+ var sortKey = parsed.filters.sort;
610
+ if (sortKey === "date") {
611
+ return filtered
612
+ .slice()
613
+ .sort(function (a, b) { return (b.date || "").localeCompare(a.date || ""); })
614
+ .slice(0, 20);
615
+ }
616
+ if (!parsed.freeText) return filtered.slice(0, 20);
617
+ return filtered
618
+ .map(function (e) { return { entry: e, score: score(e, parsed.freeText) }; })
619
+ .filter(function (r) { return r.score > 0; })
620
+ .sort(function (a, b) { return b.score - a.score; })
621
+ .slice(0, 15)
622
+ .map(function (r) { return r.entry; });
623
+ }
624
+
625
+ function renderResults(results) {
626
+ const ul = document.getElementById("palette-results");
627
+ if (!ul) return;
628
+ currentResults = results;
629
+ activeIdx = 0;
630
+ ul.innerHTML = results.map(function (r, i) {
631
+ const meta = [r.project, r.date, r.model].filter(Boolean).join(" · ");
632
+ return '<li data-i="' + i + '" class="' + (i === 0 ? 'active' : '') + '">' +
633
+ '<span class="result-type">' + (r.type || 'page') + '</span>' +
634
+ '<span class="result-title">' + escapeHtml(r.title) + '</span>' +
635
+ (meta ? '<div class="result-meta">' + escapeHtml(meta) + '</div>' : '') +
636
+ '</li>';
637
+ }).join("");
638
+ ul.querySelectorAll("li").forEach(function (li) {
639
+ li.addEventListener("click", function () {
640
+ const i = parseInt(li.getAttribute("data-i"));
641
+ openResult(i);
642
+ });
643
+ });
644
+ }
645
+
646
+ function escapeHtml(s) {
647
+ return String(s || "").replace(/[&<>"']/g, function (c) {
648
+ return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
649
+ });
650
+ }
651
+
652
+ function openResult(i) {
653
+ if (!currentResults[i]) return;
654
+ const r = currentResults[i];
655
+ // #277: slash commands don't have URLs — copy the command text
656
+ // to the clipboard + flash a hint instead of navigating.
657
+ if (r.type === "slash" || !r.url) {
658
+ try { navigator.clipboard && navigator.clipboard.writeText(r.title); } catch (e) {}
659
+ const input = document.getElementById("palette-input");
660
+ if (input) { input.value = r.title; input.placeholder = "copied — paste inside Claude Code"; }
661
+ return;
662
+ }
663
+ const pageUrl = window.LLMWIKI_INDEX_URL || "";
664
+ // Compute base dir from current page URL
665
+ const pathPrefix = pageUrl.substring(0, pageUrl.lastIndexOf("/") + 1) || "";
666
+ window.location.href = pathPrefix + r.url;
667
+ }
668
+
669
+ // #478, #479: dialog focus + inert helpers shared by palette + help.
670
+ // Stash who opened the dialog so we can restore focus on close.
671
+ // Apply `inert` to every direct child of <body> EXCEPT the dialog
672
+ // itself so AT users can't tab into the page chrome behind the
673
+ // backdrop (the previous aria-hidden gate left siblings reachable).
674
+ //
675
+ // Post-review: stash is a Map keyed by dialog.id so opening a second
676
+ // dialog while the first is still open doesn't clobber the first
677
+ // dialog's restoration target. Equally, inert is only removed from
678
+ // siblings that are NOT themselves currently-open dialogs, so closing
679
+ // help while palette is still open doesn't strip the palette's inert
680
+ // wrapping of the rest of the chrome.
681
+ var __dialogLastFocus = new Map();
682
+ function __getInertSiblings(dialog) {
683
+ return Array.prototype.filter.call(
684
+ document.body.children,
685
+ function (el) { return el !== dialog; }
686
+ );
687
+ }
688
+ function __isOpenDialog(el) {
689
+ return el && el.classList && el.classList.contains("open") &&
690
+ (el.id === "palette" || el.id === "help-dialog");
691
+ }
692
+ function __isDialogOpen(dialog) {
693
+ return dialog && dialog.classList.contains("open");
694
+ }
695
+ function __getFocusable(container) {
696
+ return Array.prototype.filter.call(
697
+ container.querySelectorAll(
698
+ 'a[href], button:not([disabled]), input:not([disabled]), ' +
699
+ 'select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
700
+ ),
701
+ function (el) { return !el.hasAttribute("disabled") && el.offsetParent !== null; }
702
+ );
703
+ }
704
+ function __syncTriggerAriaExpanded(dialog, value) {
705
+ // #ui-h8 (#568): trigger button's aria-expanded must mirror the
706
+ // dialog's open/closed state so AT users hear the right thing
707
+ // when they re-focus the trigger.
708
+ if (!dialog || !dialog.id) return;
709
+ const trigger = document.querySelector('[aria-controls="' + dialog.id + '"]');
710
+ if (trigger) trigger.setAttribute("aria-expanded", value ? "true" : "false");
711
+ }
712
+ function __openDialog(dialog, firstFocus) {
713
+ if (!dialog || dialog.classList.contains("open")) return;
714
+ if (dialog.id) __dialogLastFocus.set(dialog.id, document.activeElement);
715
+ dialog.classList.add("open");
716
+ __syncTriggerAriaExpanded(dialog, true);
717
+ __getInertSiblings(dialog).forEach(function (s) { s.setAttribute("inert", ""); });
718
+ if (firstFocus && firstFocus.focus) firstFocus.focus();
719
+ }
720
+ function __closeDialog(dialog) {
721
+ if (!dialog || !dialog.classList.contains("open")) return;
722
+ dialog.classList.remove("open");
723
+ __syncTriggerAriaExpanded(dialog, false);
724
+ // Only strip inert from siblings that are NOT themselves an open
725
+ // dialog — otherwise closing the help-dialog while palette is open
726
+ // re-exposes the palette's inert chrome guard.
727
+ __getInertSiblings(dialog).forEach(function (s) {
728
+ if (!__isOpenDialog(s)) s.removeAttribute("inert");
729
+ });
730
+ var lf = dialog.id ? __dialogLastFocus.get(dialog.id) : null;
731
+ if (lf && lf.focus) {
732
+ try { lf.focus(); } catch (e) { /* trigger gone */ }
733
+ }
734
+ if (dialog.id) __dialogLastFocus.delete(dialog.id);
735
+ }
736
+ // Trap Tab + Shift+Tab inside `dialog` so focus can't escape into
737
+ // the inert page chrome and become visually invisible.
738
+ function __trapTab(dialog) {
739
+ return function (e) {
740
+ if (e.key !== "Tab" || !__isDialogOpen(dialog)) return;
741
+ const focusable = __getFocusable(dialog);
742
+ if (focusable.length === 0) { e.preventDefault(); return; }
743
+ const first = focusable[0];
744
+ const last = focusable[focusable.length - 1];
745
+ if (e.shiftKey && document.activeElement === first) {
746
+ e.preventDefault(); last.focus();
747
+ } else if (!e.shiftKey && document.activeElement === last) {
748
+ e.preventDefault(); first.focus();
749
+ }
750
+ };
751
+ }
752
+
753
+ function openPalette() {
754
+ const p = document.getElementById("palette");
755
+ if (!p) return;
756
+ const input = document.getElementById("palette-input");
757
+ if (input) { input.value = ""; }
758
+ __openDialog(p, input);
759
+ // Show meta entries immediately while chunks load
760
+ var meta = getMetaSync();
761
+ if (meta.length && !idx) renderResults(meta.slice(0, 10));
762
+ loadIndex().then(function () { renderResults(search(input ? input.value : "")); });
763
+ }
764
+
765
+ function closePalette() {
766
+ const p = document.getElementById("palette");
767
+ __closeDialog(p);
768
+ }
769
+
770
+ function openHelp() {
771
+ const d = document.getElementById("help-dialog");
772
+ if (!d) return;
773
+ const closeBtn = document.getElementById("help-close");
774
+ __openDialog(d, closeBtn);
775
+ }
776
+ function closeHelp() {
777
+ const d = document.getElementById("help-dialog");
778
+ __closeDialog(d);
779
+ }
780
+
781
+ document.addEventListener("DOMContentLoaded", function () {
782
+ // Wire up buttons
783
+ const openBtn = document.getElementById("open-palette");
784
+ if (openBtn) openBtn.addEventListener("click", openPalette);
785
+
786
+ const backdrop = document.getElementById("palette-backdrop");
787
+ if (backdrop) backdrop.addEventListener("click", closePalette);
788
+
789
+ const input = document.getElementById("palette-input");
790
+ if (input) {
791
+ input.addEventListener("input", function () { renderResults(search(input.value)); });
792
+ input.addEventListener("keydown", function (e) {
793
+ const items = document.querySelectorAll("#palette-results li");
794
+ if (e.key === "ArrowDown") { e.preventDefault(); activeIdx = Math.min(items.length - 1, activeIdx + 1); updateActive(); }
795
+ else if (e.key === "ArrowUp") { e.preventDefault(); activeIdx = Math.max(0, activeIdx - 1); updateActive(); }
796
+ else if (e.key === "Enter") { e.preventDefault(); openResult(activeIdx); }
797
+ });
798
+ }
799
+
800
+ const helpBackdrop = document.getElementById("help-backdrop");
801
+ if (helpBackdrop) helpBackdrop.addEventListener("click", closeHelp);
802
+ const helpClose = document.getElementById("help-close");
803
+ if (helpClose) helpClose.addEventListener("click", closeHelp);
804
+
805
+ // #479: Tab focus traps. Listening on document so the handler fires
806
+ // even when the focused element is a backdrop / non-focusable.
807
+ const paletteEl = document.getElementById("palette");
808
+ if (paletteEl) document.addEventListener("keydown", __trapTab(paletteEl));
809
+ const helpEl = document.getElementById("help-dialog");
810
+ if (helpEl) document.addEventListener("keydown", __trapTab(helpEl));
811
+ });
812
+
813
+ function updateActive() {
814
+ const items = document.querySelectorAll("#palette-results li");
815
+ items.forEach(function (li, i) { li.classList.toggle("active", i === activeIdx); });
816
+ const active = items[activeIdx];
817
+ if (active) active.scrollIntoView({ block: "nearest" });
818
+ }
819
+
820
+ // ─── Keyboard shortcuts ─────────────────────────────────────────────────
821
+ let gPressed = false;
822
+ let gPressedTimer = null;
823
+ document.addEventListener("keydown", function (e) {
824
+ const inInput = e.target && (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA" || e.target.tagName === "SELECT");
825
+
826
+ // Cmd/Ctrl+K opens palette everywhere
827
+ if ((e.metaKey || e.ctrlKey) && e.key === "k") {
828
+ e.preventDefault();
829
+ openPalette();
830
+ return;
831
+ }
832
+ // Esc closes palette / help / clears focus
833
+ if (e.key === "Escape") {
834
+ const p = document.getElementById("palette");
835
+ const h = document.getElementById("help-dialog");
836
+ // #478: state check now reads the .open class (was aria-hidden).
837
+ if (p && p.classList.contains("open")) { closePalette(); return; }
838
+ if (h && h.classList.contains("open")) { closeHelp(); return; }
839
+ if (inInput) { e.target.blur(); return; }
840
+ }
841
+
842
+ // Shortcuts only work when not typing in an input
843
+ if (inInput) return;
844
+
845
+ if (e.key === "/") { e.preventDefault(); openPalette(); return; }
846
+ if (e.key === "?") { e.preventDefault(); openHelp(); return; }
847
+
848
+ // g-prefix shortcuts
849
+ if (e.key === "g" && !gPressed) {
850
+ gPressed = true;
851
+ gPressedTimer = setTimeout(function () { gPressed = false; }, 1000);
852
+ return;
853
+ }
854
+ if (gPressed) {
855
+ gPressed = false;
856
+ if (gPressedTimer) clearTimeout(gPressedTimer);
857
+ const rel = window.LLMWIKI_INDEX_URL || "";
858
+ const base = rel.substring(0, rel.lastIndexOf("/") + 1);
859
+ if (e.key === "h") { window.location.href = base + "index.html"; return; }
860
+ if (e.key === "p") { window.location.href = base + "projects/index.html"; return; }
861
+ if (e.key === "s") { window.location.href = base + "sessions/index.html"; return; }
862
+ }
863
+
864
+ // j/k on sessions table
865
+ const tbody = document.getElementById("sessions-tbody");
866
+ if (tbody && (e.key === "j" || e.key === "k")) {
867
+ e.preventDefault();
868
+ const visibleRows = Array.from(tbody.querySelectorAll("tr")).filter(function (r) { return !r.hidden; });
869
+ if (!visibleRows.length) return;
870
+ let cur = visibleRows.findIndex(function (r) { return r.classList.contains("selected"); });
871
+ if (cur === -1) cur = 0;
872
+ else cur = e.key === "j" ? Math.min(visibleRows.length - 1, cur + 1) : Math.max(0, cur - 1);
873
+ visibleRows.forEach(function (r) { r.classList.remove("selected"); });
874
+ visibleRows[cur].classList.add("selected");
875
+ visibleRows[cur].scrollIntoView({ block: "nearest" });
876
+ // Enter on selected row navigates
877
+ }
878
+ if (e.key === "Enter" && tbody) {
879
+ const sel = tbody.querySelector("tr.selected a");
880
+ if (sel) { window.location.href = sel.href; }
881
+ }
882
+ });
883
+ })();
884
+
885
+ // ─── Sessions table filter bar ────────────────────────────────────────────
886
+ document.addEventListener("DOMContentLoaded", function () {
887
+ const tbody = document.getElementById("sessions-tbody");
888
+ if (!tbody) return;
889
+ const fProject = document.getElementById("filter-project");
890
+ const fModel = document.getElementById("filter-model");
891
+ const fFrom = document.getElementById("filter-date-from");
892
+ const fTo = document.getElementById("filter-date-to");
893
+ const fText = document.getElementById("filter-text");
894
+ const fClear = document.getElementById("filter-clear");
895
+ const fCount = document.getElementById("filter-count");
896
+
897
+ // #ui-m1 (#572): persist filter selections to sessionStorage so a
898
+ // navigation away + back doesn't lose the user's filter state.
899
+ // sessionStorage (not localStorage) is the right scope: it survives
900
+ // back/forward but clears on tab close, matching user expectations
901
+ // for a transient filter view.
902
+ const STORAGE_KEY = "sessionwiki-sessions-filters";
903
+ function _readSaved() {
904
+ try {
905
+ const raw = sessionStorage.getItem(STORAGE_KEY);
906
+ return raw ? JSON.parse(raw) : null;
907
+ } catch (e) { return null; }
908
+ }
909
+ function _writeSaved() {
910
+ try {
911
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify({
912
+ p: fProject ? fProject.value : "",
913
+ m: fModel ? fModel.value : "",
914
+ from: fFrom ? fFrom.value : "",
915
+ to: fTo ? fTo.value : "",
916
+ txt: fText ? fText.value : "",
917
+ }));
918
+ } catch (e) { /* private mode */ }
919
+ }
920
+ // Restore on page load.
921
+ const saved = _readSaved();
922
+ if (saved) {
923
+ if (fProject && saved.p) fProject.value = saved.p;
924
+ if (fModel && saved.m) fModel.value = saved.m;
925
+ if (fFrom && saved.from) fFrom.value = saved.from;
926
+ if (fTo && saved.to) fTo.value = saved.to;
927
+ if (fText && saved.txt) fText.value = saved.txt;
928
+ }
929
+
930
+ function apply() {
931
+ const p = fProject ? fProject.value : "";
932
+ const m = fModel ? fModel.value : "";
933
+ const from = fFrom ? fFrom.value : "";
934
+ const to = fTo ? fTo.value : "";
935
+ const txt = fText ? fText.value.toLowerCase() : "";
936
+ let shown = 0;
937
+ Array.from(tbody.querySelectorAll("tr")).forEach(function (r) {
938
+ const rp = r.getAttribute("data-project") || "";
939
+ const rm = r.getAttribute("data-model") || "";
940
+ const rd = r.getAttribute("data-date") || "";
941
+ const rs = (r.getAttribute("data-slug") || "").toLowerCase();
942
+ let show = true;
943
+ if (p && rp !== p) show = false;
944
+ if (m && rm !== m) show = false;
945
+ if (from && rd < from) show = false;
946
+ if (to && rd > to) show = false;
947
+ if (txt && rs.indexOf(txt) === -1) show = false;
948
+ r.hidden = !show;
949
+ if (show) shown++;
950
+ });
951
+ if (fCount) fCount.textContent = shown + " shown";
952
+ _writeSaved();
953
+ }
954
+
955
+ [fProject, fModel, fFrom, fTo, fText].forEach(function (el) {
956
+ if (el) el.addEventListener("input", apply);
957
+ });
958
+ if (fClear) fClear.addEventListener("click", function () {
959
+ if (fProject) fProject.value = "";
960
+ if (fModel) fModel.value = "";
961
+ if (fFrom) fFrom.value = "";
962
+ if (fTo) fTo.value = "";
963
+ if (fText) fText.value = "";
964
+ try { sessionStorage.removeItem(STORAGE_KEY); } catch (e) {}
965
+ apply();
966
+ });
967
+ apply();
968
+ });
969
+
970
+ // ─── Hover-to-preview wikilinks ───────────────────────────────────────────
971
+ // When the user hovers over a wikilink (an <a> whose text starts with "[["
972
+ // or whose href is a wiki page), fetch the target's first ~300 chars and
973
+ // show a floating preview card. Uses the client-side search index.
974
+ (function () {
975
+ let idx = null;
976
+ let previewEl = null;
977
+ let hideTimer = null;
978
+
979
+ function getPreviewEl() {
980
+ if (previewEl) return previewEl;
981
+ previewEl = document.createElement("div");
982
+ previewEl.className = "wikilink-preview";
983
+ previewEl.setAttribute("hidden", "");
984
+ previewEl.innerHTML = '<div class="wl-title"></div><div class="wl-body"></div>';
985
+ document.body.appendChild(previewEl);
986
+ previewEl.addEventListener("mouseenter", function () {
987
+ if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
988
+ });
989
+ previewEl.addEventListener("mouseleave", function () {
990
+ hidePreview();
991
+ });
992
+ return previewEl;
993
+ }
994
+
995
+ function loadIndex() {
996
+ if (idx) return Promise.resolve(idx);
997
+ // Reuse the shared chunked loader from the palette IIFE (#47)
998
+ if (window.__sessionwikiLoadIndex) {
999
+ return window.__sessionwikiLoadIndex().then(function (data) { idx = data; return idx; });
1000
+ }
1001
+ var url = window.LLMWIKI_INDEX_URL || "search-index.json";
1002
+ return fetch(url)
1003
+ .then(function (r) { return r.ok ? r.json() : []; })
1004
+ .then(function (data) {
1005
+ idx = Array.isArray(data) ? data : (data.entries || []);
1006
+ return idx;
1007
+ })
1008
+ .catch(function () { idx = []; return idx; });
1009
+ }
1010
+
1011
+ function findEntry(keyOrText) {
1012
+ if (!idx) return null;
1013
+ const needle = (keyOrText || "").toLowerCase().trim();
1014
+ if (!needle) return null;
1015
+ // Try exact title match first
1016
+ for (const e of idx) {
1017
+ if ((e.title || "").toLowerCase() === needle) return e;
1018
+ }
1019
+ // Fall back to prefix
1020
+ for (const e of idx) {
1021
+ if ((e.title || "").toLowerCase().startsWith(needle)) return e;
1022
+ }
1023
+ // Fall back to substring
1024
+ for (const e of idx) {
1025
+ if ((e.title || "").toLowerCase().indexOf(needle) !== -1) return e;
1026
+ }
1027
+ return null;
1028
+ }
1029
+
1030
+ function showPreview(target, entry) {
1031
+ const el = getPreviewEl();
1032
+ el.querySelector(".wl-title").textContent = entry.title || entry.id || "";
1033
+ el.querySelector(".wl-body").textContent = (entry.body || "").slice(0, 300);
1034
+ // Position below the target
1035
+ const rect = target.getBoundingClientRect();
1036
+ el.style.position = "fixed";
1037
+ el.style.top = (rect.bottom + 8) + "px";
1038
+ el.style.left = Math.min(window.innerWidth - 380, Math.max(16, rect.left)) + "px";
1039
+ el.removeAttribute("hidden");
1040
+ }
1041
+
1042
+ function hidePreview() {
1043
+ if (previewEl) previewEl.setAttribute("hidden", "");
1044
+ }
1045
+
1046
+ function attach(a) {
1047
+ const text = (a.textContent || "").trim();
1048
+ // Only target links that look like wikilinks (starting with [[) or that
1049
+ // point to another page in site/sessions, site/projects, or site/.
1050
+ const isWiki = text.startsWith("[[") || /sessions\/|projects\//.test(a.getAttribute("href") || "");
1051
+ if (!isWiki) return;
1052
+ let key = text.replace(/^\[\[|\]\]$/g, "").trim();
1053
+ if (!key) {
1054
+ // Derive from href
1055
+ const href = a.getAttribute("href") || "";
1056
+ const m = href.match(/([^/]+)\.html$/);
1057
+ if (m) key = m[1];
1058
+ }
1059
+ if (!key) return;
1060
+
1061
+ function _show() {
1062
+ if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
1063
+ loadIndex().then(function () {
1064
+ const entry = findEntry(key);
1065
+ if (entry) showPreview(a, entry);
1066
+ });
1067
+ }
1068
+ function _hide() {
1069
+ hideTimer = setTimeout(hidePreview, 200);
1070
+ }
1071
+ // #ui-h13 (#570): keyboard parity for the hover preview. Show on
1072
+ // focus + hide on blur so a Tab-only user gets the same affordance
1073
+ // a mouse user gets. ESC dismisses immediately and returns nothing
1074
+ // to do (focus is already on the link).
1075
+ a.addEventListener("mouseenter", _show);
1076
+ a.addEventListener("mouseleave", _hide);
1077
+ a.addEventListener("focus", _show);
1078
+ a.addEventListener("blur", _hide);
1079
+ a.addEventListener("keydown", function (e) {
1080
+ if (e.key === "Escape") {
1081
+ if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
1082
+ hidePreview();
1083
+ }
1084
+ });
1085
+ }
1086
+
1087
+ document.addEventListener("DOMContentLoaded", function () {
1088
+ document.querySelectorAll(".content a").forEach(attach);
1089
+ });
1090
+ })();
1091
+
1092
+ // ─── Timeline view on sessions index ──────────────────────────────────────
1093
+ // Render a compact sparkline above the sessions table showing session count
1094
+ // per day over the last 60 days.
1095
+ (function () {
1096
+ // Post-final-review: local attribute escaper. The timeline SVG below
1097
+ // string-concatenates `data-date` and `data-count` into HTML; while
1098
+ // the values come from controlled `data-date` row attributes (built
1099
+ // in build.py from frontmatter dates), defense-in-depth escapes them
1100
+ // anyway. The palette IIFE has its own `escapeHtml` but it's out of
1101
+ // scope here, hence the local copy.
1102
+ function escAttr(s) {
1103
+ return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
1104
+ return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
1105
+ });
1106
+ }
1107
+ document.addEventListener("DOMContentLoaded", function () {
1108
+ const tbody = document.getElementById("sessions-tbody");
1109
+ if (!tbody) return;
1110
+ // Only run on the sessions index page
1111
+ const container = document.querySelector(".section .container");
1112
+ if (!container || !container.querySelector(".filter-bar")) return;
1113
+
1114
+ // Collect dates
1115
+ const rows = Array.from(tbody.querySelectorAll("tr"));
1116
+ const counts = new Map();
1117
+ rows.forEach(function (r) {
1118
+ const d = r.getAttribute("data-date");
1119
+ if (!d) return;
1120
+ counts.set(d, (counts.get(d) || 0) + 1);
1121
+ });
1122
+ if (!counts.size) return;
1123
+
1124
+ // Sort dates ascending
1125
+ const dates = Array.from(counts.keys()).sort();
1126
+ const maxCount = Math.max(...counts.values());
1127
+
1128
+ // #453: position bars by calendar date so gaps between active days are
1129
+ // visible. The previous behaviour stretched dates.length bars across
1130
+ // the full width with equal spacing, which hid 6-month gaps. We now
1131
+ // compute calendar span (minDate→maxDate) in days and lay bars out
1132
+ // proportional to their date offset. Single-day collections fall back
1133
+ // to a single centred bar.
1134
+ const minDate = new Date(dates[0] + "T00:00:00Z");
1135
+ const maxDate = new Date(dates[dates.length - 1] + "T00:00:00Z");
1136
+ const dayMs = 86400000;
1137
+ const spanDays = Math.round((maxDate - minDate) / dayMs) + 1;
1138
+
1139
+ // Build an SVG sparkline
1140
+ const w = 800;
1141
+ const h = 60;
1142
+ const padX = 4;
1143
+ const innerW = w - 2 * padX;
1144
+ const slotW = spanDays > 1 ? innerW / spanDays : innerW;
1145
+ const bars = dates.map(function (d) {
1146
+ const count = counts.get(d);
1147
+ const offset = spanDays > 1
1148
+ ? Math.round((new Date(d + "T00:00:00Z") - minDate) / dayMs)
1149
+ : 0;
1150
+ const x = spanDays > 1 ? padX + offset * slotW : padX + innerW / 2 - 2;
1151
+ const barW = Math.max(2, slotW - 1);
1152
+ const barH = (count / maxCount) * (h - 16);
1153
+ const y = h - barH - 4;
1154
+ return '<rect x="' + x + '" y="' + y + '" width="' + barW + '" height="' + barH +
1155
+ '" fill="var(--accent)" opacity="0.7" data-date="' + escAttr(d) + '" data-count="' + escAttr(count) + '"></rect>';
1156
+ }).join("");
1157
+
1158
+ const svg =
1159
+ '<svg viewBox="0 0 ' + w + ' ' + h + '" preserveAspectRatio="none" ' +
1160
+ 'style="width:100%;height:' + h + 'px;display:block" aria-label="Session activity timeline">' +
1161
+ bars + '</svg>';
1162
+
1163
+ // #453: label now shows calendar span (matches the geometry above) plus
1164
+ // active-day count and peak so users can read both stories from one line.
1165
+ const labelText = spanDays === 1
1166
+ ? 'Activity timeline · 1 day · peak ' + maxCount + (maxCount === 1 ? ' session' : ' sessions')
1167
+ : 'Activity timeline · ' + spanDays + ' days · ' + dates.length +
1168
+ ' active · peak ' + maxCount + (maxCount === 1 ? ' session/day' : ' sessions/day');
1169
+
1170
+ // Create the timeline block. #v1378-review: previously assigned
1171
+ // the label + svg via innerHTML, which interpolated `labelText`
1172
+ // (currently number-only — safe today) into HTML without escaping.
1173
+ // Defense-in-depth: build the label as a real element with
1174
+ // textContent so a future change feeding a user-derived string
1175
+ // into the label can't introduce XSS. The svg string itself is
1176
+ // already escaped via escAttr() at every data-* interpolation
1177
+ // and uses only static structural markup elsewhere.
1178
+ const tl = document.createElement("div");
1179
+ tl.className = "timeline-block";
1180
+ const labelEl = document.createElement("div");
1181
+ labelEl.className = "timeline-label muted";
1182
+ labelEl.textContent = labelText;
1183
+ tl.appendChild(labelEl);
1184
+ tl.insertAdjacentHTML("beforeend", svg);
1185
+
1186
+ // Insert above the filter bar
1187
+ const filter = container.querySelector(".filter-bar");
1188
+ if (filter) container.insertBefore(tl, filter);
1189
+ });
1190
+ })();
1191
+
1192
+ // ─── v0.4: Related pages panel ────────────────────────────────────────────
1193
+ // On a session page, find 3-5 other sessions that share wikilink targets
1194
+ // or project, and display them at the bottom under a "Related pages" heading.
1195
+ (function () {
1196
+ document.addEventListener("DOMContentLoaded", function () {
1197
+ const article = document.querySelector("article.content");
1198
+ if (!article) return;
1199
+ // Only on session pages (have a breadcrumb + back-to-project link)
1200
+ const backBtn = document.querySelector(".session-actions a.btn");
1201
+ if (!backBtn) return;
1202
+
1203
+ // Extract current page metadata from the sessionwiki:metadata comment
1204
+ const html = document.documentElement.outerHTML;
1205
+ const m = html.match(/sessionwiki:metadata\n([\s\S]*?)-->/);
1206
+ if (!m) return;
1207
+ const meta = {};
1208
+ m[1].split("\n").forEach(function (line) {
1209
+ const idx = line.indexOf(":");
1210
+ if (idx > 0) {
1211
+ const k = line.slice(0, idx).trim();
1212
+ const v = line.slice(idx + 1).trim();
1213
+ if (k && v) meta[k] = v;
1214
+ }
1215
+ });
1216
+ const currentProject = meta.project || "";
1217
+ const currentSlug = meta.slug || "";
1218
+ if (!currentProject) return;
1219
+
1220
+ // Reuse the shared chunked loader (#47) — includes session entries
1221
+ var loader = window.__sessionwikiLoadIndex
1222
+ ? window.__sessionwikiLoadIndex()
1223
+ : fetch(window.LLMWIKI_INDEX_URL || "search-index.json")
1224
+ .then(function (r) { return r.ok ? r.json() : []; })
1225
+ .then(function (d) { return Array.isArray(d) ? d : (d.entries || []); });
1226
+ loader
1227
+ .then(function (entries) {
1228
+ if (!entries || !entries.length) return;
1229
+ // Score each other session: same project = 2 pts, shared wikilink targets = +1 per token
1230
+ const scored = entries
1231
+ .filter(function (e) {
1232
+ return e.type === "session" && e.url && !e.url.endsWith(currentSlug + ".html");
1233
+ })
1234
+ .map(function (e) {
1235
+ let score = 0;
1236
+ if (e.project === currentProject) score += 2;
1237
+ return { entry: e, score: score };
1238
+ })
1239
+ .filter(function (s) { return s.score > 0; })
1240
+ .sort(function (a, b) { return b.score - a.score; })
1241
+ .slice(0, 5);
1242
+ if (!scored.length) return;
1243
+
1244
+ // Post-review remediation: title + url + date used to be
1245
+ // interpolated into innerHTML without escaping. Build the DOM
1246
+ // tree explicitly with createElement / textContent so a malicious
1247
+ // session frontmatter title (e.g. "<img src=x onerror=...>") or
1248
+ // a `javascript:` URL can't execute in the visitor's browser.
1249
+ function _safeHref(raw) {
1250
+ // Reject anything that isn't a relative path or http(s).
1251
+ // Same-origin checks happen at the browser; we just gate the
1252
+ // protocol prefix here to stop `javascript:` / `data:` etc.
1253
+ var s = String(raw || "");
1254
+ if (/^(javascript|data|vbscript):/i.test(s)) return "#";
1255
+ return s;
1256
+ }
1257
+ const section = document.createElement("div");
1258
+ section.className = "related-pages";
1259
+ const heading = document.createElement("h3");
1260
+ heading.textContent = "Related pages";
1261
+ section.appendChild(heading);
1262
+ const ul = document.createElement("ul");
1263
+ scored.forEach(function (s) {
1264
+ const li = document.createElement("li");
1265
+ const a = document.createElement("a");
1266
+ a.href = _safeHref("../../" + (s.entry.url || ""));
1267
+ a.textContent = String(s.entry.title || "");
1268
+ li.appendChild(a);
1269
+ if (s.entry.date) {
1270
+ const span = document.createElement("span");
1271
+ span.className = "muted";
1272
+ span.textContent = " \u00b7 " + String(s.entry.date);
1273
+ li.appendChild(span);
1274
+ }
1275
+ ul.appendChild(li);
1276
+ });
1277
+ section.appendChild(ul);
1278
+ article.appendChild(section);
1279
+ })
1280
+ .catch(function () {});
1281
+ });
1282
+ })();
1283
+
1284
+ // v0.8 (#64, #72): the v0.4 JS-based tiny-strip heatmap is gone. The 365-day
1285
+ // GitLab/GitHub-style grid is now rendered at build time as pure SVG by
1286
+ // sessionwiki/viz_heatmap.py and inlined into index.html + each project page.
1287
+ // The page CSS (--heatmap-0..4) picks up the current theme automatically —
1288
+ // no JS wiring needed.
1289
+
1290
+ // ─── v0.4: Search result highlights ──────────────────────────────────────
1291
+ // When showing search palette results, highlight the matched query in the
1292
+ // title and body snippet.
1293
+ (function () {
1294
+ function highlight(text, query) {
1295
+ if (!query || !text) return escapeLocalHtml(text);
1296
+ const q = query.toLowerCase();
1297
+ const lower = text.toLowerCase();
1298
+ const i = lower.indexOf(q);
1299
+ if (i === -1) return escapeLocalHtml(text);
1300
+ return escapeLocalHtml(text.slice(0, i)) +
1301
+ '<mark>' + escapeLocalHtml(text.slice(i, i + q.length)) + '</mark>' +
1302
+ escapeLocalHtml(text.slice(i + q.length));
1303
+ }
1304
+ function escapeLocalHtml(s) {
1305
+ return String(s || "").replace(/[&<>"']/g, function (c) {
1306
+ return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
1307
+ });
1308
+ }
1309
+ // Expose so the palette renderer can call it if it chooses
1310
+ window.sessionwikiHighlight = highlight;
1311
+ })();
1312
+
1313
+ // ─── v0.4: Deep-link icon next to headings ────────────────────────────────
1314
+ (function () {
1315
+ document.addEventListener("DOMContentLoaded", function () {
1316
+ document.querySelectorAll(".content h2[id], .content h3[id], .content h4[id]").forEach(function (h) {
1317
+ if (h.querySelector(".deep-link")) return;
1318
+ const icon = document.createElement("a");
1319
+ icon.className = "deep-link";
1320
+ icon.href = "#" + h.id;
1321
+ icon.innerHTML = "🔗";
1322
+ icon.title = "Copy link to this section";
1323
+ icon.addEventListener("click", function (ev) {
1324
+ ev.preventDefault();
1325
+ const url = window.location.origin + window.location.pathname + "#" + h.id;
1326
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1327
+ navigator.clipboard.writeText(url).then(function () {
1328
+ icon.textContent = "✓";
1329
+ setTimeout(function () { icon.textContent = "🔗"; }, 1200);
1330
+ });
1331
+ }
1332
+ });
1333
+ h.appendChild(icon);
1334
+ });
1335
+ });
1336
+ })();
1337
+ """