dsh-tiddlywiki 0.27.2 → 0.28.0

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 (41) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +3 -0
  3. package/cordis.patch.yml +13 -13
  4. package/docs/CHANGELOG.md +2 -1
  5. package/docs/code-review-2026-09-17.md +151 -0
  6. package/docs/features.md +5 -2
  7. package/docs/usage.md +34 -3
  8. package/docs/wiki-split.md +97 -0
  9. package/lib/client.js +54 -27
  10. package/lib/index.js +2803 -517
  11. package/lib/index.js.map +1 -1
  12. package/package.json +5 -4
  13. package/skills/wiki-split/SKILL.md +106 -0
  14. package/src/client/endpoints.ts +37 -0
  15. package/src/client/index.ts +14 -0
  16. package/src/client/knowledge-fab.ts +62 -3
  17. package/src/client/markdown-editor.ts +128 -128
  18. package/src/client/panel.ts +2 -1
  19. package/src/client/settings-page.ts +217 -3
  20. package/src/client/state.ts +39 -39
  21. package/src/client/status-cache.ts +17 -0
  22. package/src/client/styles.ts +27 -0
  23. package/src/client/toast.ts +22 -22
  24. package/src/client/tw-frame.ts +28 -4
  25. package/src/client/wiki-focus.ts +70 -0
  26. package/src/client/wiki-scope-dock.ts +116 -0
  27. package/src/host/admin.ts +175 -35
  28. package/src/host/git.ts +50 -5
  29. package/src/host/path-key.ts +35 -0
  30. package/src/host/prompt.ts +24 -0
  31. package/src/host/repo-committers.ts +149 -0
  32. package/src/host/routes.ts +254 -81
  33. package/src/host/seeds.ts +51 -10
  34. package/src/host/session-scope.ts +154 -0
  35. package/src/host/skill-install.ts +121 -0
  36. package/src/host/tools.ts +141 -49
  37. package/src/host/wiki-farm.ts +417 -0
  38. package/src/host/wiki-instance.ts +596 -0
  39. package/src/host/wiki-registry.ts +601 -0
  40. package/src/host/wiki.ts +19 -0
  41. package/src/index.ts +686 -459
