@joe-broadhead/opencode-mem 0.8.3 → 0.8.4

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.
package/src/tools/wiki.js CHANGED
@@ -1,12 +1,19 @@
1
1
  import { quarantineNote, quarantineText } from "../curation.js"
2
2
  import { RECORDS_FILE, RECORDS_WIKI, isRecordsText } from "../records.js"
3
+ import { codedMessage } from "../errors.js"
3
4
  import { errorMessage, neutralizeFenceClosers, oneLine, redactSecrets } from "../util.js"
4
5
  import { discoverKnowledge, isRecordsWikiName, searchKnowledge } from "./knowledge.js"
5
6
 
6
7
  const MAX_FILE_BYTES = 512 * 1024
7
8
  const DEFAULT_FILE = "README.md"
8
9
  /** The wiki actions that change knowledge; every other action only reads. */
9
- export const WIKI_WRITE_ACTIONS = Object.freeze(["create", "write", "append"])
10
+ export const WIKI_WRITE_ACTIONS = Object.freeze(["create", "write", "append", "delete"])
11
+ /** The actions that write a source file (delete has its own path). */
12
+ const FILE_WRITE_ACTIONS = Object.freeze(["create", "write", "append"])
13
+ /** The hub's structural pages, which page/rm refuses (PAGE_FORBIDDEN_REFS). */
14
+ const STRUCTURAL_PAGES = new Set(["index", "schema", "purpose"])
15
+ /** Pages a delete answer names; the rest are counted. */
16
+ const MAX_PAGES_NAMED = 5
10
17
  /** How much of a team write the approval shows. */
11
18
  const APPROVAL_EXCERPT_CHARS = 400
12
19
  const RECORDS_REFUSAL = `the "${RECORDS_WIKI}" wiki holds commitments; use mem_commitments to list, add, update, or delete them.`
