@xingular/harness 0.0.0-stage → 0.1.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 (133) hide show
  1. package/README.md +269 -2
  2. package/dist/cli.js +11046 -0
  3. package/dist/terminal-pi.js +326 -0
  4. package/package.json +41 -4
  5. package/src/accounts/accounts.test.ts +223 -0
  6. package/src/accounts/accounts.ts +522 -0
  7. package/src/accounts/env.ts +204 -0
  8. package/src/accounts/secrets.ts +50 -0
  9. package/src/accounts/store.ts +338 -0
  10. package/src/capabilities/api.ts +75 -0
  11. package/src/capabilities/runSnapshot.ts +59 -0
  12. package/src/capabilities/types.ts +34 -0
  13. package/src/cli.ts +110 -0
  14. package/src/core/bus.ts +34 -0
  15. package/src/core/changes.ts +33 -0
  16. package/src/core/env.ts +27 -0
  17. package/src/core/errors.ts +32 -0
  18. package/src/core/frontmatter.ts +47 -0
  19. package/src/core/fs.test.ts +38 -0
  20. package/src/core/fs.ts +92 -0
  21. package/src/core/index.ts +193 -0
  22. package/src/core/path.ts +45 -0
  23. package/src/core/projects.ts +90 -0
  24. package/src/core/text.ts +39 -0
  25. package/src/harness.ts +289 -0
  26. package/src/index.ts +69 -0
  27. package/src/mcp/connections.ts +441 -0
  28. package/src/mcp/manager.ts +130 -0
  29. package/src/mcp/oauth.ts +195 -0
  30. package/src/mcp/service.test.ts +376 -0
  31. package/src/mcp/service.ts +567 -0
  32. package/src/mcp/types.ts +105 -0
  33. package/src/memory/api.test.ts +82 -0
  34. package/src/memory/api.ts +287 -0
  35. package/src/memory/blocks.test.ts +78 -0
  36. package/src/memory/blocks.ts +406 -0
  37. package/src/memory/caller.ts +57 -0
  38. package/src/memory/dispatch.ts +59 -0
  39. package/src/memory/facts.test.ts +41 -0
  40. package/src/memory/facts.ts +248 -0
  41. package/src/memory/graph.ts +103 -0
  42. package/src/memory/health.test.ts +130 -0
  43. package/src/memory/health.ts +74 -0
  44. package/src/memory/maintainer.ts +272 -0
  45. package/src/memory/maintenance.test.ts +176 -0
  46. package/src/memory/maintenance.ts +330 -0
  47. package/src/memory/migrate.ts +79 -0
  48. package/src/memory/operations.ts +138 -0
  49. package/src/memory/proposals.test.ts +168 -0
  50. package/src/memory/proposals.ts +576 -0
  51. package/src/memory/recall.test.ts +104 -0
  52. package/src/memory/recall.ts +271 -0
  53. package/src/memory/references.ts +77 -0
  54. package/src/memory/runContext.ts +93 -0
  55. package/src/memory/secrets.ts +6 -0
  56. package/src/memory/store.test.ts +66 -0
  57. package/src/memory/store.ts +385 -0
  58. package/src/memory/wiki.test.ts +47 -0
  59. package/src/memory/wiki.ts +422 -0
  60. package/src/memory/wikiIndex.test.ts +88 -0
  61. package/src/memory/wikiIndex.ts +116 -0
  62. package/src/plugins/api.ts +181 -0
  63. package/src/plugins/attachments.test.ts +84 -0
  64. package/src/plugins/attachments.ts +128 -0
  65. package/src/plugins/builtin.ts +82 -0
  66. package/src/plugins/catalogue.test.ts +254 -0
  67. package/src/plugins/catalogue.ts +250 -0
  68. package/src/plugins/cli.ts +184 -0
  69. package/src/plugins/discover.ts +151 -0
  70. package/src/plugins/firstParty.test.ts +143 -0
  71. package/src/plugins/firstParty.ts +129 -0
  72. package/src/plugins/hooks.test.ts +250 -0
  73. package/src/plugins/hooks.ts +239 -0
  74. package/src/plugins/identity.ts +37 -0
  75. package/src/plugins/install.test.ts +107 -0
  76. package/src/plugins/install.ts +106 -0
  77. package/src/plugins/inventory.ts +123 -0
  78. package/src/plugins/manifest.ts +44 -0
  79. package/src/plugins/plugins.test.ts +205 -0
  80. package/src/plugins/plugins.ts +184 -0
  81. package/src/plugins/proposal.ts +121 -0
  82. package/src/plugins/runtime.test.ts +40 -0
  83. package/src/plugins/runtime.ts +82 -0
  84. package/src/plugins/trust.ts +142 -0
  85. package/src/plugins/types.ts +130 -0
  86. package/src/prompt/compile.test.ts +261 -0
  87. package/src/prompt/compile.ts +732 -0
  88. package/src/server/methods.ts +308 -0
  89. package/src/server/remote.ts +77 -0
  90. package/src/server/rpc.ts +116 -0
  91. package/src/server/serve.ts +28 -0
  92. package/src/server/server.test.ts +174 -0
  93. package/src/sessions/approvals.ts +118 -0
  94. package/src/sessions/contracts.ts +299 -0
  95. package/src/sessions/conversation.test.ts +150 -0
  96. package/src/sessions/extensionSession.test.ts +74 -0
  97. package/src/sessions/extensionUi.test.ts +65 -0
  98. package/src/sessions/extensionUi.ts +102 -0
  99. package/src/sessions/history.ts +51 -0
  100. package/src/sessions/lineageJoin.ts +75 -0
  101. package/src/sessions/policy.ts +32 -0
  102. package/src/sessions/pricing.ts +60 -0
  103. package/src/sessions/reasoningSummaries.ts +59 -0
  104. package/src/sessions/registry.ts +294 -0
  105. package/src/sessions/runIndex.ts +99 -0
  106. package/src/sessions/runStore.test.ts +152 -0
  107. package/src/sessions/runStore.ts +332 -0
  108. package/src/sessions/runner.ts +556 -0
  109. package/src/sessions/runtimeResources.test.ts +61 -0
  110. package/src/sessions/sessions.test.ts +434 -0
  111. package/src/sessions/sessions.ts +295 -0
  112. package/src/skills/registry.test.ts +104 -0
  113. package/src/skills/registry.ts +394 -0
  114. package/src/terminal/cli.ts +149 -0
  115. package/src/terminal/client.ts +74 -0
  116. package/src/terminal/controller.ts +227 -0
  117. package/src/terminal/piExtension.ts +208 -0
  118. package/src/terminal/pluginControl.test.ts +146 -0
  119. package/src/terminal/pluginMenu.ts +112 -0
  120. package/src/terminal/socket.ts +182 -0
  121. package/src/terminal/standalone.test.ts +115 -0
  122. package/src/terminal/standalone.ts +126 -0
  123. package/src/terminal/terminal.test.ts +302 -0
  124. package/src/terminal/terminals.ts +429 -0
  125. package/src/tools/askUser.ts +45 -0
  126. package/src/tools/definitions.ts +187 -0
  127. package/src/tools/memoryTools.ts +22 -0
  128. package/src/tools/pluginPropose.ts +41 -0
  129. package/src/tools/types.ts +36 -0
  130. package/src/web/safeRequest.ts +171 -0
  131. package/src/web/text.ts +53 -0
  132. package/src/web/tools.ts +134 -0
  133. package/src/web/web.test.ts +141 -0