@@ -0,0 +1,601 @@
1
+ /**
2
+ * Multi-wiki registry (v0.28.0) — which knowledge bases exist, which one is the
3
+ * default, and which of them the agent may see at all.
4
+ *
5
+ * WHY A FILE OUTSIDE EVERY WIKI
6
+ * -----------------------------
7
+ * Same reason as the single-location pointer (`host/wiki-location.ts`): the
8
+ * settings page stores its overrides INSIDE the wiki it configures
9
+ * (`$:/plugins/dsh-tiddlywiki/config`), so "which wikis exist / which is the
10
+ * default" cannot live there — the answer must outlive every one of them.
11
+ * The registry therefore lives next to the pointer:
12
+ *
13
+ * $DSH_HOME/dsh-tiddlywiki/wikis.json
14
+ * { "version": 1, "defaultId": "main",
15
+ * "wikis": [ { "id": "main", "label": "工作", "root": "D:/notes",
16
+ * "name": "main", "agentVisible": true, "autostart": true } ] }
17
+ *
18
+ * THREE SOURCES, ONE PRECEDENCE
19
+ * -----------------------------
20
+ * wikis.json > legacy location.json (one `active` location) > cordis config default
21
+ *
22
+ * A user upgrading from a single-wiki install has only `location.json`; it is
23
+ * migrated IN MEMORY into a one-entry registry (id `main`, agentVisible +
24
+ * autostart true, so the upgrade reproduces the old behaviour exactly). The
25
+ * caller writes the migrated registry back at its leisure — this module only
26
+ * reads and validates.
27
+ *
28
+ * FAIL LOUD, DEGRADE TO A KNOWN-GOOD STATE
29
+ * ----------------------------------------
30
+ * A malformed registry is REPORTED and the fallback chain is used — it is
31
+ * never silently acted upon (the same rule `readLocationState()` follows, and
32
+ * for the same reason: a hand-edited JSON must not make the plugin boot
33
+ * somewhere unexpected). Two severities:
34
+ *
35
+ * - `fatal` — the file is structurally unusable, or keeping it would be
36
+ * DANGEROUS (duplicate id, two entries on one folder, nested
37
+ * folders, a future schema version). → registry comes from
38
+ * the fallback chain.
39
+ * - `warnings` — healed or skipped (one unparsable entry, `defaultId`
40
+ * pointing at a wiki that is gone). → registry is usable.
41
+ *
42
+ * NESTED FOLDERS ARE REFUSED ON PURPOSE
43
+ * -------------------------------------
44
+ * Two registered wikis that contain one another (`D:/notes` and
45
+ * `D:/notes/work`) are rejected rather than warned about: path-prefix
46
+ * attribution becomes ambiguous for every git operation, and the OUTER wiki's
47
+ * `git add -A` commits the inner wiki's tiddlers too (see the repo-keyed commit
48
+ * model in `host/git.ts`). Both failure modes are silent and expensive, so the
49
+ * cheapest correct answer is "no".
50
+ *
51
+ * @module dsh-tiddlywiki/host/wiki-registry
52
+ */
53
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
54
+ import { basename, dirname } from 'node:path'
55
+ import { dshHomePath } from '../sdk.ts'
56
+ import { isInsidePath, pathComparisonKey } from './path-key.ts'
57
+ import { defaultLocationStateFile, locationPath, normalizeLocation, readLocationState, type WikiLocation } from './wiki-location.ts'
58
+
59
+ /** Registry schema version (bumped only on an incompatible change). */
60
+ export const WIKI_REGISTRY_VERSION = 1
61
+
62
+ /** Id of the entry a migrated single-wiki install gets. */
63
+ export const DEFAULT_WIKI_ID = 'main'
64
+
65
+ /**
66
+ * How many knowledge bases the plugin runs at once.
67
+ *
68
+ * - `single` (default): exactly the behaviour every existing install already
69
+ * has — ONE wiki, chosen by the legacy pointer file over the cordis default.
70
+ * The registry is then only a memory of `mode` + the candidate list.
71
+ * - `multi`: the registry drives a farm — one TW child per entry, `autostart`
72
+ * entries come up at boot, and GUI/agent can address each one by id.
73
+ *
74
+ * WHY IT LIVES IN THIS FILE (and not in a wiki's config tiddler): the decision
75
+ * must be readable BEFORE any wiki starts, and a config tiddler only exists
76
+ * inside a wiki that is already running. Same reasoning as `agentVisible`.
77
+ */
78
+ export type WikiMode = 'single' | 'multi'
79
+
80
+ /** The accepted modes, in declaration order (settings-page radio list). */
81
+ export const WIKI_MODES: readonly WikiMode[] = ['single', 'multi']
82
+
83
+ /** Mode assumed when the registry says nothing (upgrades, fresh installs). */
84
+ export const DEFAULT_WIKI_MODE: WikiMode = 'single'
85
+
86
+ /** One registered knowledge base. */
87
+ export interface WikiEntry {
88
+ /**
89
+ * Stable, URL-safe identifier. It is a path segment of the same-origin proxy
90
+ * (`/dsh-tiddlywiki/tw/<id>/`) and part of the tiddler titles the session
91
+ * scope is stored under, so the charset is deliberately narrow and lowercase.
92
+ */
93
+ id: string
94
+ /** Display name used by every entry point / tab / picker (the single source). */
95
+ label: string
96
+ /** Absolute folder that HOLDS the wiki folder (same shape as WikiLocation). */
97
+ root: string
98
+ /** Wiki folder name under `root`; `.` means "the root folder itself". */
99
+ name: string
100
+ /**
101
+ * May the AGENT reach this wiki at all? `false` = completely invisible: not
102
+ * in the session picker, not mentioned in the injected prompt, never a
103
+ * target of any `tiddlywiki_*` tool. Humans are unaffected.
104
+ *
105
+ * It lives HERE and not in the wiki's own config tiddler on purpose: asking
106
+ * "should this one be hidden?" must not require starting the hidden wiki.
107
+ */
108
+ agentVisible: boolean
109
+ /** Start its TW child process at boot (default false; the default wiki is true). */
110
+ autostart: boolean
111
+ }
112
+
113
+ /** The whole registry: the mode, a non-empty list, and the default-wiki pointer. */
114
+ export interface WikiRegistry {
115
+ version: number
116
+ /**
117
+ * `single` = one wiki, legacy behaviour (the pointer file still decides which);
118
+ * `multi` = run every entry, `defaultId` decides the agent's fallback scope.
119
+ */
120
+ mode: WikiMode
121
+ /** Id of the wiki a session with no explicit scope falls back to. */
122
+ defaultId: string
123
+ wikis: WikiEntry[]
124
+ }
125
+
126
+ /** Result of `validateRegistry()`: what survived, what ruined it, what was healed. */
127
+ export interface RegistryValidation {
128
+ /** Best-effort registry; absent only when `fatal` is non-empty. */
129
+ registry?: WikiRegistry
130
+ /** Reasons the file must NOT be trusted (fall back to the legacy chain). */
131
+ fatal: string[]
132
+ /** Healed/skipped problems worth showing the user. */
133
+ warnings: string[]
134
+ }
135
+
136
+ /** Result of `readRegistry()` — always yields a usable registry. */
137
+ export interface RegistryReadResult {
138
+ registry: WikiRegistry
139
+ /** Where the returned registry came from (settings-page display). */
140
+ source: 'file' | 'legacy' | 'default'
141
+ /** Joined problem text; fatal problems mean the fallback chain was used. */
142
+ error?: string
143
+ /** Non-fatal problems healed in the returned registry. */
144
+ warnings: string[]
145
+ }
146
+
147
+ /** Default registry file: `$DSH_HOME/dsh-tiddlywiki/wikis.json`. */
148
+ export function defaultRegistryFile(): string {
149
+ return dshHomePath('dsh-tiddlywiki', 'wikis.json')
150
+ }
151
+
152
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
153
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
154
+ }
155
+
156
+ /**
157
+ * Normalise/validate a wiki id, or undefined when unusable.
158
+ *
159
+ * Lowercased on purpose: the id is a URL path segment, and `/tw/Work/` vs
160
+ * `/tw/work/` resolving to two different wikis on a case-insensitive Windows
161
+ * filesystem would be a trap. Derivation (`deriveWikiId`) lowercases too, so a
162
+ * round trip is stable.
163
+ */
164
+ export function normalizeWikiId(raw: unknown): string | undefined {
165
+ if (typeof raw !== 'string') return undefined
166
+ const id = raw.trim().toLowerCase()
167
+ if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(id)) return undefined
168
+ return id
169
+ }
170
+
171
+ /**
172
+ * Wiki ids that must NOT be used, because a wiki id is a PATH SEGMENT of the
173
+ * same-origin proxy (`/dsh-tiddlywiki/tw/<id>/…`) while the TW child serves its
174
+ * own endpoints at its ROOT (`/status`, `/recipes/…`, `/files/…`). An id equal
175
+ * to one of those would make `/tw/status` ambiguous: is it the default wiki's
176
+ * TW status, or the wiki named `status`? Nothing in the request can tell them
177
+ * apart, so the id is simply refused (v0.28.0).
178
+ *
179
+ * This list is what lets the proxy treat "first segment looks like a known id"
180
+ * as the per-wiki form and everything else as a TW path.
181
+ */
182
+ export const RESERVED_WIKI_IDS: readonly string[] = [
183
+ 'status', 'recipes', 'bags', 'files', 'render', 'login', 'logout',
184
+ 'favicon.ico', 'index.html', 'static', 'assets',
185
+ ]
186
+
187
+ /** Filesystem-safe slug for a wiki id (may be empty for junk input). */
188
+ function slugifyIdPart(raw: unknown): string {
189
+ return String(raw ?? '')
190
+ .trim()
191
+ .toLowerCase()
192
+ .replace(/[^a-z0-9._-]+/g, '-')
193
+ .replace(/-{2,}/g, '-')
194
+ .replace(/^[-.]+|[-.]+$/g, '')
195
+ .slice(0, 48)
196
+ }
197
+
198
+ /**
199
+ * Derive a unique wiki id from a folder name (or any label), avoiding `taken`.
200
+ * Falls back to `wiki`, `wiki-2`, … when the slug is empty or already used.
201
+ */
202
+ export function deriveWikiId(source: unknown, taken: Iterable<string> = []): string {
203
+ const used = new Set<string>()
204
+ // Reserved ids are "taken" too: a folder literally named `status` must not
205
+ // produce a wiki id the proxy could never route.
206
+ for (const reserved of RESERVED_WIKI_IDS) used.add(reserved)
207
+ for (const item of taken) {
208
+ const id = normalizeWikiId(item)
209
+ if (id !== undefined) used.add(id)
210
+ }
211
+ const base = normalizeWikiId(slugifyIdPart(source)) ?? 'wiki'
212
+ if (!used.has(base)) return base
213
+ for (let n = 2; n < 10_000; n += 1) {
214
+ const candidate = `${base}-${n}`.slice(0, 64)
215
+ if (!used.has(candidate)) return candidate
216
+ }
217
+ // Unreachable for a real registry; still must return a *valid* id.
218
+ return `wiki-${Date.now().toString(36)}`.slice(0, 64)
219
+ }
220
+
221
+ /** The `{root, name}` location this entry points at. */
222
+ export function entryLocation(entry: Pick<WikiEntry, 'root' | 'name'>): WikiLocation {
223
+ return { root: entry.root, name: entry.name }
224
+ }
225
+
226
+ /** Absolute folder this entry serves. */
227
+ export function entryPath(entry: Pick<WikiEntry, 'root' | 'name'>): string {
228
+ return locationPath(entryLocation(entry))
229
+ }
230
+
231
+ /**
232
+ * Comparison key for duplicate/nesting detection — the SHARED one from
233
+ * host/path-key.ts (the repo grouping and the farm's path-change check need the
234
+ * same answer to "is this the same folder?", so there is exactly one rule).
235
+ *
236
+ * @see pathComparisonKey
237
+ */
238
+
239
+ /** Display label for an entry that came without one. */
240
+ function defaultLabel(location: WikiLocation): string {
241
+ if (location.name !== '.') return location.name.slice(0, 60)
242
+ return basename(locationPath(location)).slice(0, 60) || '.'
243
+ }
244
+
245
+ /**
246
+ * Validate one entry. Missing `label` is derived, missing flags take their
247
+ * defaults (`agentVisible` true, `autostart` false) — those are not errors.
248
+ */
249
+ export function normalizeEntry(input: unknown): { entry?: WikiEntry; error?: string } {
250
+ if (!isPlainObject(input)) return { error: '条目必须是一个对象' }
251
+ const id = normalizeWikiId(input.id)
252
+ if (id === undefined) {
253
+ return { error: `知识库 id 非法(需以小写字母或数字开头,后接 a-z0-9._-,最长 64):${JSON.stringify(input.id)}` }
254
+ }
255
+ if (RESERVED_WIKI_IDS.includes(id)) {
256
+ return { error: `知识库 id「${id}」被保留:它会和 TW 自己的根路径 /${id} 撞名,同源代理无法区分两者` }
257
+ }
258
+ const normalized = normalizeLocation({ root: input.root, name: input.name })
259
+ if (normalized.location === undefined) return { error: normalized.error ?? '位置非法' }
260
+ const label = typeof input.label === 'string' && input.label.trim().length > 0
261
+ ? input.label.trim().slice(0, 60)
262
+ : defaultLabel(normalized.location)
263
+ return {
264
+ entry: {
265
+ id,
266
+ label,
267
+ root: normalized.location.root,
268
+ name: normalized.location.name,
269
+ agentVisible: input.agentVisible !== false,
270
+ autostart: input.autostart === true,
271
+ },
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Duplicate-folder and nested-folder problems across a candidate entry list.
277
+ *
278
+ * Nested = one entry's folder is strictly inside another's. Checked in both
279
+ * directions and reported once per pair (the outer entry is named first).
280
+ */
281
+ export function findPathConflicts(entries: readonly WikiEntry[]): string[] {
282
+ const problems: string[] = []
283
+ const byKey = new Map<string, WikiEntry>()
284
+ for (const entry of entries) {
285
+ const path = entryPath(entry)
286
+ const key = pathComparisonKey(path)
287
+ const duplicate = byKey.get(key)
288
+ if (duplicate !== undefined) {
289
+ problems.push(`知识库「${entry.id}」与「${duplicate.id}」指向同一个目录:${path}`)
290
+ continue
291
+ }
292
+ byKey.set(key, entry)
293
+ }
294
+ const unique = [...byKey.values()]
295
+ for (const outer of unique) {
296
+ const outerPath = entryPath(outer)
297
+ for (const inner of unique) {
298
+ if (inner === outer) continue
299
+ // Strictly inside: `''` (same path) is already reported as a duplicate, and
300
+ // a sibling (`D:/notes` vs `D:/notes2`) is not nesting.
301
+ if (!isInsidePath(outerPath, entryPath(inner))) continue
302
+ problems.push(
303
+ `知识库「${inner.id}」位于「${outer.id}」目录内部(${entryPath(inner)} ⊂ ${entryPath(outer)}):嵌套登记会让外层知识库的 git 一并提交内层内容,已拒绝`,
304
+ )
305
+ }
306
+ }
307
+ return problems
308
+ }
309
+
310
+ /**
311
+ * Validate a parsed registry object.
312
+ *
313
+ * Structural/ambiguous problems are FATAL (empty `registry`): a duplicate id,
314
+ * two entries on one folder, nested folders, a future schema version, or a
315
+ * list where nothing parses. Per-entry junk and a stale `defaultId` are healed
316
+ * and reported as warnings, because dropping one wiki is recoverable while
317
+ * refusing to boot is not.
318
+ */
319
+ export function validateRegistry(input: unknown): RegistryValidation {
320
+ const fatal: string[] = []
321
+ const warnings: string[] = []
322
+ if (!isPlainObject(input)) return { fatal: ['清单必须是一个 JSON 对象'], warnings }
323
+
324
+ const rawVersion = input.version
325
+ if (typeof rawVersion === 'number' && Number.isFinite(rawVersion) && rawVersion > WIKI_REGISTRY_VERSION) {
326
+ return { fatal: [`清单版本 ${rawVersion} 由更新版本的插件写入,本版本(${WIKI_REGISTRY_VERSION})无法安全读取`], warnings }
327
+ }
328
+ if (!Array.isArray(input.wikis) || input.wikis.length === 0) {
329
+ return { fatal: ['清单里没有任何知识库(wikis 必须是非空数组)'], warnings }
330
+ }
331
+
332
+ const entries: WikiEntry[] = []
333
+ const seenIds = new Set<string>()
334
+ for (const [index, item] of input.wikis.entries()) {
335
+ const normalized = normalizeEntry(item)
336
+ if (normalized.entry === undefined) {
337
+ warnings.push(`跳过第 ${index + 1} 个条目:${normalized.error}`)
338
+ continue
339
+ }
340
+ if (seenIds.has(normalized.entry.id)) {
341
+ return { fatal: [`知识库 id 重复:${normalized.entry.id}`], warnings }
342
+ }
343
+ seenIds.add(normalized.entry.id)
344
+ entries.push(normalized.entry)
345
+ }
346
+ if (entries.length === 0) {
347
+ return { fatal: warnings.length > 0 ? [...warnings, '没有任何条目可用'] : ['清单里没有任何可用的知识库'], warnings }
348
+ }
349
+
350
+ const conflicts = findPathConflicts(entries)
351
+ if (conflicts.length > 0) return { fatal: conflicts, warnings }
352
+
353
+ const rawDefault = typeof input.defaultId === 'string' ? input.defaultId.trim().toLowerCase() : ''
354
+ let defaultId = rawDefault
355
+ if (!seenIds.has(defaultId)) {
356
+ if (rawDefault.length > 0) warnings.push(`defaultId「${rawDefault}」不在清单里,已回退到「${entries[0]?.id ?? DEFAULT_WIKI_ID}」`)
357
+ defaultId = entries[0]?.id ?? DEFAULT_WIKI_ID
358
+ }
359
+ // Mode: a missing field means "the behaviour you already had" (single), and an
360
+ // UNKNOWN value is healed to single rather than being fatal — a typo must not
361
+ // collapse a working farm into `nothing runs`.
362
+ const rawMode = input.mode
363
+ let mode: WikiMode = DEFAULT_WIKI_MODE
364
+ if (rawMode !== undefined) {
365
+ if (rawMode === 'single' || rawMode === 'multi') mode = rawMode
366
+ else warnings.push(`未知的 mode「${String(rawMode)}」,已按 ${DEFAULT_WIKI_MODE} 处理`)
367
+ }
368
+ return { registry: { version: WIKI_REGISTRY_VERSION, mode, defaultId, wikis: entries }, fatal, warnings }
369
+ }
370
+
371
+ /** One localised entry for the current location, or undefined. */
372
+ export function findEntry(registry: WikiRegistry, id: unknown): WikiEntry | undefined {
373
+ if (typeof id !== 'string') return undefined
374
+ const key = id.trim().toLowerCase()
375
+ return registry.wikis.find((entry) => entry.id === key)
376
+ }
377
+
378
+ /** The default entry (falls back to the first when `defaultId` dangles). */
379
+ export function defaultEntry(registry: WikiRegistry): WikiEntry | undefined {
380
+ return findEntry(registry, registry.defaultId) ?? registry.wikis[0]
381
+ }
382
+
383
+ /** Insert or replace one entry by id (immutable); `defaultId` stays valid. */
384
+ export function upsertWiki(registry: WikiRegistry, entry: WikiEntry): WikiRegistry {
385
+ const index = registry.wikis.findIndex((item) => item.id === entry.id)
386
+ const wikis = index >= 0
387
+ ? registry.wikis.map((item, i) => (i === index ? entry : item))
388
+ : [...registry.wikis, entry]
389
+ const defaultId = findEntry({ ...registry, wikis }, registry.defaultId) !== undefined
390
+ ? registry.defaultId
391
+ : (wikis[0]?.id ?? entry.id)
392
+ return { ...registry, defaultId, wikis }
393
+ }
394
+
395
+ /**
396
+ * Drop one entry (immutable). Refuses to empty the list — the plugin always
397
+ * needs at least one wiki — and re-points `defaultId` when it was removed.
398
+ */
399
+ export function removeWiki(registry: WikiRegistry, id: unknown): { registry?: WikiRegistry; error?: string } {
400
+ const target = findEntry(registry, id)
401
+ if (target === undefined) return { error: `知识库「${String(id)}」不在清单里` }
402
+ if (registry.wikis.length <= 1) return { error: '至少要保留一个知识库' }
403
+ const wikis = registry.wikis.filter((entry) => entry !== target)
404
+ const defaultId = target.id === registry.defaultId ? (wikis[0]?.id ?? target.id) : registry.defaultId
405
+ return { registry: { ...registry, defaultId, wikis } }
406
+ }
407
+
408
+ /**
409
+ * A settings-page action on the wiki list (v0.28.0).
410
+ *
411
+ * The shape is deliberately a small discriminated union rather than "POST the
412
+ * whole registry": the page can then never invent an inconsistent file, and
413
+ * every mutation goes through the SAME validation the boot path uses.
414
+ */
415
+ export type WikiAction =
416
+ | { action: 'add'; wiki: unknown }
417
+ | { action: 'update'; wiki: unknown }
418
+ | { action: 'remove'; id: unknown }
419
+ | { action: 'set-default'; id: unknown }
420
+ | { action: 'set-mode'; mode: unknown }
421
+
422
+ /**
423
+ * Apply ONE action to a registry, purely (v0.28.0).
424
+ *
425
+ * Pure on purpose: the side effects (write the file, reconcile the farm) stay in
426
+ * the host wiring, so the RULES — which id gets derived, what a duplicate means,
427
+ * what a folder move may collide with — are unit-testable in milliseconds
428
+ * (`scripts/verify-wiki-registry.mjs`).
429
+ *
430
+ * Every action re-runs `validateRegistry()` on the RESULT, because a change can
431
+ * create exactly the situations the registry exists to refuse: two entries on
432
+ * one folder, or one entry nested inside another.
433
+ */
434
+ export function applyWikiAction(registry: WikiRegistry, input: unknown): { registry?: WikiRegistry; error?: string } {
435
+ if (!isPlainObject(input) || typeof input.action !== 'string') {
436
+ return { error: '动作必须是一个带 action 字段的对象' }
437
+ }
438
+ const action = input.action
439
+ const finish = (next: WikiRegistry): { registry?: WikiRegistry; error?: string } => {
440
+ const validated = validateRegistry(next)
441
+ if (validated.registry === undefined) return { error: validated.fatal.join(';') }
442
+ return { registry: validated.registry }
443
+ }
444
+
445
+ if (action === 'add') {
446
+ const raw = isPlainObject(input.wiki) ? input.wiki : undefined
447
+ if (raw === undefined) return { error: 'add 需要 wiki 字段' }
448
+ // The id is derived from the label/folder when the caller does not name one,
449
+ // so the settings page can offer "add this folder" without asking for an id.
450
+ const explicit = normalizeWikiId(raw.id)
451
+ const id = explicit ?? deriveWikiId(typeof raw.label === 'string' && raw.label.trim().length > 0 ? raw.label : raw.name, registry.wikis.map((entry) => entry.id))
452
+ if (findEntry(registry, id) !== undefined) return { error: `知识库「${id}」已存在(改它请用 update)` }
453
+ const normalized = normalizeEntry({ ...raw, id })
454
+ if (normalized.entry === undefined) return { error: normalized.error ?? '条目非法' }
455
+ return finish({ ...registry, wikis: [...registry.wikis, normalized.entry] })
456
+ }
457
+
458
+ if (action === 'update') {
459
+ const raw = isPlainObject(input.wiki) ? input.wiki : undefined
460
+ if (raw === undefined) return { error: 'update 需要 wiki 字段' }
461
+ const id = normalizeWikiId(raw.id)
462
+ if (id === undefined) return { error: 'update 必须带一个合法的 id' }
463
+ const existing = findEntry(registry, id)
464
+ if (existing === undefined) return { error: `知识库「${id}」不在清单里(新增请用 add)` }
465
+ const normalized = normalizeEntry({ ...raw, id })
466
+ if (normalized.entry === undefined) return { error: normalized.error ?? '条目非法' }
467
+ return finish(upsertWiki(registry, normalized.entry))
468
+ }
469
+
470
+ if (action === 'remove') {
471
+ const removed = removeWiki(registry, input.id)
472
+ if (removed.registry === undefined) return { error: removed.error ?? '删除失败' }
473
+ return finish(removed.registry)
474
+ }
475
+
476
+ if (action === 'set-default') {
477
+ // A DANGLING default would be healed by validateRegistry, so it is checked
478
+ // here instead: "make this one the default" must fail loudly when it is gone.
479
+ const target = findEntry(registry, input.id)
480
+ if (target === undefined) return { error: `知识库「${String(input.id)}」不在清单里,无法设为默认` }
481
+ return finish({ ...registry, defaultId: target.id })
482
+ }
483
+
484
+ if (action === 'set-mode') {
485
+ if (input.mode !== 'single' && input.mode !== 'multi') {
486
+ return { error: `mode 只能是 ${WIKI_MODES.join(' 或 ')}(收到 ${JSON.stringify(input.mode)})` }
487
+ }
488
+ return finish({ ...registry, mode: input.mode })
489
+ }
490
+
491
+ return { error: `未知动作「${action}」(可用:add / update / remove / set-default / set-mode)` }
492
+ }
493
+
494
+ /**
495
+ * A one-entry registry for a single location (migration / first run).
496
+ *
497
+ * `mode` defaults to `single` — a migrated install must reproduce exactly the
498
+ * behaviour it had before the registry existed.
499
+ */
500
+ export function singleEntryRegistry(location: WikiLocation, id: string = DEFAULT_WIKI_ID, mode: WikiMode = DEFAULT_WIKI_MODE): WikiRegistry {
501
+ const normalized = normalizeLocation({ root: location.root, name: location.name })
502
+ const resolved: WikiLocation = normalized.location ?? { root: location.root, name: location.name }
503
+ const entryId = normalizeWikiId(id) ?? DEFAULT_WIKI_ID
504
+ return {
505
+ version: WIKI_REGISTRY_VERSION,
506
+ mode,
507
+ defaultId: entryId,
508
+ wikis: [{
509
+ id: entryId,
510
+ label: defaultLabel(resolved),
511
+ root: resolved.root,
512
+ name: resolved.name,
513
+ // A migrated single-wiki install IS the wiki the agent has always seen
514
+ // and the one that has always started at boot: keep both flags on.
515
+ agentVisible: true,
516
+ autostart: true,
517
+ }],
518
+ }
519
+ }
520
+
521
+ /** Write the registry atomically (tmp + rename, mkdir -p). */
522
+ export async function writeRegistry(registry: WikiRegistry, file: string = defaultRegistryFile()): Promise<void> {
523
+ const payload = JSON.stringify({ ...registry, updatedAt: new Date().toISOString() }, null, 2)
524
+ await mkdir(dirname(file), { recursive: true })
525
+ const tmp = `${file}.tmp`
526
+ await writeFile(tmp, payload, 'utf8')
527
+ await rename(tmp, file)
528
+ }
529
+
530
+ /**
531
+ * Read + validate the registry, falling back through `location.json` to the
532
+ * cordis default. Never throws: every failure is a reported error plus a
533
+ * usable one-entry registry.
534
+ */
535
+ export async function readRegistry(deps: {
536
+ file?: string
537
+ legacyFile?: string
538
+ /** The cordis-configured default location (last resort). */
539
+ fallback: WikiLocation
540
+ }): Promise<RegistryReadResult> {
541
+ const file = deps.file ?? defaultRegistryFile()
542
+ const legacyFile = deps.legacyFile ?? defaultLocationStateFile()
543
+
544
+ /**
545
+ * The chain below the registry: legacy pointer, then the cordis default.
546
+ * `reason` is prepended so the user learns WHY the registry was ignored.
547
+ */
548
+ const fallbackChain = async (reason: string, warnings: string[]): Promise<RegistryReadResult> => {
549
+ const legacy = await readLocationState(legacyFile)
550
+ // A migration — or a genuine first run — is NORMAL, not an error. Only a
551
+ // non-empty `reason` (a registry that EXISTS but cannot be trusted) is
552
+ // reported as one; the plain cases explain themselves through `source`.
553
+ // Otherwise every fresh install would greet the user with a red banner.
554
+ const legacyWarnings = legacy.error !== undefined ? [legacy.error] : []
555
+ if (legacy.active !== undefined) {
556
+ return {
557
+ registry: singleEntryRegistry(legacy.active, DEFAULT_WIKI_ID),
558
+ source: 'legacy',
559
+ ...(reason.length > 0 ? { error: `${reason};已回退到位置指针文件里的知识库(${locationPath(legacy.active)})` } : {}),
560
+ warnings: [...warnings, ...legacyWarnings],
561
+ }
562
+ }
563
+ return {
564
+ registry: singleEntryRegistry(deps.fallback, DEFAULT_WIKI_ID),
565
+ source: 'default',
566
+ ...(reason.length > 0 ? { error: `${reason};已回退到配置默认知识库(${locationPath(deps.fallback)})` } : {}),
567
+ warnings: [...warnings, ...legacyWarnings],
568
+ }
569
+ }
570
+
571
+ let raw: string
572
+ try {
573
+ raw = await readFile(file, 'utf8')
574
+ } catch (err) {
575
+ const code = (err as NodeJS.ErrnoException).code
576
+ if (code !== 'ENOENT') {
577
+ return fallbackChain(`知识库清单读不到(${file}):${err instanceof Error ? err.message : String(err)}`, [])
578
+ }
579
+ // Absent registry is the normal first run / upgrade path: no error text.
580
+ return fallbackChain('', [])
581
+ }
582
+
583
+ let parsed: unknown
584
+ try {
585
+ parsed = JSON.parse(raw)
586
+ } catch {
587
+ return fallbackChain(`知识库清单不是合法 JSON(${file})`, [])
588
+ }
589
+
590
+ const validated = validateRegistry(parsed)
591
+ if (validated.registry === undefined) {
592
+ return fallbackChain(`知识库清单不可用(${validated.fatal.join(';')})`, validated.warnings)
593
+ }
594
+ const warnings = validated.warnings
595
+ return {
596
+ registry: validated.registry,
597
+ source: 'file',
598
+ ...(warnings.length > 0 ? { error: warnings.join(';') } : {}),
599
+ warnings,
600
+ }
601
+ }
package/src/host/wiki.ts CHANGED
@@ -43,6 +43,25 @@ export const TW_PROXY_PREFIX = `${PATH_PREFIX}/tw`
43
43
  /** The proxy base path (trailing slash) handed to browsers / TW's frontend. */
44
44
  export const TW_PROXY_PATH = `${TW_PROXY_PREFIX}/`
45
45
 
46
+ /**
47
+ * The same-origin proxy base a wiki's TW frontend must use (v0.28.0).
48
+ *
49
+ * SINGLE mode returns the LEGACY bare path: that wiki IS the default one, and
50
+ * every existing install already has exactly that value in its host tiddler — so
51
+ * the upgrade produces no diff at all.
52
+ *
53
+ * MULTI mode gives each wiki `/dsh-tiddlywiki/tw/<id>/`. That is load-bearing:
54
+ * TW builds every API URL from this tiddler, so a wiki using the bare path while
55
+ * another wiki is default would render one wiki's UI over another's data.
56
+ *
57
+ * Both forms route to the same child, so a stale value left by a mode flip is
58
+ * harmless. Exported so the host wiring and the verification harness use ONE
59
+ * implementation of the rule.
60
+ */
61
+ export function proxyBaseFor(mode: 'single' | 'multi', wikiId: string): string {
62
+ return mode === 'multi' ? `${TW_PROXY_PATH}${encodeURIComponent(wikiId)}/` : TW_PROXY_PATH
63
+ }
64
+
46
65
  /*
47
66
  * Readiness is POLICY, not a constant: `ready-policy.ts` owns the soft window
48
67
  * (default 60s, configurable), the 3× hard deadline and the polling loop — see