@@ -14,6 +21,35 @@ const RECORDS_REFUSAL = `the "${RECORDS_WIKI}" wiki holds commitments; use mem_c
14
21
  const READ_HINT =
15
22
  "To read a wiki hit in full: mem_wiki with action \"read\", wiki_id = the hit's source, ref = the hit's path."
16
23
 
24
+ /**
25
+ * Flat names for the folders the page layout used to prescribe. The hub's
26
+ * `raw/write` creates `raw/sources/` but never a folder under it, so
27
+ * "projects/harbour.md" fails with ENOENT after the person approved it. Until
28
+ * authored pages land (docs/design/memory-tools-v1.md, P2), a source file
29
+ * name has no folder: "project-harbour.md".
30
+ */
31
+ const FLAT_PREFIXES = Object.freeze({
32
+ projects: "project",
33
+ people: "person",
34
+ teams: "team",
35
+ decisions: "decision",
36
+ runbooks: "runbook",
37
+ })
38
+
39
+ /** The flat source file name for a nested one: "projects/harbour.md" -> "project-harbour.md". */
40
+ export function flatFilename(filename) {
41
+ const parts = String(filename ?? "").split("/").filter(Boolean)
42
+ if (parts.length < 2) return parts.join("")
43
+ const [first, ...rest] = parts
44
+ const prefix = FLAT_PREFIXES[first.toLowerCase()] ?? first
45
+ return [prefix, ...rest].join("-")
46
+ }
47
+
48
+ /** The refusal for a source file name with a folder in it; nothing was asked or written. */
49
+ function nestedRefusal(action, filename) {
50
+ return `not written: source files cannot be in folders yet ("${oneLine(filename, 120)}"); the wiki cannot create the folder, so the ${action} would fail. Nothing was asked or written. Use a flat name, for example "${oneLine(flatFilename(filename), 120)}", and link pages by that name.`
51
+ }
52
+
17
53
  /**
18
54
  * `mem_wiki`: read, search, and write durable knowledge pages.
19
55
  *
@@ -36,14 +72,39 @@ export function registerWiki(editor, toolkit) {
36
72
  sharedScope,
37
73
  config,
38
74
  resolveSpace,
75
+ resolveReadSpace,
39
76
  resolvePrivateSpace,
40
77
  resolveWriteSpace,
41
78
  assertTeamWrite,
42
79
  runtime,
43
80
  } = toolkit
44
81
 
45
- function visibilityOf(input) {
46
- return input?.visibility === "private" ? "private" : "team"
82
+ /** The visibility the call asked for: private, team, or auto (the default). */
83
+ function requestedVisibility(input) {
84
+ const value = String(input?.visibility ?? "")
85
+ return value === "private" || value === "team" ? value : "auto"
86
+ }
87
+
88
+ /**
89
+ * The visibility a write or delete takes. As asked, or for auto the
90
+ * session's space, as recall reads it: a shared space bound to the session
91
+ * (or passed with `space`) is a team write that asks; otherwise the personal
92
+ * space. Without a control plane there is no shared space, so auto is
93
+ * private. Working out the kind never binds the session.
94
+ */
95
+ async function writeVisibility(input, context) {
96
+ const asked = requestedVisibility(input)
97
+ if (asked !== "auto") return { visibility: asked }
98
+ if (!control) return { visibility: "private" }
99
+ const requested = String(input?.space ?? "").trim()
100
+ try {
101
+ const spaceContext = requested
102
+ ? await runtime.resolveContext({ space: requested, agent: context?.agent })
103
+ : await runtime.sessionContext(context?.sessionID, context?.agent)
104
+ return { visibility: spaceContext?.space_kind === "shared" ? "team" : "private" }
105
+ } catch (error) {
106
+ return { error: errorMessage(error) }
107
+ }
47
108
  }
48
109
 
49
110
  function filenameOf(input) {
@@ -56,9 +117,10 @@ export function registerWiki(editor, toolkit) {
56
117
 
57
118
  /**
58
119
  * The source file a write or append changes. A model that read a page by the
59
- * path a search showed ("wiki/projects/harbour.md") passes that path back;
60
- * the source file is "projects/harbour.md". With no name at all a write is
61
- * refused rather than landing in README.md.
120
+ * path a search showed ("wiki/project-harbour.md") passes that path back;
121
+ * the source file is "project-harbour.md". With no name at all a write is
122
+ * refused rather than landing in README.md. A name with a folder in it is
123
+ * refused by the caller (`nestedRefusal`).
62
124
  */
63
125
  function writeTarget(input) {
64
126
  const given = input?.filename ?? input?.path ?? input?.ref
@@ -83,7 +145,8 @@ export function registerWiki(editor, toolkit) {
83
145
  }
84
146
  }
85
147
 
86
- async function resolveWrite(input, context, visibility, approval) {
148
+ /** The space a write or delete goes to, and its scope. Nothing is asked here. */
149
+ async function resolveWrite(input, context, visibility) {
87
150
  const resolved = await resolveWriteSpace(input, context, visibility)
88
151
  if (resolved.invalid) return { invalid: resolved.invalid }
89
152
  if (resolved.error) return { error: resolved.error }
@@ -91,18 +154,73 @@ export function registerWiki(editor, toolkit) {
91
154
  const scoped = spaceContext
92
155
  ? toolkit.scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
93
156
  : toolkit.scope({ sessionID: context?.sessionID, agent: context?.agent })
94
- // Every team-visible write asks for approval, in local mode too: mem_remember
95
- // and mem_forget already do, and the wiki is the more durable of the three.
96
- if (visibility === "team") {
97
- try {
98
- await assertTeamWrite(context, "wiki.write", [spaceContext?.space_id ?? "team"], approval)
99
- } catch (error) {
100
- return { denied: errorMessage(error) }
101
- }
102
- }
103
157
  return { spaceContext, scoped }
104
158
  }
105
159
 
160
+ /**
161
+ * Ask for a team write, once everything that could refuse it has passed.
162
+ * Every team-visible write asks, in local mode too: mem_remember and
163
+ * mem_forget already do, and the wiki is the more durable of the three.
164
+ * Returns the denial's words, or "".
165
+ */
166
+ async function approveWrite(context, visibility, spaceContext, approval) {
167
+ if (visibility !== "team") return ""
168
+ try {
169
+ await assertTeamWrite(context, "wiki.write", [spaceContext?.space_id ?? "team"], approval)
170
+ return ""
171
+ } catch (error) {
172
+ return errorMessage(error)
173
+ }
174
+ }
175
+
176
+ /**
177
+ * The wiki's status, or "" when it cannot be read. Only a definite
178
+ * "processing" refuses a write in advance; any other answer lets the write
179
+ * run, and the hub's own answer decides.
180
+ */
181
+ async function wikiStatus(scoped, wikiID) {
182
+ try {
183
+ const wiki = await backend.getWiki({ scope: scoped, wikiID })
184
+ return String(wiki?.status ?? "")
185
+ } catch {
186
+ return ""
187
+ }
188
+ }
189
+
190
+ /**
191
+ * The hub refuses every write and delete while a wiki ingests (`409 wiki is
192
+ * processing`), and an ingest follows every write by default, so a second
193
+ * write within minutes used to fail after the person had approved it.
194
+ */
195
+ function busyMessage(wikiID, asked, done = "written") {
196
+ return codedMessage(
197
+ "MEMORY_WIKI_BUSY",
198
+ `wiki ${oneLine(wikiID, 80)} is ingesting an earlier write (status: processing) and refuses writes and deletes until it finishes, usually within a few minutes; nothing was ${asked ? "" : "asked or "}${done}`,
199
+ "retry once mem_wiki status shows it ready. To write several files in a row, pass ingest: false on each write and ingest: true only on the last one",
200
+ )
201
+ }
202
+
203
+ /** A hub rejection of a wiki write or delete, in words that say what to do next. */
204
+ function hubFailure(error, wikiID, filename) {
205
+ const message = errorMessage(error)
206
+ const what = String(error?.what ?? message)
207
+ if (Number(error?.status) === 409 || /wiki is processing/i.test(what)) return text(busyMessage(wikiID, true))
208
+ // The hub's ENOENT names a path on its own disk: never repeat it.
209
+ if (/\bENOENT\b/.test(what)) {
210
+ return text(
211
+ codedMessage(
212
+ "MEMORY_WIKI_NO_FOLDERS",
213
+ `the wiki cannot create a folder for "${oneLine(filename, 120)}"; nothing was written`,
214
+ `use a flat name, for example "${oneLine(flatFilename(filename), 120)}"`,
215
+ ),
216
+ )
217
+ }
218
+ if (/invalid path/i.test(what)) {
219
+ return text(codedMessage("MEMORY_WIKI_INVALID_PATH", `the wiki refused "${oneLine(filename, 120)}" as a path; nothing was written`, "use a plain flat file name such as \"project-harbour.md\""))
220
+ }
221
+ return fail(message)
222
+ }
223
+
106
224
  /**
107
225
  * Register a new wiki in its space's control catalog. A gateway that has
108
226
  * the create hook (issue #2) already did it and says so with `resource_id`
@@ -134,6 +252,15 @@ export function registerWiki(editor, toolkit) {
134
252
  }
135
253
  }
136
254
 
255
+ /** What happens after a write, and how to write several files without the lock. */
256
+ function ingestNote(written) {
257
+ if (written.ingested) {
258
+ return "ingestion started (asynchronous); until it finishes the wiki refuses writes, so when writing several files pass ingest: false on each and ingest: true only on the last"
259
+ }
260
+ if (written.ingestError) return `ingestion not started (${written.ingestError}); the source file is written, and search finds it after the next ingest`
261
+ return "ingestion not started (ingest: false); pass ingest: true on the last write so search finds the changes"
262
+ }
263
+
137
264
  /**
138
265
  * The wiki a read or status names. Without `wiki_id`, the only wiki visible
139
266
  * in the scope is used and the answer says so; with several, the refusal
@@ -146,8 +273,14 @@ export function registerWiki(editor, toolkit) {
146
273
  if (ids.length === 1) return { wikiID: ids[0], note: `(wiki_id not given; using the only visible wiki, ${oneLine(ids[0], 80)})\n` }
147
274
  // No wiki at all: a read or status answers like list and search do (what
148
275
  // was checked, and that nothing more exists), so the agent does not list,
149
- // ask for a status, or search to make sure. A write keeps the refusal.
150
- if (ids.length === 0) return { empty: true, error: `wiki_id is required for ${action}; no wiki is visible in this scope` }
276
+ // ask for a status, or search to make sure. A write is refused with the
277
+ // call that makes the wiki: none exists until create runs.
278
+ if (ids.length === 0) {
279
+ return {
280
+ empty: true,
281
+ error: `not ${action === "append" ? "appended" : action === "delete" ? "deleted" : "written"}: no wiki exists in this space yet, so there is nothing to ${action}. Nothing was asked or written. Create the space's knowledge wiki first: mem_wiki with action "create", name "My knowledge" (in a shared space "<space name> knowledge"), filename "index.md", and content "# Index"; then ${action} the page.`,
282
+ }
283
+ }
151
284
  return {
152
285
  error: `wiki_id is required for ${action}; visible wikis: ${ids
153
286
  .slice(0, 10)
@@ -193,8 +326,10 @@ export function registerWiki(editor, toolkit) {
193
326
  const where = spaceContext ? toolkit.describeSpace(spaceContext) : "the local scope"
194
327
  const checked =
195
328
  input?.visibility === "private" || input?.visibility === "team"
196
- ? `only ${input.visibility} knowledge was checked; a list without visibility checks both`
197
- : "private and shared knowledge were both checked"
329
+ ? `only ${input.visibility} knowledge was checked${spaceContext ? "" : "; a list without visibility checks both"}`
330
+ : spaceContext
331
+ ? "the session's space was checked (a shared space bound to the session, else your personal space); pass space to check another"
332
+ : "private and shared knowledge were both checked"
198
333
  return `no accessible knowledge assets in ${where}: ${checked}. No wiki or page exists here yet, so there is nothing to read or search; listing again finds nothing more. Create the space's knowledge wiki with action "create" when a page is needed.`
199
334
  }