@@ -0,0 +1,385 @@
1
+ // Canonical Wiki files under `<data root>/wiki/`. One global corpus: `home.md`, `library/**`,
2
+ // and `projects/<slug>/**` hold pages; `blocks/` holds memory blocks and `facts/` holds short
3
+ // typed facts; `raw/`, `revisions/`, `inbox/`, `operations/`, and `trash/` are shared. A page's Wiki path and
4
+ // namespace come from where its file lives, so they are never stored twice.
5
+ import { createHash } from 'node:crypto'
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs'
7
+ import { join, relative } from 'node:path'
8
+ import { stringify } from 'yaml'
9
+
10
+ import { DEFAULT_PRODUCT_NAME } from '../core/env'
11
+ import { invalid, notFound } from '../core/errors'
12
+ import * as frontmatter from '../core/frontmatter'
13
+ import { appendLine, atomicWrite, newId, now, readJson, safeId, writeJson } from '../core/fs'
14
+ import { comparePaths, compareText, lines, takeChars } from '../core/text'
15
+
16
+ export const ROOT_NAMESPACE = '/'
17
+ /** Pages that belong to no project. `/docs` (its name before storage version 3) is accepted as input. */
18
+ export const LIBRARY_NAMESPACE = '/library'
19
+ export const LAYOUT = ['blocks', 'facts', 'library', 'projects', 'raw', 'revisions', 'inbox', 'operations'] as const
20
+
21
+ export function wikiDir(root: string): string {
22
+ return join(root, 'wiki')
23
+ }
24
+
25
+ function createIfMissing(path: string, contents: string): void {
26
+ if (!existsSync(path)) atomicWrite(path, contents)
27
+ }
28
+
29
+ export const SCHEMA = `# Wiki schema
30
+
31
+ - One global Wiki. \`home.md\` is the Home page, \`library/\` holds pages that belong to no project, and \`projects/<slug>/\` is a project's namespace.
32
+ - Pages carry frontmatter \`id\`, \`title\`, \`type\`, \`updatedAt\`, \`sourceIds\`, \`links\`. The path and namespace come from the file's location.
33
+ - \`blocks/\` holds memory blocks that are always in an agent's or session's context: \`shared/\`, \`agents/<agent-id>/\`, and \`projects/<slug>/brief.md\`.
34
+ - \`facts/\` holds short typed facts with \`kind\`, \`namespace\`, \`confidence\`, \`status\`, and sources.
35
+ - Skills, prompts, and rules live in the registry (\`registry/\`); pages and facts link to them by id (\`skills/<name>\`).
36
+ - \`raw/\` holds immutable source snapshots; replacing a source creates a new version.
37
+ - Every change writes a snapshot and manifest entry in \`revisions/\`. Claims without verifiable evidence go to \`inbox/\`.
38
+ `
39
+
40
+ /** Creates the Wiki skeleton. Existing files are never replaced. */
41
+ export function ensureLayout(root: string, productName = DEFAULT_PRODUCT_NAME): void {
42
+ ensureLayoutAt(wikiDir(root), productName)
43
+ }
44
+
45
+ /** The skeleton in any folder, so a migration can stage it before it replaces the Wiki. */
46
+ export function ensureLayoutAt(directory: string, productName = DEFAULT_PRODUCT_NAME): void {
47
+ for (const part of LAYOUT) mkdirSync(join(directory, part), { recursive: true })
48
+ createIfMissing(
49
+ join(directory, 'home.md'),
50
+ `---\nid: home\ntitle: Home\ntype: summary\nsourceIds: []\nlinks: []\n---\n\n# Welcome\n\nThis is the shared ${productName} Wiki: memory blocks, knowledge, and the playbook every agent and session works from.\n`
51
+ )
52
+ createIfMissing(join(directory, 'index.md'), '# Wiki index\n\nNo pages yet.\n')
53
+ createIfMissing(join(directory, 'log.md'), '# Maintenance log\n\n')
54
+ createIfMissing(join(directory, 'schema.md'), SCHEMA)
55
+ }
56
+
57
+ // What a project's Links page says until something is recorded: a map of where the project's
58
+ // documents and notes are, not a copy of them.
59
+ const LINKS_PLACEHOLDER = 'Nothing recorded yet. List the documents, notes, and sources that matter for this project, one line each: a link or path, then what it is for and why it matters. Link to them; do not copy them here.'
60
+
61
+ /** The fixed pages every project namespace starts with, beside `overview`: file name, title, type. */
62
+ export const PROJECT_SKELETON = [
63
+ ['decisions', 'Decisions', 'decision'],
64
+ ['state', 'Current state', 'summary'],
65
+ ['open-questions', 'Open questions', 'question'],
66
+ ['links', 'Links', 'reference']
67
+ ] as const
68
+
69
+ function yamlText(text: string): string {
70
+ try {
71
+ return stringify(text, { lineWidth: 0 }).trimEnd()
72
+ } catch {
73
+ return 'Project'
74
+ }
75
+ }
76
+
77
+ /** Where a project's namespace lives, creating its overview page the first time. */
78
+ export function ensureProjectNamespace(root: string, slug: string, name: string): void {
79
+ const directory = join(wikiDir(root), 'projects', safeId(slug))
80
+ mkdirSync(directory, { recursive: true })
81
+ createIfMissing(
82
+ join(directory, 'overview.md'),
83
+ `---\nid: project-${slug}\ntitle: ${yamlText(name)}\ntype: project\nsourceIds: []\nlinks: []\n---\n\nOverview of the ${name.replaceAll('\n', ' ')} project.\n`
84
+ )
85
+ // One page per aspect, updated in place, so knowledge has a place to go before it exists.
86
+ for (const [file, title, pageType] of PROJECT_SKELETON) {
87
+ createIfMissing(
88
+ join(directory, `${file}.md`),
89
+ `---\nid: ${slug}-${file}\ntitle: ${yamlText(`${name}: ${title}`)}\ntype: ${pageType}\nsourceIds: [user]\nlinks:\n- toId: project-${slug}\n type: references\n---\n\n${file === 'links' ? LINKS_PLACEHOLDER : 'Nothing recorded yet.'}\n`
90
+ )
91
+ }
92
+ }
93
+
94
+ // ---- Locations ----------------------------------------------------------------
95
+
96
+ /** A page's Wiki path (`/projects/agent-x/architecture`) and namespace (`/projects/agent-x`). */
97
+ export interface Location {
98
+ path: string
99
+ namespace: string
100
+ }
101
+
102
+ /** Whether a page is part of a project's fixed skeleton (it may stand alone and start empty). */
103
+ export function isSkeleton(location: Location): boolean {
104
+ return location.namespace.startsWith('/projects/') && PROJECT_SKELETON.some(([file]) => location.path === `${location.namespace}/${file}`)
105
+ }
106
+
107
+ export function locate(wiki: string, file: string): Location {
108
+ const inside = relative(wiki, file)
109
+ const parts = (inside.startsWith('..') ? file : inside).split('/').filter(Boolean)
110
+ if (parts.length) parts[parts.length - 1] = parts[parts.length - 1].replace(/(?<=.)\.[^.]*$/, '')
111
+ const namespace = parts[0] === 'projects' && parts.length > 2 ? `/projects/${parts[1]}` : parts[0] === 'library' ? LIBRARY_NAMESPACE : ROOT_NAMESPACE
112
+ return { path: `/${parts.join('/')}`, namespace }
113
+ }
114
+
115
+ /**
116
+ * Folder that new pages in `namespace` are written to. Accepts `/`, `/library[/…]`, and
117
+ * `/projects/<slug>[/…]`; every segment must be a safe identifier.
118
+ */
119
+ export function namespaceDir(wiki: string, namespace: string): string {
120
+ const trimmed = namespace.trim().replace(/\/+$/, '')
121
+ if (!trimmed || trimmed === LIBRARY_NAMESPACE) return join(wiki, 'library')
122
+ const segments = trimmed.replace(/^\/+/, '').split('/')
123
+ if (segments[0] === 'docs') segments[0] = 'library'
124
+ for (const segment of segments) {
125
+ try {
126
+ safeId(segment)
127
+ } catch {
128
+ throw invalid(`${namespace} is not a valid Wiki namespace.`)
129
+ }
130
+ }
131
+ if (segments[0] === 'library' || (segments[0] === 'projects' && segments.length > 1)) return join(wiki, ...segments)
132
+ throw invalid(`${namespace} is not a Wiki namespace. Use /library or /projects/<project>.`)
133
+ }
134
+
135
+ /** `/projects/<slug>` for any path inside a project namespace. */
136
+ export function projectNamespaceOf(namespace: string): string | null {
137
+ const [first, slug] = namespace.replace(/^\/+/, '').split('/')
138
+ return first === 'projects' && slug ? `/projects/${slug}` : null
139
+ }
140
+
141
+ // ---- Pages ----------------------------------------------------------------------
142
+
143
+ export interface WikiLink {
144
+ fromId: string
145
+ toId: string
146
+ type: string
147
+ }
148
+
149
+ /** Page frontmatter. Older pages also carry `scope`; it is ignored and not written back. */
150
+ export interface Frontmatter {
151
+ id: string
152
+ title: string
153
+ type: string
154
+ updatedAt: string
155
+ sourceIds: string[]
156
+ links: WikiLink[]
157
+ }
158
+
159
+ export const PAGE_TYPES = ['project', 'person', 'concept', 'decision', 'summary', 'question', 'reference'] as const
160
+ export const LINK_TYPES = ['references', 'depends_on', 'supersedes', 'contradicts', 'produced_by', 'uses'] as const
161
+
162
+ export interface ParsedPage {
163
+ frontmatter: Frontmatter
164
+ body: string
165
+ path: string
166
+ location: Location
167
+ }
168
+
169
+ /** A string array field: absent is empty, anything else that is not a list of strings fails the parse. */
170
+ export function stringList(value: unknown): string[] | null {
171
+ if (value === undefined) return []
172
+ return Array.isArray(value) && value.every((item) => typeof item === 'string') ? (value as string[]) : null
173
+ }
174
+
175
+ /** A `links` field with the same rules: every entry needs `toId` and `type`. */
176
+ export function linkList(value: unknown, fromId: string): WikiLink[] | null {
177
+ if (value === undefined) return []
178
+ if (!Array.isArray(value)) return null
179
+ const links: WikiLink[] = []
180
+ for (const item of value) {
181
+ const link = item as { toId?: unknown; type?: unknown } | null
182
+ if (!link || typeof link !== 'object' || typeof link.toId !== 'string' || typeof link.type !== 'string') return null
183
+ if ((LINK_TYPES as readonly string[]).includes(link.type)) links.push({ fromId, toId: link.toId, type: link.type })
184
+ }
185
+ return links
186
+ }
187
+
188
+ export function parsePage(text: string, wiki: string, path: string): ParsedPage | null {
189
+ const parsed = frontmatter.parse(text)
190
+ if (!parsed) return null
191
+ const { id, title, type, updatedAt } = parsed.front
192
+ if (typeof id !== 'string' || typeof title !== 'string' || typeof type !== 'string') return null
193
+ if (updatedAt !== undefined && typeof updatedAt !== 'string') return null
194
+ if (!(PAGE_TYPES as readonly string[]).includes(type)) return null
195
+ const sourceIds = stringList(parsed.front.sourceIds)
196
+ const links = linkList(parsed.front.links, id)
197
+ if (!sourceIds || !links) return null
198
+ return { frontmatter: { id, title, type, updatedAt: updatedAt ?? '', sourceIds, links }, body: parsed.body, path, location: locate(wiki, path) }
199
+ }
200
+
201
+ export function serializePage(front: Frontmatter, body: string): string {
202
+ return frontmatter.serialize({ id: front.id, title: front.title, type: front.type, updatedAt: front.updatedAt, sourceIds: front.sourceIds, links: front.links }, body)
203
+ }
204
+
205
+ export function markdownFiles(directory: string, into: string[]): void {
206
+ let entries: string[]
207
+ try {
208
+ entries = readdirSync(directory)
209
+ } catch {
210
+ return
211
+ }
212
+ for (const name of entries) {
213
+ if (name.startsWith('.')) continue
214
+ const path = join(directory, name)
215
+ let directoryEntry = false
216
+ try {
217
+ directoryEntry = statSync(path).isDirectory()
218
+ } catch {
219
+ continue
220
+ }
221
+ if (directoryEntry) markdownFiles(path, into)
222
+ else if (name.endsWith('.md') && name.length > 3) into.push(path)
223
+ }
224
+ }
225
+
226
+ export function isFile(path: string): boolean {
227
+ try {
228
+ return statSync(path).isFile()
229
+ } catch {
230
+ return false
231
+ }
232
+ }
233
+
234
+ export function isDir(path: string): boolean {
235
+ try {
236
+ return statSync(path).isDirectory()
237
+ } catch {
238
+ return false
239
+ }
240
+ }
241
+
242
+ /** Every page file: Home, the Library, and project namespaces. */
243
+ export function pageFiles(wiki: string): string[] {
244
+ const files: string[] = []
245
+ if (isFile(join(wiki, 'home.md'))) files.push(join(wiki, 'home.md'))
246
+ markdownFiles(join(wiki, 'library'), files)
247
+ markdownFiles(join(wiki, 'projects'), files)
248
+ return files.sort(comparePaths)
249
+ }
250
+
251
+ export function loadPages(wiki: string): ParsedPage[] {
252
+ const pages: ParsedPage[] = []
253
+ for (const path of pageFiles(wiki)) {
254
+ let text: string
255
+ try {
256
+ text = readFileSync(path, 'utf8')
257
+ } catch {
258
+ continue
259
+ }
260
+ const page = parsePage(text, wiki, path)
261
+ if (page) pages.push(page)
262
+ }
263
+ return pages
264
+ }
265
+
266
+ export function firstParagraph(body: string): string {
267
+ const line = lines(body).map((entry) => entry.trim()).find((entry) => entry && !entry.startsWith('#')) ?? ''
268
+ return takeChars(line, 240)
269
+ }
270
+
271
+ export { slugify as slug } from '../core/projects'
272
+
273
+ // ---- Revisions --------------------------------------------------------------------
274
+
275
+ export interface WikiRevision {
276
+ id: string
277
+ pageId: string
278
+ createdAt: string
279
+ actor: string
280
+ reason: string
281
+ }
282
+
283
+ /** Revision folder for any entry: a page, a fact, a block (`blocks/shared/user`), or a registry item (`skills/<name>`). */
284
+ export function revisionsDir(wiki: string, entryId: string): string {
285
+ return join(wiki, 'revisions', safeId(entryId.replaceAll('/', '--')))
286
+ }
287
+
288
+ export function readManifest(wiki: string, entryId: string): WikiRevision[] {
289
+ return readJson<WikiRevision[]>(join(revisionsDir(wiki, entryId), 'manifest.json')) ?? []
290
+ }
291
+
292
+ export function currentRevision(wiki: string, entryId: string): string | null {
293
+ try {
294
+ return readManifest(wiki, entryId).at(-1)?.id ?? null
295
+ } catch {
296
+ return null
297
+ }
298
+ }
299
+
300
+ export function snapshot(wiki: string, entryId: string, contents: string, actor: string, reason: string): WikiRevision {
301
+ const directory = revisionsDir(wiki, entryId)
302
+ const revision: WikiRevision = { id: newId(), pageId: entryId, createdAt: now(), actor, reason }
303
+ atomicWrite(join(directory, `${revision.id}.md`), contents)
304
+ const manifest = readManifest(wiki, entryId)
305
+ manifest.push(revision)
306
+ writeJson(join(directory, 'manifest.json'), manifest)
307
+ return revision
308
+ }
309
+
310
+ export function revisionText(wiki: string, entryId: string, revisionId: string): string {
311
+ try {
312
+ return readFileSync(join(revisionsDir(wiki, entryId), `${safeId(revisionId)}.md`), 'utf8')
313
+ } catch {
314
+ throw notFound('Revision')
315
+ }
316
+ }
317
+
318
+ export function log(wiki: string, line: string): void {
319
+ appendLine(join(wiki, 'log.md'), line)
320
+ }
321
+
322
+ // ---- Sources ------------------------------------------------------------------------
323
+
324
+ export interface WikiSource {
325
+ id: string
326
+ name: string
327
+ importedAt: string
328
+ version: number
329
+ previousId: string | null
330
+ }
331
+
332
+ interface StoredSource extends WikiSource {
333
+ sha256: string
334
+ }
335
+
336
+ function storedSources(wiki: string): StoredSource[] {
337
+ let entries: string[]
338
+ try {
339
+ entries = readdirSync(join(wiki, 'raw'))
340
+ } catch {
341
+ return []
342
+ }
343
+ const sources: StoredSource[] = []
344
+ for (const name of entries) {
345
+ try {
346
+ const stored = readJson<StoredSource>(join(wiki, 'raw', name, 'meta.json'))
347
+ if (stored && typeof stored.id === 'string') sources.push(stored)
348
+ } catch {
349
+ // A source without readable metadata is not listed.
350
+ }
351
+ }
352
+ return sources.sort((left, right) => compareText(left.importedAt, right.importedAt))
353
+ }
354
+
355
+ const withoutHash = ({ sha256: _hash, ...source }: StoredSource): WikiSource => source
356
+
357
+ export function listSources(wiki: string): WikiSource[] {
358
+ return storedSources(wiki).map(withoutHash)
359
+ }
360
+
361
+ export function importSource(wiki: string, name: string, bytes: Uint8Array): WikiSource {
362
+ const hash = createHash('sha256').update(bytes).digest('hex')
363
+ const existing = storedSources(wiki)
364
+ const same = existing.find((source) => source.sha256 === hash)
365
+ if (same) return withoutHash(same)
366
+ const previous = existing.filter((source) => source.name === name).reduce<StoredSource | null>((best, source) => (!best || source.version >= best.version ? source : best), null)
367
+ const stored: StoredSource = {
368
+ id: `src-${hash.slice(0, 12)}`,
369
+ name,
370
+ importedAt: now(),
371
+ version: previous ? previous.version + 1 : 1,
372
+ previousId: previous?.id ?? null,
373
+ sha256: hash
374
+ }
375
+ const directory = join(wiki, 'raw', stored.id)
376
+ atomicWrite(join(directory, name), bytes)
377
+ writeJson(join(directory, 'meta.json'), stored)
378
+ log(wiki, `- ${stored.importedAt} · user · ingest · source \`${stored.id}\` (${stored.name}, v${stored.version})`)
379
+ return withoutHash(stored)
380
+ }
381
+
382
+ /** Evidence ids that need no local file: runs, URLs, and things the user accepted or wrote. */
383
+ export function isExternalEvidence(id: string): boolean {
384
+ return id.startsWith('run:') || id.startsWith('url:') || id.startsWith('user')
385
+ }
@@ -0,0 +1,47 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { afterEach, expect, test } from 'vitest'
4
+
5
+ import { dataRoot, writeWiki } from '../../tests/helpers'
6
+ import { closeIndex } from '../core/index'
7
+ import * as blocks from './blocks'
8
+ import { readManifest, snapshot, wikiDir } from './store'
9
+ import { resolveEntry, restore, scan } from './wiki'
10
+
11
+ const roots: string[] = []
12
+ afterEach(() => roots.splice(0).forEach(closeIndex))
13
+ const setup = (): string => {
14
+ const root = dataRoot()
15
+ roots.push(root)
16
+ return root
17
+ }
18
+
19
+ test('resolves pages, memories and registry items', () => {
20
+ const root = setup()
21
+ writeWiki(root, 'projects/app/arch.md', '---\nid: arch\ntitle: Architecture\ntype: concept\n---\n\nTauri.\n')
22
+ writeWiki(root, 'facts/pnpm.md', '---\nid: pnpm\ntitle: Use pnpm\nkind: preference\n---\n\nUse pnpm.\n')
23
+ mkdirSync(join(root, 'registry/skills/review'), { recursive: true })
24
+ writeFileSync(join(root, 'registry/skills/review/SKILL.md'), '---\nname: review\ndescription: Review code\n---\n\nSteps.\n')
25
+ expect(resolveEntry(root, 'arch').kind).toBe('page')
26
+ expect(resolveEntry(root, '/projects/app/arch').kind).toBe('page')
27
+ expect(resolveEntry(root, 'pnpm').kind).toBe('memory')
28
+ expect(resolveEntry(root, 'skills/review').kind).toBe('registry')
29
+ expect(() => resolveEntry(root, 'missing')).toThrow()
30
+ const kinds = scan(root).entries.map((entry) => entry.kind)
31
+ for (const kind of ['page', 'memory', 'skill']) expect(kinds).toContain(kind)
32
+ blocks.ensureUser(wikiDir(root))
33
+ expect(scan(root).entries.some((entry) => entry.kind === 'block' && entry.id === 'blocks/shared/user' && entry.entryType === 'shared')).toBe(true)
34
+ })
35
+
36
+ test('restores registry items through revisions', () => {
37
+ const root = setup()
38
+ mkdirSync(join(root, 'registry/rules'), { recursive: true })
39
+ const file = join(root, 'registry/rules/style.md')
40
+ writeFileSync(file, 'Use tabs.\n')
41
+ const wiki = wikiDir(root)
42
+ const first = snapshot(wiki, 'rules/style', 'Use tabs.\n', 'user', 'Original')
43
+ writeFileSync(file, 'Use spaces.\n')
44
+ restore(root, 'rules/style', first.id)
45
+ expect(readFileSync(file, 'utf8')).toBe('Use tabs.\n')
46
+ expect(readManifest(wiki, 'rules/style')).toHaveLength(3)
47
+ })