200
335
 
@@ -212,66 +347,313 @@ export function registerWiki(editor, toolkit) {
212
347
  }
213
348
  }
214
349
 
215
- /** What exists, so the next read can name it. */
350
+ /**
351
+ * What exists, so the next read can name it. The hub lists no pages while a
352
+ * wiki ingests (page/ls answers [] unless it is ready), which read as
353
+ * "pages: none" right after status had counted them; say why instead.
354
+ */
216
355
  async function notFound(scoped, wikiID, name) {
217
- const [pages, sources] = await Promise.all([
218
- orNull(backend.listWikiPages({ scope: scoped, wikiID })).catch(() => null),
219
- orNull(backend.knowledgeCall({ knowledgeID: wikiID, toolName: "list_raw", params: {}, scope: scoped })).catch(() => null),
356
+ const failed = Symbol("failed")
357
+ const [pages, sources, wiki] = await Promise.all([
358
+ orNull(backend.listWikiPages({ scope: scoped, wikiID })).catch(() => failed),
359
+ orNull(backend.knowledgeCall({ knowledgeID: wikiID, toolName: "list_raw", params: {}, scope: scoped })).catch(() => failed),
360
+ orNull(backend.getWiki({ scope: scoped, wikiID })).catch(() => null),
220
361
  ])
221
- const pageNames = (pages?.items ?? []).map((item) => item?.path ?? item?.id).filter(Boolean).slice(0, 15)
222
- const sourceNames = (Array.isArray(sources) ? sources : sources?.items ?? [])
223
- .map((item) => (typeof item === "string" ? item : item?.filename))
224
- .filter(Boolean)
225
- .slice(0, 15)
226
- const list = (names) => (names.length ? names.map((entry) => oneLine(entry, 120)).join(", ") : "none")
362
+ const status = String(wiki?.status ?? "")
363
+ const pageNames = pages === failed ? [] : (pages?.items ?? []).map((item) => item?.path ?? item?.id).filter(Boolean).slice(0, 15)
364
+ const sourceNames = sources === failed
365
+ ? []
366
+ : (Array.isArray(sources) ? sources : sources?.items ?? [])
367
+ .map((item) => (typeof item === "string" ? item : item?.filename))
368
+ .filter(Boolean)
369
+ .sort()
370
+ .slice(0, 15)
371
+ const list = (names) => names.map((entry) => oneLine(entry, 120)).join(", ")
372
+ let pageLine
373
+ if (pageNames.length) pageLine = list(pageNames)
374
+ else if (pages === failed) pageLine = "could not be listed now"
375
+ else if (status && status !== "ready") pageLine = `none listed while the wiki is ${oneLine(status, 40)}; pages are listed again once ingestion finishes (mem_wiki status shows ready). Source files read at once`
376
+ else if (Number(wiki?.page_count) > 0) pageLine = `none listed, though the wiki reports ${Number(wiki.page_count)}; read by filename meanwhile`
377
+ else pageLine = "none"
378
+ const sourceLine = sourceNames.length ? list(sourceNames) : sources === failed ? "could not be listed now" : "none"
227
379
  return (
228
380
  `not found in ${oneLine(wikiID, 80)}: ${oneLine(name, 120)}\n` +
229
- `pages (pass as ref): ${list(pageNames)}\n` +
230
- `source files (pass as filename): ${list(sourceNames)}`
381
+ `pages (pass as ref): ${pageLine}\n` +
382
+ `source files (pass as filename): ${sourceLine}`
231
383
  )
232
384
  }
233
385
 
386
+ /**
387
+ * The catalog row of a wiki in a control-plane space: the gateway's
388
+ * accessible-asset answer carries `resource_id` next to the wiki id.
389
+ */
390
+ async function catalogResourceOf(scoped, wikiID) {
391
+ const assets = await backend.listAccessibleAssets({ scope: scoped, assetType: "llm_wiki" })
392
+ const row = (assets?.items ?? []).find((asset) => String(asset?.content_ref ?? asset?.asset_id ?? "") === wikiID)
393
+ const id = typeof row?.resource_id === "string" ? row.resource_id.trim() : ""
394
+ return id || null
395
+ }
396
+
397
+ /** A whole wiki read back after a delete: gone is a 403 (no catalog row) or a 404. */
398
+ async function wikiGone(scoped, wikiID) {
399
+ try {
400
+ await backend.getWiki({ scope: scoped, wikiID })
401
+ return { gone: false, text: `wiki ${oneLine(wikiID, 80)} is still readable` }
402
+ } catch (error) {
403
+ const status = Number(error?.status)
404
+ if (status === 403 || status === 404) return { gone: true, text: `wiki ${oneLine(wikiID, 80)} is no longer reachable (${status})` }
405
+ return { gone: null, text: `the read-back failed (${errorMessage(error)})` }
406
+ }
407
+ }
408
+
409
+ /** A refusal of a delete by the hub or the gateway, in words that say what to do. */
410
+ function deleteFailure(error, wikiID, target) {
411
+ const what = String(error?.what ?? errorMessage(error))
412
+ if (Number(error?.status) === 409 || /wiki is processing/i.test(what)) return text(busyMessage(wikiID, true, "deleted"))
413
+ if (/endpoint_not_allowed|not available through the gateway/i.test(what)) {
414
+ return text(
415
+ codedMessage("MEMORY_WIKI_DELETE_UNAVAILABLE", "this Memory server does not allow wiki deletes yet (its gateway predates them); nothing was deleted", "ask the Memory server's operator to upgrade the gateway"),
416
+ )
417
+ }
418
+ if (/forbidden path/i.test(what)) {
419
+ return text(codedMessage("MEMORY_WIKI_STRUCTURAL", `"${oneLine(target, 120)}" is one of the wiki's structural pages (index, schema, purpose); nothing was deleted`, "delete a source file or another page"))
420
+ }
421
+ if (/invalid path/i.test(what)) return text(`not deleted: ${oneLine(target, 120)} was not found in wiki ${oneLine(wikiID, 80)}; nothing was deleted.`)
422
+ if (/resource_delete_forbidden|resource owner or a space owner or admin/i.test(what)) {
423
+ return text(`not deleted: only the wiki's owner or a space owner or admin can delete it. Nothing was deleted.`)
424
+ }
425
+ return fail(errorMessage(error))
426
+ }
427
+
428
+ /** Names of pages a delete removed or rewrote, bounded. */
429
+ function namedPages(list) {
430
+ const names = (Array.isArray(list) ? list : []).map((entry) => oneLine(typeof entry === "string" ? entry : entry?.ref ?? entry?.path ?? "", 120)).filter(Boolean)
431
+ if (names.length === 0) return ""
432
+ return `${names.slice(0, MAX_PAGES_NAMED).join(", ")}${names.length > MAX_PAGES_NAMED ? `, +${names.length - MAX_PAGES_NAMED} more` : ""}`
433
+ }
434
+
435
+ /**
436
+ * `mem_wiki` delete: one source file (`filename`), one generated page
437
+ * (`ref`), or a whole wiki (`wiki_id` alone). Without `confirm: true` it
438
+ * reads what would go and says so, changing nothing and asking nothing.
439
+ * With it, it always asks (`wiki.delete`, private or team), deletes, and
440
+ * reads the deletion back. A whole wiki in a control-plane space goes
441
+ * through the gateway's resource delete, so its catalog row goes with it.
442
+ */
443
+ async function deleteAction(input, context) {
444
+ const rawFilename = input?.filename === undefined || input?.filename === null ? "" : String(input.filename).trim()
445
+ const rawRef = String(input?.ref ?? input?.path ?? "").trim()
446
+ if (rawFilename && rawRef) {
447
+ return text("not deleted: delete takes one target: filename (a source file), ref (a generated page), or neither with wiki_id (the whole wiki). Nothing was asked or deleted.")
448
+ }
449
+ const kind = rawFilename ? "source" : rawRef ? "page" : "wiki"
450
+ const givenWiki = String(input?.wiki_id ?? "").trim()
451
+ if (kind === "wiki" && !givenWiki) {
452
+ return text(
453
+ "not deleted: name what to delete. filename deletes a source file, ref a generated page, and wiki_id alone the whole wiki (mem_wiki list shows the ids). Nothing was asked or deleted.",
454
+ )
455
+ }
456
+ let target = ""
457
+ if (kind === "source") {
458
+ target = filenameOf({ filename: rawFilename.replace(/^\/*wiki\//, "") })
459
+ if (!target) return text("invalid filename")
460
+ if (target === RECORDS_FILE) return text(`not deleted: ${RECORDS_REFUSAL}`)
461
+ } else if (kind === "page") {
462
+ if (rawRef.split("/").some((part) => part === "..")) return text("invalid ref")
463
+ target = oneLine(rawRef, 240)
464
+ if (STRUCTURAL_PAGES.has(target.replace(/^\/*wiki\//, "").replace(/\.md$/i, ""))) {
465
+ return text(`not deleted: "${target}" is one of the wiki's structural pages (index, schema, purpose), which the wiki keeps. Nothing was asked or deleted.`)
466
+ }
467
+ }
468
+ if (toolkit.runtime.records?.isRecordsWiki(givenWiki)) return text(`not deleted: ${RECORDS_REFUSAL}`)
469
+
470
+ const chosenVisibility = await writeVisibility(input, context)
471
+ if (chosenVisibility.error) return fail(chosenVisibility.error)
472
+ const { visibility } = chosenVisibility
473
+ const resolved = await resolveWrite(input, context, visibility)
474
+ if (resolved.invalid) return text(resolved.invalid)
475
+ if (resolved.error) return fail(resolved.error)
476
+ const { spaceContext, scoped } = resolved
477
+ const where = spaceContext ? toolkit.describeSpace(spaceContext) : "the local scope"
478
+
479
+ try {
480
+ const found = kind === "wiki" ? { wikiID: givenWiki, note: "" } : await wikiFor(input, scoped, "delete")
481
+ if (found.error) return text(found.error)
482
+ const { wikiID, note } = found
483
+ if (toolkit.runtime.records?.isRecordsWiki(wikiID)) return text(`not deleted: ${RECORDS_REFUSAL}`)
484
+
485
+ // What would go, read now, so the preview and the approval name it.
486
+ let subject
487
+ let resourceID = null
488
+ if (kind === "wiki") {
489
+ let wiki
490
+ try {
491
+ wiki = await backend.getWiki({ scope: scoped, wikiID })
492
+ } catch (error) {
493
+ if ([403, 404].includes(Number(error?.status))) return text(`not deleted: wiki ${oneLine(wikiID, 80)} was not found in ${where}. Nothing was asked or deleted.`)
494
+ throw error
495
+ }
496
+ if (isRecordsWikiName(wiki?.name)) {
497
+ toolkit.runtime.records?.noteRecordsWiki(wikiID)
498
+ return text(`not deleted: ${RECORDS_REFUSAL}`)
499
+ }
500
+ if (spaceContext && control) {
501
+ resourceID = await catalogResourceOf(scoped, wikiID)
502
+ if (!resourceID) return text(`not deleted: wiki ${oneLine(wikiID, 80)} is not in ${where}'s catalog, so it cannot be deleted from here. Nothing was asked or deleted.`)
503
+ const userId = spaceContext.user_id || runtime.config.user
504
+ try {
505
+ await control.deleteResource({ userId, spaceId: spaceContext.space_id, resourceId: resourceID, dryRun: true })
506
+ } catch (error) {
507
+ if ([400, 403, 404].includes(Number(error?.status))) return text(`not deleted: ${errorMessage(error)}. Nothing was asked or deleted.`)
508
+ throw error
509
+ }
510
+ }
511
+ const pages = Number(wiki?.page_count) || 0
512
+ subject = `the whole wiki ${oneLine(wikiID, 80)} (${oneLine(wiki?.name ?? "", 120)}${pages ? `, ${pages} pages` : ""}): every source file and page${resourceID ? ", and its catalog entry and grants" : ""}`
513
+ } else {
514
+ if ((await wikiStatus(scoped, wikiID)) === "processing") return text(busyMessage(wikiID, false, "deleted"))
515
+ const existing = kind === "source" ? await readSource(scoped, wikiID, target) : await readPage(scoped, wikiID, target)
516
+ if (!existing) return text(`${note}${await notFound(scoped, wikiID, target)}\nNothing was asked or deleted.`)
517
+ subject =
518
+ kind === "source"
519
+ ? `source file ${target} (${Buffer.byteLength(existing.content)} bytes) from wiki ${oneLine(wikiID, 80)}; the wiki also deletes the pages ingested only from it and rewrites the pages that cite it`
520
+ : `page ${target} from wiki ${oneLine(wikiID, 80)}; links to it on other pages are removed, and a page ingested from a source file comes back at the next ingest unless that file is deleted too`
521
+ }
522
+
523
+ if (input?.confirm !== true) {
524
+ return text(
525
+ `${note}Preview only: nothing was deleted and nothing was asked. In ${where}, mem_wiki delete with confirm: true would delete ${subject}. That call asks the person first, then reads the deletion back.`,
526
+ )
527
+ }
528
+
529
+ try {
530
+ await toolkit.assert({
531
+ sessionID: context?.sessionID,
532
+ agent: context?.agent,
533
+ source: { type: "tool", messageID: context?.messageID, id: context?.id },
534
+ action: "wiki.delete",
535
+ resources: [kind === "wiki" ? wikiID : `${wikiID}/${target}`],
536
+ save: [],
537
+ metadata: { kind: "wiki", target: kind, wiki: wikiID, ...(target ? { name: target } : {}), space: spaceContext?.space_id ?? "local", visibility },
538
+ })
539
+ } catch (error) {
540
+ return text(`wiki delete denied: ${errorMessage(error)}. Nothing was deleted.`)
541
+ }
542
+
543
+ if (kind === "wiki") {
544
+ if (resourceID) {
545
+ try {
546
+ const result = await control.deleteResource({ userId: spaceContext.user_id || runtime.config.user, spaceId: spaceContext.space_id, resourceId: resourceID })
547
+ if (result?.deleted !== true) return fail(`wiki ${oneLine(wikiID, 80)} was not deleted: the gateway did not confirm the delete.`)
548
+ } catch (error) {
549
+ return deleteFailure(error, wikiID, wikiID)
550
+ }
551
+ } else {
552
+ let data
553
+ try {
554
+ data = await backend.deleteWiki({ scope: scoped, wikiIDs: [wikiID] })
555
+ } catch (error) {
556
+ return deleteFailure(error, wikiID, wikiID)
557
+ }
558
+ const deleted = (data?.deleted_ids ?? []).map(String).includes(wikiID)
559
+ const missing = (data?.failed ?? []).some((entry) => String(entry?.id) === wikiID && /not\s*found/i.test(String(entry?.reason ?? "")))
560
+ if (!deleted && !missing) return fail(`wiki ${oneLine(wikiID, 80)} was not deleted: ${oneLine((data?.failed ?? [])[0]?.reason ?? "the wiki did not confirm it", 200)}.`)
561
+ }
562
+ const back = await wikiGone(scoped, wikiID)
563
+ log.info("wiki deleted", { wikiID, catalog: Boolean(resourceID), verified: back.gone })
564
+ if (back.gone === false) return fail(`wiki ${oneLine(wikiID, 80)}: the delete was reported, but ${back.text}. Report this to the Memory server's operator.`)
565
+ return text(`deleted the whole wiki ${oneLine(wikiID, 80)} from ${where}${resourceID ? ", with its catalog entry" : ""}. Read back: ${back.text}.`)
566
+ }
567
+
568
+ let data
569
+ try {
570
+ data =
571
+ kind === "source"
572
+ ? await backend.deleteWikiRaw({ scope: scoped, wikiID, filenames: [target] })
573
+ : await backend.deleteWikiPages({ scope: scoped, wikiID, refs: [target] })
574
+ } catch (error) {
575
+ log.warn("wiki delete failed", error)
576
+ return deleteFailure(error, wikiID, target)
577
+ }
578
+ const still = kind === "source" ? await readSource(scoped, wikiID, target) : await readPage(scoped, wikiID, target)
579
+ const cascade =
580
+ kind === "source"
581
+ ? [
582
+ namedPages(data?.deleted_pages) ? `It also deleted the pages ingested only from it: ${namedPages(data.deleted_pages)}.` : "",
583
+ Array.isArray(data?.rewritten_pages) && data.rewritten_pages.length ? `It rewrote ${data.rewritten_pages.length} page(s) that cited it.` : "",
584
+ ]
585
+ : [Array.isArray(data?.rewritten_files) && data.rewritten_files.length ? `It removed links to it from ${data.rewritten_files.length} file(s).` : ""]
586
+ log.info("wiki file deleted", { wikiID, kind, verified: !still })
587
+ if (still) return fail(`${kind === "source" ? "source file" : "page"} ${target} in wiki ${oneLine(wikiID, 80)}: the delete was reported, but it still reads back. Report this to the Memory server's operator.`)
588
+ return text(
589
+ `${note}deleted ${kind === "source" ? "source file" : "page"} ${target} from wiki ${oneLine(wikiID, 80)}. ${cascade.filter(Boolean).join(" ")}${cascade.some(Boolean) ? " " : ""}Read back: it is gone.`,
590
+ )
591
+ } catch (error) {
592
+ log.warn("wiki delete failed", error)
593
+ return fail(errorMessage(error))
594
+ }
595
+ }
596
+
234
597
  editor.add({
235
598
  name: "wiki",
236
599
  description:
237
- "Read, search, or write knowledge pages. Each space has one knowledge wiki (\"My knowledge\" in the personal space) holding index.md, log.md, projects/<slug>.md, people/<slug>.md (private only), teams/, decisions/, runbooks/, and glossary.md. Use list/search/read for documentation, architecture, ownership, runbooks, a project's status, and call-graph questions; read index.md before creating a page and extend an existing one. Use write to replace a page (one write per page per session) and append for log.md. Where a project stands goes in its page's dated Status section, replaced on update; things to do go in mem_commitments, never as a checklist on a page. A team write asks the person and shows the file and an excerpt.",
600
+ "Read, search, or write knowledge pages. A space has a knowledge wiki only once action create makes one (name it \"My knowledge\" in the personal space); list shows which wikis exist. Keep one knowledge wiki per space, holding flat source files: index.md, log.md, project-<slug>.md, person-<slug>.md (private only), team-<slug>.md, decision-<date>-<slug>.md, runbook-<slug>.md, and glossary.md (no folders: a name with a folder is refused). Use list/search/read for documentation, architecture, ownership, runbooks, a project's status, and call-graph questions; read index.md before creating a page and extend an existing one. Use write to replace a page (one write per page per session) and append for log.md. A write starts an ingest that locks the wiki for a few minutes: to write several files, pass ingest: false on each and ingest: true on the last. Where a project stands goes in its page's dated Status section, replaced on update; things to do go in mem_commitments, never as a checklist on a page. Like mem_recall it uses the session's space by default: your personal space, or a shared space bound to the session. A write to a shared space asks the person and shows the file and an excerpt; a write to your personal space does not. delete removes one source file (filename), one generated page (ref), or a whole wiki (wiki_id alone): without confirm it only previews; with confirm: true it always asks the person, then deletes and reads it back.",
238
601
  input: {
239
602
  type: "object",
240
603
  properties: {
241
604
  action: {
242
605
  type: "string",
243
- enum: ["list", "search", "create", "write", "append", "read", "status"],
606
+ enum: ["list", "search", "create", "write", "append", "read", "status", "delete"],
244
607
  description:
245
- 'Required. Read-only: list, search, read, status. Writes: create, write, append. Example: {"action": "search", "query": "onboarding guide"}',
608
+ 'Required. Read-only: list, search, read, status. Writes: create, write, append, delete. Example: {"action": "search", "query": "onboarding guide"}',
246
609
  },
247
610
  query: { type: "string", description: "Search query (required for action=search)" },
248
611
  knowledge_id: {
249
612
  type: "string",
250
613
  description: "Restrict a search to one id returned by action=list (the wiki/code-graph id, not an ACL asset id)",
251
614
  },
252
- wiki_id: { type: "string", description: "Wiki id for read/status/write/append; optional when exactly one wiki is visible (the answer names it)" },
615
+ wiki_id: {
616
+ type: "string",
617
+ description:
618
+ "Wiki id for read, status, write, append, and delete; optional when exactly one wiki is visible (the answer names it), except that deleting a whole wiki always names it",
619
+ },
253
620
  name: { type: "string", description: "Human-readable wiki name for action=create" },
254
621
  filename: {
255
622
  type: "string",
256
- description: `Source file to create, write, or append, for example "projects/harbour.md" (required for write and append; create defaults to ${DEFAULT_FILE}). Read takes it too. Path traversal is rejected`,
623
+ description: `Source file to create, write, or append, a flat name such as "project-harbour.md" (required for write and append; create defaults to ${DEFAULT_FILE}). No folders: "projects/harbour.md" is refused before anything is asked. Read takes it too, and delete takes it to delete one source file. Path traversal is rejected`,
257
624
  },
258
625
  content: {
259
626
  type: "string",
260
627
  description:
261
- "Markdown for create, write (replaces the file), or append. A project page (projects/<slug>.md) is: # Name; Updated YYYY-MM-DD · Owner · Tracker; ## Purpose; ## Status (as of YYYY-MM-DD), replaced on every update; ## Decisions (- YYYY-MM-DD: decision, because why); ## Open questions; ## People; ## Links; ## Log (one line appended per change). No checkboxes: things to do are mem_commitments",
628
+ "Markdown for create, write (replaces the file), or append. A project page (project-<slug>.md) is: # Name; Updated YYYY-MM-DD · Owner · Tracker; ## Purpose; ## Status (as of YYYY-MM-DD), replaced on every update; ## Decisions (- YYYY-MM-DD: decision, because why); ## Open questions; ## People; ## Links; ## Log (one line appended per change). No checkboxes: things to do are mem_commitments",
629
+ },
630
+ ingest: {
631
+ type: "boolean",
632
+ description:
633
+ "Start ingestion after create, write, or append (default true). The wiki refuses writes while it ingests (a few minutes), so to write several files pass ingest: false on each and ingest: true only on the last",
262
634
  },
263
- ingest: { type: "boolean", description: "Trigger extraction after write/append (default true)" },
264
635
  ref: {
265
636
  type: "string",
266
- description: "Page to read (action=read): the `path` a search hit shows (its source file is read first, so a page just written reads current), or a page id from status",
637
+ description:
638
+ "Page to read (action=read): the `path` a search hit shows (its source file is read first, so a page just written reads current), or a page id from status. Delete takes it to delete one generated page",
639
+ },
640
+ confirm: {
641
+ type: "boolean",
642
+ description:
643
+ "delete only: omitted or false previews what would go and changes nothing; true asks the person, deletes, and reads the deletion back. When the person asked for the delete, pass true; when you propose it, preview and ask them first",
267
644
  },
268
645
  path: { type: "string", description: "Same as ref: the page path a search hit shows" },
269
646
  visibility: {
270
647
  type: "string",
271
- enum: ["team", "private"],
272
- description: "team (default) uses shared knowledge; private uses your personal knowledge space. A list without visibility shows both",
648
+ enum: ["auto", "private", "team"],
649
+ description:
650
+ "auto (default), as mem_recall: the session's space, a shared space bound to the session or else your personal space; a write there is team (it asks) or private (it does not). private: your personal space. team: a shared space, bound or passed with space",
651
+ },
652
+ type: {
653
+ type: "string",
654
+ enum: ["wiki", "code-graph", "all"],
655
+ description: "Which knowledge list and search cover: wiki, code-graph, or all (the default)",
273
656
  },
274
- type: { type: "string", enum: ["wiki", "code-graph", "all"] },
275
657
  space: { type: "string", description: "Space id to browse or write (control plane); defaults to the active space" },
276
658
  },
277
659
  required: ["action"],
@@ -280,13 +662,23 @@ export function registerWiki(editor, toolkit) {
280
662
  options: { namespace: "mem" },
281
663
  execute: async (input, context) => {
282
664
  const action = String(input?.action ?? "list")
283
- const visibility = visibilityOf(input)
665
+ const asked = requestedVisibility(input)
666
+
667
+ if (action === "delete") return deleteAction(input, context)
284
668
 
285
- if (WIKI_WRITE_ACTIONS.includes(action)) {
669
+ if (FILE_WRITE_ACTIONS.includes(action)) {
286
670
  const content = String(input?.content ?? "")
287
671
  if (action !== "create" && !content.trim()) return text(`nothing to ${action}: content is empty`)
288
672
  if (Buffer.byteLength(content) > MAX_FILE_BYTES) return text("wiki content is too large (max 512 KB)")
289
- const target = action === "create" ? filenameOf(input) : writeTarget(input).filename ?? ""
673
+ // Everything that can be refused from the call alone is refused before
674
+ // anything is asked: a person never approves a write that cannot run.
675
+ if (action === "create" && !oneLine(input?.name, 200).trim()) return text("wiki name is required")
676
+ const createName = action === "create" ? filenameOf(input) : ""
677
+ const chosen = action !== "create" ? writeTarget(input) : createName ? { filename: createName } : { invalid: true }
678
+ if (chosen.missing) return text(`filename is required for ${action}: the source file, for example "project-harbour.md"`)
679
+ if (chosen.invalid) return text("invalid filename")
680
+ const target = chosen.filename
681
+ if (target.includes("/")) return text(nestedRefusal(action, target))
290
682
  // The records wiki is mem_commitments' store: never written here.
291
683
  if (
292
684
  (action === "create" && isRecordsWikiName(oneLine(input?.name, 200).trim())) ||
@@ -297,17 +689,19 @@ export function registerWiki(editor, toolkit) {
297
689
  return text(`not written: ${RECORDS_REFUSAL}`)
298
690
  }
299
691
 
300
- const resolved = await resolveWrite(input, context, visibility, approvalOf(action, input, target, content))
692
+ const chosenVisibility = await writeVisibility(input, context)
693
+ if (chosenVisibility.error) return fail(chosenVisibility.error)
694
+ const { visibility } = chosenVisibility
695
+ const resolved = await resolveWrite(input, context, visibility)
301
696
  if (resolved.invalid) return text(resolved.invalid)
302
697
  if (resolved.error) return fail(resolved.error)
303
- if (resolved.denied) return text(`wiki write denied: ${resolved.denied}`)
304
698
 
305
699
  try {
306
700
  if (action === "create") {
307
701
  const name = oneLine(input?.name, 200).trim()
308
- if (!name) return text("wiki name is required")
309
- const filename = filenameOf(input)
310
- if (!filename) return text("invalid filename")
702
+ const filename = target
703
+ const denied = await approveWrite(context, visibility, resolved.spaceContext, approvalOf(action, input, target, content))
704
+ if (denied) return text(`wiki write denied: ${denied}`)
311
705
  const wiki = await backend.createWiki({ scope: resolved.scoped, name })
312
706
  const wikiID = String(wiki?.wiki_id ?? "")
313
707
  if (!wikiID) throw new Error("wiki/create returned no wiki_id")
@@ -319,32 +713,28 @@ export function registerWiki(editor, toolkit) {
319
713
  `wiki ${wikiID} was created but resource registration failed: ${errorMessage(error)}. An operator must register it before the gateway can expose it.`,
320
714
  )
321
715
  }
322
- const written = await writeRaw(
323
- resolved.scoped,
324
- wikiID,
325
- filename,
326
- content || `# ${name}\n`,
327
- input?.ingest !== false,
328
- )
716
+ let written
717
+ try {
718
+ written = await writeRaw(resolved.scoped, wikiID, filename, content || `# ${name}\n`, input?.ingest !== false)
719
+ } catch (error) {
720
+ log.warn("wiki create write failed", error)
721
+ return hubFailure(error, wikiID, filename)
722
+ }
329
723
  log.info("wiki created", { wikiID, visibility, resource: resource?.id ?? null })
330
724
  return text(
331
- `created wiki ${wikiID} (${name}); wrote ${filename}; ${
332
- written.ingested ? "ingestion started (asynchronous)" : "ingestion not started"
333
- }${resource?.id ? `; resource ${resource.id}` : ""}`,
725
+ `created wiki ${wikiID} (${name}); wrote ${filename}; ${ingestNote(written)}${resource?.id ? `; resource ${resource.id}` : ""}`,
334
726
  )
335
727
  }
336
728
 
337
729
  // As read does: with one visible wiki, it is the target, and the
338
730
  // answer names it. With none or several, the refusal lists them.
339
- const target = await wikiFor(input, resolved.scoped, action)
340
- if (target.error) return text(target.error)
341
- const { wikiID, note } = target
731
+ const found = await wikiFor(input, resolved.scoped, action)
732
+ if (found.error) return text(found.error)
733
+ const { wikiID, note } = found
342
734
  if (toolkit.runtime.records?.isRecordsWiki(wikiID)) return text(`not written: ${RECORDS_REFUSAL}`)
343
- const chosen = writeTarget(input)
344
- if (chosen.missing) return text(`filename is required for ${action}: the source file, for example "projects/harbour.md"`)
345
- if (chosen.invalid) return text("invalid filename")
346
- const filename = chosen.filename
347
- if (filename === RECORDS_FILE) return text(`not written: ${RECORDS_REFUSAL}`)
735
+ const filename = target
736
+ // An ingesting wiki refuses the write: say so before anyone is asked.
737
+ if ((await wikiStatus(resolved.scoped, wikiID)) === "processing") return text(busyMessage(wikiID, false))
348
738
 
349
739
  let body = content
350
740
  if (action === "append") {
@@ -354,15 +744,21 @@ export function registerWiki(editor, toolkit) {
354
744
  if (Buffer.byteLength(body) > MAX_FILE_BYTES) return text("wiki file is too large after append")
355
745
  }
356
746
 
357
- const written = await writeRaw(resolved.scoped, wikiID, filename, body, input?.ingest !== false)
747
+ const denied = await approveWrite(context, visibility, resolved.spaceContext, approvalOf(action, input, target, content))
748
+ if (denied) return text(`wiki write denied: ${denied}`)
749
+ let written
750
+ try {
751
+ written = await writeRaw(resolved.scoped, wikiID, filename, body, input?.ingest !== false)
752
+ } catch (error) {
753
+ log.warn("wiki write failed", error)
754
+ return hubFailure(error, wikiID, filename)
755
+ }
358
756
  // Say what the write guarantees, so the agent does not read its own
359
757
  // write back to check it: the source file now holds exactly this.
360
758
  return text(
361
759
  `${note}${action === "append" ? "appended to" : "wrote"} ${filename} in wiki ${wikiID}: the source file now holds ${
362
760
  action === "append" ? "its earlier text and then" : "exactly"
363
- } the content you sent (${Buffer.byteLength(body)} bytes), and a read of it returns that; ${
364
- written.ingested ? "ingestion started (asynchronous)" : "ingestion not started"
365
- }${written.ingestError ? ` (${written.ingestError})` : ""}`,
761
+ } the content you sent (${Buffer.byteLength(body)} bytes), and a read of it returns that; ${ingestNote(written)}`,
366
762
  )
367
763
  } catch (error) {
368
764
  log.warn("wiki write failed", error)
@@ -370,10 +766,14 @@ export function registerWiki(editor, toolkit) {
370
766
  }
371
767
  }
372
768
 
769
+ // A read follows recall's rule: auto is the session's space (a bound
770
+ // shared space, else personal), and an explicit space never rebinds.
373
771
  const resolved =
374
- visibility === "private" && control
772
+ asked === "private" && control
375
773
  ? await resolvePrivateSpace(input, context)
376
- : await resolveSpace(input, context)
774
+ : asked === "auto" && control
775
+ ? await resolveReadSpace(input, context, "auto")
776
+ : await resolveSpace(input, context)
377
777
  if (resolved.invalid) return text(resolved.invalid)
378
778
  if (resolved.error) return fail(resolved.error)
379
779
  const spaceContext = resolved.context
@@ -382,7 +782,7 @@ export function registerWiki(editor, toolkit) {
382
782
  sessionID: input?.space ? undefined : context?.sessionID,
383
783
  agent: context?.agent,
384
784
  })
385
- : visibility === "private"
785
+ : asked === "private"
386
786
  ? toolkit.scope({ sessionID: context?.sessionID, agent: context?.agent })
387
787
  : sharedScope()
388
788
  const assetType = input?.type === "code-graph" ? "code_graph" : input?.type === "wiki" ? "llm_wiki" : undefined
@@ -402,7 +802,7 @@ export function registerWiki(editor, toolkit) {
402
802
  const seen = new Set()
403
803
  for (const asset of assets?.items ?? []) {
404
804
  if (asset.asset_type !== "llm_wiki" && asset.asset_type !== "code_graph") continue
405
- if (!spaceContext && visibility === "private" && asset.visibility !== "private") continue
805
+ if (!spaceContext && asked === "private" && asset.visibility !== "private") continue
406
806
  // An explicit "team" lists team assets only. With no visibility a
407
807
  // read lists everything the caller may read, as control mode does
408
808
  // (the active context is the personal space unless one is bound):
@@ -519,12 +919,14 @@ export function registerWiki(editor, toolkit) {
519
919
  backend.getWiki({ scope: scoped, wikiID }),
520
920
  backend.listWikiPages({ scope: scoped, wikiID }).catch(() => null),
521
921
  ])
522
- const pageCount = Array.isArray(pages?.items) ? pages.items.length : wiki?.page_count ?? 0
922
+ // While it ingests the hub lists no pages; its own count is the answer then.
923
+ const listed = Array.isArray(pages?.items) ? pages.items.length : 0
924
+ const pageCount = listed || Number(wiki?.page_count) || 0
925
+ const status = String(wiki?.status ?? "unknown")
523
926
  return text(
524
- `wiki: ${oneLine(wiki?.wiki_id ?? wikiID, 120)}\nname: ${oneLine(wiki?.name ?? "", 200)}\nstatus: ${oneLine(
525
- wiki?.status ?? "unknown",
526
- 40,
527
- )}\npages: ${pageCount}`,
927
+ `wiki: ${oneLine(wiki?.wiki_id ?? wikiID, 120)}\nname: ${oneLine(wiki?.name ?? "", 200)}\nstatus: ${oneLine(status, 40)}${
928
+ status === "processing" ? " (ingesting: writes and deletes are refused until it is ready)" : ""
929
+ }\npages: ${pageCount}`,
528
930
  )
529
931
  }
530
932