@joe-broadhead/opencode-mem 0.9.14 → 0.11.3

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 (143) hide show
  1. package/CHANGELOG.md +1856 -0
  2. package/README.md +15 -7
  3. package/SECURITY.md +3 -1
  4. package/docs/agent-instructions.md +1 -1
  5. package/docs/agent-protocol.md +7 -7
  6. package/docs/permissions.md +16 -0
  7. package/package.json +8921 -1070
  8. package/shared/page-paths.js +44 -0
  9. package/skills/mem.pages/SKILL.md +3 -1
  10. package/skills/mem.usage/SKILL.md +15 -15
  11. package/src/action-grant-keys.js +159 -0
  12. package/src/action-grant.js +439 -0
  13. package/src/actions.js +1690 -0
  14. package/src/backend/records.js +25 -2
  15. package/src/backend/v3.js +76 -22
  16. package/src/call-shapes.js +17 -16
  17. package/src/collector-lock.js +533 -62
  18. package/src/collector-service.js +153 -26
  19. package/src/collector.js +623 -30
  20. package/src/config.js +88 -7
  21. package/src/connect.js +106 -8
  22. package/src/credentials.js +123 -25
  23. package/src/events.js +174 -3
  24. package/src/forget-turn.js +141 -0
  25. package/src/host-refusal.js +78 -0
  26. package/src/index.js +209 -22
  27. package/src/jobs/host.js +557 -0
  28. package/src/ops/codes.js +110 -0
  29. package/src/ops/copy-lineage.js +42 -0
  30. package/src/ops/index.js +28 -0
  31. package/src/ops/space-ops.js +1936 -0
  32. package/src/outlinks.js +103 -0
  33. package/src/p2-reservation.js +151 -0
  34. package/src/permissions.js +30 -0
  35. package/src/plugins/descriptor.js +62 -0
  36. package/src/plugins/discovery.js +318 -0
  37. package/src/plugins/grants.js +178 -0
  38. package/src/plugins/locate.js +319 -0
  39. package/src/plugins/manifest.js +1162 -0
  40. package/src/plugins/source-contract/index.js +34 -0
  41. package/src/plugins/source-contract/policy.js +102 -0
  42. package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
  43. package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
  44. package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
  45. package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
  46. package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
  47. package/src/plugins/source-contract/vendor/broker-client.js +93 -0
  48. package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
  49. package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
  50. package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
  51. package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
  52. package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
  53. package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
  54. package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
  55. package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
  56. package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
  57. package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
  58. package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
  59. package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
  60. package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
  61. package/src/plugins/source-contract/vendor/cursor.js +26 -0
  62. package/src/plugins/source-contract/vendor/descriptor.js +34 -0
  63. package/src/plugins/source-contract/vendor/events.js +257 -0
  64. package/src/plugins/source-contract/vendor/index.js +10 -0
  65. package/src/plugins/source-contract/vendor/params.js +22 -0
  66. package/src/plugins/source-contract/vendor/permission.js +28 -0
  67. package/src/plugins/source-contract/vendor/pick.js +22 -0
  68. package/src/plugins/source-contract/vendor/read.js +29 -0
  69. package/src/plugins/source-contract/vendor/registry.js +23 -0
  70. package/src/plugins/source-contract/vendor/schema.js +17 -0
  71. package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
  72. package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
  73. package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
  74. package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
  75. package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
  76. package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
  77. package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
  78. package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
  79. package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
  80. package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
  81. package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
  82. package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
  83. package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
  84. package/src/plugins/source-contract/vendor/schemas.js +19 -0
  85. package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
  86. package/src/plugins/verify.js +56 -0
  87. package/src/protocol.js +11 -6
  88. package/src/recall.js +92 -5
  89. package/src/records.js +61 -2
  90. package/src/requests.js +216 -0
  91. package/src/runtime.js +89 -7
  92. package/src/setup-time.js +68 -0
  93. package/src/skills.js +230 -8
  94. package/src/source-ids.js +25 -0
  95. package/src/sources/declaration.js +365 -0
  96. package/src/sources/reads.js +772 -0
  97. package/src/sources/rpc.js +151 -0
  98. package/src/sources.js +389 -92
  99. package/src/spaces.js +283 -11
  100. package/src/spool.js +61 -4
  101. package/src/stated.js +10 -5
  102. package/src/storable.js +139 -0
  103. package/src/tools/commitments.js +74 -23
  104. package/src/tools/held-write.js +46 -19
  105. package/src/tools/index.js +28 -0
  106. package/src/tools/ingest.js +38 -2
  107. package/src/tools/memory.js +56 -25
  108. package/src/tools/page.js +212 -95
  109. package/src/tools/recall.js +218 -4
  110. package/src/tools/share.js +42 -3
  111. package/src/tools/shared.js +84 -6
  112. package/src/tools/space-lifecycle.js +278 -0
  113. package/src/tools/spaces.js +381 -30
  114. package/src/tools/status.js +9 -2
  115. package/src/tools/wiki.js +231 -116
  116. package/src/util.js +110 -6
  117. package/src/vendor/source-contract/README.md +24 -0
  118. package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
  119. package/src/vendor/source-contract/VENDOR.json +81 -0
  120. package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
  121. package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
  122. package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
  123. package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
  124. package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
  125. package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
  126. package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
  127. package/src/vendor/source-contract/cursor.js +26 -0
  128. package/src/vendor/source-contract/events.js +257 -0
  129. package/src/vendor/source-contract/registry.js +23 -0
  130. package/src/vendor/source-contract/tools-rpc.js +42 -0
  131. package/src/views/access-reads.js +256 -0
  132. package/src/views/communities.js +77 -0
  133. package/src/views/contracts.js +1082 -23
  134. package/src/views/inbox-bytes.js +103 -0
  135. package/src/views/profile.js +31 -0
  136. package/src/views/receipt.js +26 -1
  137. package/src/views/records-reads.js +520 -41
  138. package/src/views/rpc.js +153 -25
  139. package/src/views/shape.js +8 -5
  140. package/src/views/write-state.js +89 -0
  141. package/src/wiki-ingest.js +215 -0
  142. package/src/wiki-state.js +228 -0
  143. package/views/pages.html +2 -2
package/src/tools/wiki.js CHANGED
@@ -2,12 +2,18 @@ import { quarantineNote, quarantineText } from "../curation.js"
2
2
  import { RECORDS_FILE, RECORDS_WIKI, isRecordsText } from "../records.js"
3
3
  import { codedMessage } from "../errors.js"
4
4
  import { errorMessage, neutralizeFenceClosers, oneLine, redactSecrets } from "../util.js"
5
+ import { createWikiIngest, WIKI_INGEST_DELAY_MS } from "../wiki-ingest.js"
6
+ import { wikiCache, wikiErrorOf, wikiStateOf } from "../wiki-state.js"
5
7
  import { discoverKnowledge, isRecordsWikiName, searchKnowledge } from "./knowledge.js"
8
+ import { failedAnswer, refusedAnswer, wikiPlace, withWriteState } from "../views/write-state.js"
6
9
 
7
10
  const MAX_FILE_BYTES = 512 * 1024
8
11
  const DEFAULT_FILE = "README.md"
9
12
  /** The wiki actions that change knowledge; every other action only reads. */
10
13
  export const WIKI_WRITE_ACTIONS = Object.freeze(["create", "write", "append", "delete"])
14
+
15
+ /** The reads of mem_wiki, and all of `mem.wikis` (jelly #74). */
16
+ export const WIKI_READ_ACTIONS = Object.freeze(["list", "search", "read", "status"])
11
17
  /** The actions that write a source file (delete has its own path). */
12
18
  const FILE_WRITE_ACTIONS = Object.freeze(["create", "write", "append"])
13
19
  /** The hub's structural pages, which page/rm refuses (PAGE_FORBIDDEN_REFS). */
@@ -78,6 +84,33 @@ export function registerWiki(editor, toolkit) {
78
84
  runtime,
79
85
  } = toolkit
80
86
 
87
+ // 0.11.3 (jelly's #89 ask A4): a write's answer opens with its state line,
88
+ // and a refusal opens with `state: refused` and names nothing.
89
+ const refuse = (content) => refusedAnswer(text(content))
90
+ const failedCall = (message) => failedAnswer(fail(message))
91
+
92
+ /** The last ready page set of each wiki, and why an ingest failed (jelly #89 A1, A2). */
93
+ const cache = wikiCache({ stateDir: config.stateDir, log })
94
+
95
+ /**
96
+ * The write path (jelly #89 A3): every write schedules one debounced ingest,
97
+ * and a write the hub refuses during an ingest is queued, never refused.
98
+ * `toolkit.wikiIngest` lets the engine stop its timers with the tool set's.
99
+ */
100
+ const ingest =
101
+ toolkit.wikiIngest ??
102
+ createWikiIngest({
103
+ backend,
104
+ log,
105
+ delay: config.wikiIngestMs ?? WIKI_INGEST_DELAY_MS,
106
+ rememberError: (wikiID, message) => cache.rememberError(wikiID, message),
107
+ clearError: (wikiID) => cache.clearError(wikiID),
108
+ rememberPending: (wikiID, scope) => cache.rememberPending(wikiID, scope),
109
+ clearPending: (wikiID) => cache.clearPending(wikiID),
110
+ pending: () => cache.pending(),
111
+ })
112
+ toolkit.wikiIngest = ingest
113
+
81
114
  /** The visibility the call asked for: private, team, or auto (the default). */
82
115
  function requestedVisibility(input) {
83
116
  const value = String(input?.visibility ?? "")
@@ -184,15 +217,15 @@ export function registerWiki(editor, toolkit) {
184
217
  }
185
218
 
186
219
  /**
187
- * The hub refuses every write and delete while a wiki ingests (`409 wiki is
188
- * processing`), and an ingest follows every write by default, so a second
189
- * write within minutes used to fail after the person had approved it.
220
+ * The hub refuses a delete while a wiki ingests (`409 wiki is processing`).
221
+ * Writes no longer wait on that: a write during an ingest is queued
222
+ * (src/wiki-ingest.js), and the answer says so.
190
223
  */
191
224
  function busyMessage(wikiID, asked, done = "written") {
192
225
  return codedMessage(
193
226
  "MEMORY_WIKI_BUSY",
194
- `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}`,
195
- "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",
227
+ `wiki ${oneLine(wikiID, 80)} is ingesting an earlier write (status: processing) and refuses deletes until it finishes, usually within a few minutes; nothing was ${asked ? "" : "asked or "}${done}`,
228
+ "retry once mem_wiki status shows it ready",
196
229
  )
197
230
  }
198
231
 
@@ -200,10 +233,10 @@ export function registerWiki(editor, toolkit) {
200
233
  function hubFailure(error, wikiID, filename) {
201
234
  const message = errorMessage(error)
202
235
  const what = String(error?.what ?? message)
203
- if (Number(error?.status) === 409 || /wiki is processing/i.test(what)) return text(busyMessage(wikiID, true))
236
+ if (Number(error?.status) === 409 || /wiki is processing/i.test(what)) return refuse(busyMessage(wikiID, true))
204
237
  // The hub's ENOENT names a path on its own disk: never repeat it.
205
238
  if (/\bENOENT\b/.test(what)) {
206
- return text(
239
+ return refuse(
207
240
  codedMessage(
208
241
  "MEMORY_WIKI_NO_FOLDERS",
209
242
  `the wiki cannot create a folder for "${oneLine(filename, 120)}"; nothing was written`,
@@ -237,24 +270,34 @@ export function registerWiki(editor, toolkit) {
237
270
  })
238
271
  }
239
272
 
240
- async function writeRaw(scope, wikiID, filename, content, ingest) {
241
- await backend.writeWikiRaw({ scope, wikiID, files: [{ filename, content }] })
242
- if (ingest === false) return { ingested: false }
243
- try {
244
- await backend.ingestWiki({ scope, wikiID })
245
- return { ingested: true }
246
- } catch (error) {
247
- return { ingested: false, ingestError: errorMessage(error) }
248
- }
273
+ async function writeRaw(scope, wikiID, filename, content) {
274
+ return ingest.write({ scope, wikiID, filename, content })
249
275
  }
250
276
 
251
- /** What happens after a write, and how to write several files without the lock. */
277
+ /**
278
+ /**
279
+ * The state a written source file's answer opens with (0.11.3): the file is
280
+ * saved at once, so `processing` while the ingest it started makes search and
281
+ * the pages derived from it current, `failed` when that ingest did not start,
282
+ * and `stored` when no ingest was asked for.
283
+ */
284
+ function writtenState(written) {
285
+ if (written?.queued) return "queued"
286
+ // A3 starts an ingest after every write (ingest: false is ignored), so a
287
+ // write that landed is `processing` until that ingest finishes.
288
+ if (written?.ingestError) return "failed"
289
+ return "processing"
290
+ }
291
+
292
+ /**
293
+ * What happens after a write. `ingest: false` is accepted and ignored: the
294
+ * ingest starts on its own, so nothing here asks the agent to batch.
295
+ */
252
296
  function ingestNote(written) {
253
- if (written.ingested) {
254
- 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"
297
+ if (written.queued) {
298
+ return "the wiki is ingesting an earlier write, so this write is queued and is written when that ingest finishes, with one ingest after it; the queue lives only in this Memory process, so a restart before then loses this write, and the person should check the wiki afterwards"
255
299
  }
256
- if (written.ingestError) return `ingestion not started (${written.ingestError}); the source file is written, and search finds it after the next ingest`
257
- return "ingestion not started (ingest: false); pass ingest: true on the last write so search finds the changes"
300
+ return "ingestion starts on its own a moment after the last write, so a burst of writes makes one ingest; search finds the changes once it finishes"
258
301
  }
259
302
 
260
303
  /**
@@ -343,10 +386,18 @@ export function registerWiki(editor, toolkit) {
343
386
  }
344
387
  }
345
388
 
389
+ /** A page/ls answer as the cache keeps it: `{ ref, title }`, bounded. */
390
+ function listedPages(data) {
391
+ return (data?.items ?? [])
392
+ .map((item) => ({ ref: String(item?.path ?? item?.id ?? ""), title: oneLine(item?.title || item?.path || item?.id || "", 200) }))
393
+ .filter((page) => page.ref)
394
+ .slice(0, 100)
395
+ }
396
+
346
397
  /**
347
398
  * What exists, so the next read can name it. The hub lists no pages while a
348
- * wiki ingests (page/ls answers [] unless it is ready), which read as
349
- * "pages: none" right after status had counted them; say why instead.
399
+ * wiki ingests (page/ls answers [] unless it is ready); the last ready set
400
+ * this engine saw is listed instead, marked stale (jelly #89 A2).
350
401
  */
351
402
  async function notFound(scoped, wikiID, name) {
352
403
  const failed = Symbol("failed")
@@ -356,7 +407,9 @@ export function registerWiki(editor, toolkit) {
356
407
  orNull(backend.getWiki({ scope: scoped, wikiID })).catch(() => null),
357
408
  ])
358
409
  const status = String(wiki?.status ?? "")
410
+ const state = status ? wikiStateOf(wiki) : ""
359
411
  const pageNames = pages === failed ? [] : (pages?.items ?? []).map((item) => item?.path ?? item?.id).filter(Boolean).slice(0, 15)
412
+ if (pages !== failed && state === "ready") cache.rememberPages(wikiID, listedPages(pages))
360
413
  const sourceNames = sources === failed
361
414
  ? []
362
415
  : (Array.isArray(sources) ? sources : sources?.items ?? [])
@@ -365,10 +418,13 @@ export function registerWiki(editor, toolkit) {
365
418
  .sort()
366
419
  .slice(0, 15)
367
420
  const list = (names) => names.map((entry) => oneLine(entry, 120)).join(", ")
421
+ const staleNames = state && state !== "ready" ? cache.pages(wikiID).map((page) => page.ref).slice(0, 15) : []
368
422
  let pageLine
369
423
  if (pageNames.length) pageLine = list(pageNames)
370
424
  else if (pages === failed) pageLine = "could not be listed now"
371
- 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`
425
+ else if (staleNames.length) {
426
+ pageLine = `${list(staleNames)}. The wiki is ${oneLine(state, 40)}, so these are the last ready set, stale until it finishes; source files read at once`
427
+ } else if (status && state !== "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`
372
428
  else if (Number(wiki?.page_count) > 0) pageLine = `none listed, though the wiki reports ${Number(wiki.page_count)}; read by filename meanwhile`
373
429
  else pageLine = "none"
374
430
  const sourceLine = sourceNames.length ? list(sourceNames) : sources === failed ? "could not be listed now" : "none"
@@ -405,20 +461,20 @@ export function registerWiki(editor, toolkit) {
405
461
  /** A refusal of a delete by the hub or the gateway, in words that say what to do. */
406
462
  function deleteFailure(error, wikiID, target) {
407
463
  const what = String(error?.what ?? errorMessage(error))
408
- if (Number(error?.status) === 409 || /wiki is processing/i.test(what)) return text(busyMessage(wikiID, true, "deleted"))
464
+ if (Number(error?.status) === 409 || /wiki is processing/i.test(what)) return refuse(busyMessage(wikiID, true, "deleted"))
409
465
  if (/endpoint_not_allowed|not available through the gateway/i.test(what)) {
410
- return text(
466
+ return refuse(
411
467
  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"),
412
468
  )
413
469
  }
414
470
  if (/forbidden path/i.test(what)) {
415
- 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"))
471
+ return refuse(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"))
416
472
  }
417
- if (/invalid path/i.test(what)) return text(`not deleted: ${oneLine(target, 120)} was not found in wiki ${oneLine(wikiID, 80)}; nothing was deleted.`)
473
+ if (/invalid path/i.test(what)) return refuse(`not deleted: ${oneLine(target, 120)} was not found in wiki ${oneLine(wikiID, 80)}; nothing was deleted.`)
418
474
  if (/resource_delete_forbidden|resource owner or a space owner or admin/i.test(what)) {
419
- return text(`not deleted: only the wiki's owner or a space owner or admin can delete it. Nothing was deleted.`)
475
+ return refuse(`not deleted: only the wiki's owner or a space owner or admin can delete it. Nothing was deleted.`)
420
476
  }
421
- return fail(errorMessage(error))
477
+ return failedCall(errorMessage(error))
422
478
  }
423
479
 
424
480
  /** Names of pages a delete removed or rewrote, bounded. */
@@ -440,43 +496,43 @@ export function registerWiki(editor, toolkit) {
440
496
  const rawFilename = input?.filename === undefined || input?.filename === null ? "" : String(input.filename).trim()
441
497
  const rawRef = String(input?.ref ?? input?.path ?? "").trim()
442
498
  if (rawFilename && rawRef) {
443
- 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.")
499
+ return refuse("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.")
444
500
  }
445
501
  const kind = rawFilename ? "source" : rawRef ? "page" : "wiki"
446
502
  const givenWiki = String(input?.wiki_id ?? "").trim()
447
503
  if (kind === "wiki" && !givenWiki) {
448
- return text(
504
+ return refuse(
449
505
  "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.",
450
506
  )
451
507
  }
452
508
  let target = ""
453
509
  if (kind === "source") {
454
510
  target = filenameOf({ filename: rawFilename.replace(/^\/*wiki\//, "") })
455
- if (!target) return text("invalid filename")
456
- if (target === RECORDS_FILE) return text(`not deleted: ${RECORDS_REFUSAL}`)
511
+ if (!target) return refuse("invalid filename")
512
+ if (target === RECORDS_FILE) return refuse(`not deleted: ${RECORDS_REFUSAL}`)
457
513
  } else if (kind === "page") {
458
- if (rawRef.split("/").some((part) => part === "..")) return text("invalid ref")
514
+ if (rawRef.split("/").some((part) => part === "..")) return refuse("invalid ref")
459
515
  target = oneLine(rawRef, 240)
460
516
  if (STRUCTURAL_PAGES.has(target.replace(/^\/*wiki\//, "").replace(/\.md$/i, ""))) {
461
- 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.`)
517
+ return refuse(`not deleted: "${target}" is one of the wiki's structural pages (index, schema, purpose), which the wiki keeps. Nothing was asked or deleted.`)
462
518
  }
463
519
  }
464
- if (toolkit.runtime.records?.isRecordsWiki(givenWiki)) return text(`not deleted: ${RECORDS_REFUSAL}`)
520
+ if (toolkit.runtime.records?.isRecordsWiki(givenWiki)) return refuse(`not deleted: ${RECORDS_REFUSAL}`)
465
521
 
466
522
  const chosenVisibility = await writeVisibility(input, context)
467
- if (chosenVisibility.error) return fail(chosenVisibility.error)
523
+ if (chosenVisibility.error) return failedCall(chosenVisibility.error)
468
524
  const { visibility } = chosenVisibility
469
525
  const resolved = await resolveWrite(input, context, visibility)
470
- if (resolved.invalid) return text(resolved.invalid)
471
- if (resolved.error) return fail(resolved.error)
526
+ if (resolved.invalid) return refuse(resolved.invalid)
527
+ if (resolved.error) return failedCall(resolved.error)
472
528
  const { spaceContext, scoped } = resolved
473
529
  const where = spaceContext ? toolkit.describeSpace(spaceContext) : "the local scope"
474
530
 
475
531
  try {
476
532
  const found = kind === "wiki" ? { wikiID: givenWiki, note: "" } : await wikiFor(input, scoped, "delete")
477
- if (found.error) return text(found.error)
533
+ if (found.error) return refuse(found.error)
478
534
  const { wikiID, note } = found
479
- if (toolkit.runtime.records?.isRecordsWiki(wikiID)) return text(`not deleted: ${RECORDS_REFUSAL}`)
535
+ if (toolkit.runtime.records?.isRecordsWiki(wikiID)) return refuse(`not deleted: ${RECORDS_REFUSAL}`)
480
536
 
481
537
  // What would go, read now, so the preview and the approval name it.
482
538
  let subject
@@ -486,30 +542,30 @@ export function registerWiki(editor, toolkit) {
486
542
  try {
487
543
  wiki = await backend.getWiki({ scope: scoped, wikiID })
488
544
  } catch (error) {
489
- 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.`)
545
+ if ([403, 404].includes(Number(error?.status))) return refuse(`not deleted: wiki ${oneLine(wikiID, 80)} was not found in ${where}. Nothing was asked or deleted.`)
490
546
  throw error
491
547
  }
492
548
  if (isRecordsWikiName(wiki?.name)) {
493
549
  toolkit.runtime.records?.noteRecordsWiki(wikiID)
494
- return text(`not deleted: ${RECORDS_REFUSAL}`)
550
+ return refuse(`not deleted: ${RECORDS_REFUSAL}`)
495
551
  }
496
552
  if (spaceContext && control) {
497
553
  resourceID = await catalogResourceOf(scoped, wikiID)
498
- 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.`)
554
+ if (!resourceID) return refuse(`not deleted: wiki ${oneLine(wikiID, 80)} is not in ${where}'s catalog, so it cannot be deleted from here. Nothing was asked or deleted.`)
499
555
  const userId = spaceContext.user_id || runtime.config.user
500
556
  try {
501
557
  await control.deleteResource({ userId, spaceId: spaceContext.space_id, resourceId: resourceID, dryRun: true })
502
558
  } catch (error) {
503
- if ([400, 403, 404].includes(Number(error?.status))) return text(`not deleted: ${errorMessage(error)}. Nothing was asked or deleted.`)
559
+ if ([400, 403, 404].includes(Number(error?.status))) return refuse(`not deleted: ${errorMessage(error)}. Nothing was asked or deleted.`)
504
560
  throw error
505
561
  }
506
562
  }
507
563
  const pages = Number(wiki?.page_count) || 0
508
564
  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" : ""}`
509
565
  } else {
510
- if ((await wikiStatus(scoped, wikiID)) === "processing") return text(busyMessage(wikiID, false, "deleted"))
566
+ if ((await wikiStatus(scoped, wikiID)) === "processing") return refuse(busyMessage(wikiID, false, "deleted"))
511
567
  const existing = kind === "source" ? await readSource(scoped, wikiID, target) : await readPage(scoped, wikiID, target)
512
- if (!existing) return text(`${note}${await notFound(scoped, wikiID, target)}\nNothing was asked or deleted.`)
568
+ if (!existing) return refuse(`${note}${await notFound(scoped, wikiID, target)}\nNothing was asked or deleted.`)
513
569
  subject =
514
570
  kind === "source"
515
571
  ? `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`
@@ -517,8 +573,8 @@ export function registerWiki(editor, toolkit) {
517
573
  }
518
574
 
519
575
  if (input?.confirm !== true) {
520
- return text(
521
- `${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.`,
576
+ return refuse(
577
+ `${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. Only delete it if the person asked: a wiki or file you created by mistake is reported, and removed only if the person asks.`,
522
578
  )
523
579
  }
524
580
 
@@ -533,14 +589,14 @@ export function registerWiki(editor, toolkit) {
533
589
  metadata: { kind: "wiki", target: kind, wiki: wikiID, ...(target ? { name: target } : {}), space: spaceContext?.space_id ?? "local", visibility },
534
590
  })
535
591
  } catch (error) {
536
- return text(`wiki delete denied: ${errorMessage(error)}. Nothing was deleted.`)
592
+ return refuse(`wiki delete denied: ${errorMessage(error)}. Nothing was deleted.`)
537
593
  }
538
594
 
539
595
  if (kind === "wiki") {
540
596
  if (resourceID) {
541
597
  try {
542
598
  const result = await control.deleteResource({ userId: spaceContext.user_id || runtime.config.user, spaceId: spaceContext.space_id, resourceId: resourceID })
543
- if (result?.deleted !== true) return fail(`wiki ${oneLine(wikiID, 80)} was not deleted: the gateway did not confirm the delete.`)
599
+ if (result?.deleted !== true) return failedCall(`wiki ${oneLine(wikiID, 80)} was not deleted: the gateway did not confirm the delete.`)
544
600
  } catch (error) {
545
601
  return deleteFailure(error, wikiID, wikiID)
546
602
  }
@@ -553,12 +609,12 @@ export function registerWiki(editor, toolkit) {
553
609
  }
554
610
  const deleted = (data?.deleted_ids ?? []).map(String).includes(wikiID)
555
611
  const missing = (data?.failed ?? []).some((entry) => String(entry?.id) === wikiID && /not\s*found/i.test(String(entry?.reason ?? "")))
556
- if (!deleted && !missing) return fail(`wiki ${oneLine(wikiID, 80)} was not deleted: ${oneLine((data?.failed ?? [])[0]?.reason ?? "the wiki did not confirm it", 200)}.`)
612
+ if (!deleted && !missing) return failedCall(`wiki ${oneLine(wikiID, 80)} was not deleted: ${oneLine(errorMessage((data?.failed ?? [])[0]?.reason ?? "the wiki did not confirm it"), 200)}.`)
557
613
  }
558
614
  const back = await wikiGone(scoped, wikiID)
559
615
  log.info("wiki deleted", { wikiID, catalog: Boolean(resourceID), verified: back.gone })
560
- 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.`)
561
- return text(`deleted the whole wiki ${oneLine(wikiID, 80)} from ${where}${resourceID ? ", with its catalog entry" : ""}. Read back: ${back.text}.`)
616
+ if (back.gone === false) return failedCall(`wiki ${oneLine(wikiID, 80)}: the delete was reported, but ${back.text}. Report this to the Memory server's operator.`)
617
+ return withWriteState(text(`deleted the whole wiki ${oneLine(wikiID, 80)} from ${where}${resourceID ? ", with its catalog entry" : ""}. Read back: ${back.text}.`), { state: "ready" })
562
618
  }
563
619
 
564
620
  let data
@@ -580,20 +636,21 @@ export function registerWiki(editor, toolkit) {
580
636
  ]
581
637
  : [Array.isArray(data?.rewritten_files) && data.rewritten_files.length ? `It removed links to it from ${data.rewritten_files.length} file(s).` : ""]
582
638
  log.info("wiki file deleted", { wikiID, kind, verified: !still })
583
- 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.`)
584
- return text(
585
- `${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.`,
639
+ if (still) return failedCall(`${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.`)
640
+ return withWriteState(
641
+ text(`${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.`),
642
+ { state: "ready" },
586
643
  )
587
644
  } catch (error) {
588
645
  log.warn("wiki delete failed", error)
589
- return fail(errorMessage(error))
646
+ return failedCall(errorMessage(error))
590
647
  }
591
648
  }
592
649
 
593
- editor.add({
650
+ const wiki = {
594
651
  name: "wiki",
595
652
  description:
596
- "When asked to read a named document or wiki file, use mem_wiki read (or search to find it), even if mem_recall might answer. Call list, search and read for documentation, architecture, ownership and call-graph questions about what was uploaded or indexed. Write only documents the person gave you, as flat source files (\"notes.md\"; a name with a folder is refused). 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. 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. 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. Never put things to do (mem_commitments), where a project stands, or person and project pages (mem_page) here.",
653
+ "When asked to read a named document or wiki file, use mem_wiki read (or search to find it), even if mem_recall might answer. Call list, search and read for documentation, architecture, ownership and call-graph questions about what was uploaded or indexed. Write only documents the person gave you, as flat source files (\"notes.md\"; a name with a folder is refused). 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. A write starts one ingest by itself a moment after the last one; a write during an ingest is queued, not refused. 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. Never put things to do (mem_commitments), where a project stands, or person and project pages (mem_page) here.",
597
654
  input: {
598
655
  type: "object",
599
656
  properties: {
@@ -626,7 +683,7 @@ export function registerWiki(editor, toolkit) {
626
683
  ingest: {
627
684
  type: "boolean",
628
685
  description:
629
- "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",
686
+ "Ignored: ingestion always starts on its own a short while after the last write, so a burst of writes makes one ingest",
630
687
  },
631
688
  ref: {
632
689
  type: "string",
@@ -636,7 +693,7 @@ export function registerWiki(editor, toolkit) {
636
693
  confirm: {
637
694
  type: "boolean",
638
695
  description:
639
- "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",
696
+ "delete only: omitted or false previews what would go and changes nothing; true asks the person, deletes, and reads the deletion back. Pass true only when the person asked; one you propose is offered, never deleted",
640
697
  },
641
698
  path: { type: "string", description: "Same as ref: the page path a search hit shows" },
642
699
  visibility: {
@@ -659,22 +716,28 @@ export function registerWiki(editor, toolkit) {
659
716
  execute: async (input, context) => {
660
717
  const action = String(input?.action ?? "list")
661
718
  const asked = requestedVisibility(input)
719
+ // 0.11.3 (jelly's #89 ask A4): a write's answer opens with its state
720
+ // line, and a refusal opens with `state: refused` and names nothing. A
721
+ // read's answer is exactly what it was.
722
+ const isWrite = FILE_WRITE_ACTIONS.includes(action)
723
+ const answer = (content) => (isWrite ? refusedAnswer(text(content)) : text(content))
724
+ const failure = (message) => (isWrite ? failedAnswer(fail(message)) : fail(message))
662
725
 
663
726
  if (action === "delete") return deleteAction(input, context)
664
727
 
665
728
  if (FILE_WRITE_ACTIONS.includes(action)) {
666
729
  const content = String(input?.content ?? "")
667
- if (action !== "create" && !content.trim()) return text(`nothing to ${action}: content is empty`)
668
- if (Buffer.byteLength(content) > MAX_FILE_BYTES) return text("wiki content is too large (max 512 KB)")
730
+ if (action !== "create" && !content.trim()) return answer(`nothing to ${action}: content is empty`)
731
+ if (Buffer.byteLength(content) > MAX_FILE_BYTES) return answer("wiki content is too large (max 512 KB)")
669
732
  // Everything that can be refused from the call alone is refused before
670
733
  // anything is asked: a person never approves a write that cannot run.
671
- if (action === "create" && !oneLine(input?.name, 200).trim()) return text("wiki name is required")
734
+ if (action === "create" && !oneLine(input?.name, 200).trim()) return answer("wiki name is required")
672
735
  const createName = action === "create" ? filenameOf(input) : ""
673
736
  const chosen = action !== "create" ? writeTarget(input) : createName ? { filename: createName } : { invalid: true }
674
- if (chosen.missing) return text(`filename is required for ${action}: the source file, for example "project-harbour.md"`)
675
- if (chosen.invalid) return text("invalid filename")
737
+ if (chosen.missing) return answer(`filename is required for ${action}: the source file, for example "project-harbour.md"`)
738
+ if (chosen.invalid) return answer("invalid filename")
676
739
  const target = chosen.filename
677
- if (target.includes("/")) return text(nestedRefusal(action, target))
740
+ if (target.includes("/")) return answer(nestedRefusal(action, target))
678
741
  // The records wiki is mem_commitments' store: never written here.
679
742
  if (
680
743
  (action === "create" && isRecordsWikiName(oneLine(input?.name, 200).trim())) ||
@@ -682,22 +745,22 @@ export function registerWiki(editor, toolkit) {
682
745
  target === RECORDS_FILE ||
683
746
  isRecordsText(content)
684
747
  ) {
685
- return text(`not written: ${RECORDS_REFUSAL}`)
748
+ return answer(`not written: ${RECORDS_REFUSAL}`)
686
749
  }
687
750
 
688
751
  const chosenVisibility = await writeVisibility(input, context)
689
- if (chosenVisibility.error) return fail(chosenVisibility.error)
752
+ if (chosenVisibility.error) return failure(chosenVisibility.error)
690
753
  const { visibility } = chosenVisibility
691
754
  const resolved = await resolveWrite(input, context, visibility)
692
- if (resolved.invalid) return text(resolved.invalid)
693
- if (resolved.error) return fail(resolved.error)
755
+ if (resolved.invalid) return answer(resolved.invalid)
756
+ if (resolved.error) return failure(resolved.error)
694
757
 
695
758
  try {
696
759
  if (action === "create") {
697
760
  const name = oneLine(input?.name, 200).trim()
698
761
  const filename = target
699
762
  const denied = await approveWrite(context, visibility, resolved.spaceContext, approvalOf(action, input, target, content))
700
- if (denied) return text(`wiki write denied: ${denied}`)
763
+ if (denied) return answer(`wiki write denied: ${denied}`)
701
764
  const wiki = await backend.createWiki({ scope: resolved.scoped, name })
702
765
  const wikiID = String(wiki?.wiki_id ?? "")
703
766
  if (!wikiID) throw new Error("wiki/create returned no wiki_id")
@@ -705,60 +768,69 @@ export function registerWiki(editor, toolkit) {
705
768
  try {
706
769
  resource = await registerWikiResource(resolved.spaceContext, wiki, name)
707
770
  } catch (error) {
708
- return fail(
771
+ return failure(
709
772
  `wiki ${wikiID} was created but resource registration failed: ${errorMessage(error)}. An operator must register it before the gateway can expose it.`,
710
773
  )
711
774
  }
712
775
  let written
713
776
  try {
714
- written = await writeRaw(resolved.scoped, wikiID, filename, content || `# ${name}\n`, input?.ingest !== false)
777
+ written = await writeRaw(resolved.scoped, wikiID, filename, content || `# ${name}\n`)
715
778
  } catch (error) {
716
779
  log.warn("wiki create write failed", error)
717
780
  return hubFailure(error, wikiID, filename)
718
781
  }
719
782
  log.info("wiki created", { wikiID, visibility, resource: resource?.id ?? null })
720
- return text(
721
- `created wiki ${wikiID} (${name}); wrote ${filename}; ${ingestNote(written)}${resource?.id ? `; resource ${resource.id}` : ""}`,
783
+ return withWriteState(
784
+ text(`created wiki ${wikiID} (${name}); wrote ${filename}; ${ingestNote(written)}${resource?.id ? `; resource ${resource.id}` : ""}`),
785
+ { state: writtenState(written), id: `${wikiID}/${filename}`, link: wikiPlace(wikiID, filename) },
722
786
  )
723
787
  }
724
788
 
725
789
  // As read does: with one visible wiki, it is the target, and the
726
790
  // answer names it. With none or several, the refusal lists them.
727
791
  const found = await wikiFor(input, resolved.scoped, action)
728
- if (found.error) return text(found.error)
792
+ if (found.error) return answer(found.error)
729
793
  const { wikiID, note } = found
730
- if (toolkit.runtime.records?.isRecordsWiki(wikiID)) return text(`not written: ${RECORDS_REFUSAL}`)
794
+ if (toolkit.runtime.records?.isRecordsWiki(wikiID)) return answer(`not written: ${RECORDS_REFUSAL}`)
731
795
  const filename = target
732
- // An ingesting wiki refuses the write: say so before anyone is asked.
733
- if ((await wikiStatus(resolved.scoped, wikiID)) === "processing") return text(busyMessage(wikiID, false))
734
-
735
796
  let body = content
736
797
  if (action === "append") {
737
798
  const existing = await backend.readWikiRaw({ scope: resolved.scoped, wikiID, filenames: [filename] })
738
799
  const current = (existing?.items ?? []).find((item) => item?.filename === filename)?.content ?? ""
739
800
  body = current ? `${current.replace(/\s+$/, "")}\n\n${content}` : content
740
- if (Buffer.byteLength(body) > MAX_FILE_BYTES) return text("wiki file is too large after append")
801
+ if (Buffer.byteLength(body) > MAX_FILE_BYTES) return answer("wiki file is too large after append")
741
802
  }
742
803
 
743
804
  const denied = await approveWrite(context, visibility, resolved.spaceContext, approvalOf(action, input, target, content))
744
- if (denied) return text(`wiki write denied: ${denied}`)
805
+ if (denied) return answer(`wiki write denied: ${denied}`)
745
806
  let written
746
807
  try {
747
- written = await writeRaw(resolved.scoped, wikiID, filename, body, input?.ingest !== false)
808
+ written = await writeRaw(resolved.scoped, wikiID, filename, body)
748
809
  } catch (error) {
749
810
  log.warn("wiki write failed", error)
750
811
  return hubFailure(error, wikiID, filename)
751
812
  }
752
813
  // Say what the write guarantees, so the agent does not read its own
753
814
  // write back to check it: the source file now holds exactly this.
754
- return text(
755
- `${note}${action === "append" ? "appended to" : "wrote"} ${filename} in wiki ${wikiID}: the source file now holds ${
756
- action === "append" ? "its earlier text and then" : "exactly"
757
- } the content you sent (${Buffer.byteLength(body)} bytes), and a read of it returns that; ${ingestNote(written)}`,
815
+ // A queued write guarantees nothing yet: the wiki is ingesting.
816
+ if (written.queued) {
817
+ const what = action === "append" ? "the append to" : ""
818
+ return withWriteState(
819
+ text(`${note}queued ${what ? `${what} ` : ""}${filename} in wiki ${wikiID} (${Buffer.byteLength(body)} bytes); ${ingestNote(written)}`),
820
+ { state: writtenState(written), id: `${wikiID}/${filename}`, link: wikiPlace(wikiID, filename) },
821
+ )
822
+ }
823
+ return withWriteState(
824
+ text(
825
+ `${note}${action === "append" ? "appended to" : "wrote"} ${filename} in wiki ${wikiID}: the source file now holds ${
826
+ action === "append" ? "its earlier text and then" : "exactly"
827
+ } the content you sent (${Buffer.byteLength(body)} bytes), and a read of it returns that; ${ingestNote(written)}`,
828
+ ),
829
+ { state: writtenState(written), id: `${wikiID}/${filename}`, link: wikiPlace(wikiID, filename) },
758
830
  )
759
831
  } catch (error) {
760
832
  log.warn("wiki write failed", error)
761
- return fail(errorMessage(error))
833
+ return failure(errorMessage(error))
762
834
  }
763
835
  }
764
836
 
@@ -770,8 +842,8 @@ export function registerWiki(editor, toolkit) {
770
842
  : asked === "auto" && control
771
843
  ? await resolveReadSpace(input, context, "auto")
772
844
  : await resolveSpace(input, context)
773
- if (resolved.invalid) return text(resolved.invalid)
774
- if (resolved.error) return fail(resolved.error)
845
+ if (resolved.invalid) return answer(resolved.invalid)
846
+ if (resolved.error) return failure(resolved.error)
775
847
  const spaceContext = resolved.context
776
848
  const scoped = spaceContext
777
849
  ? toolkit.scopeFor(spaceContext, {
@@ -827,6 +899,7 @@ export function registerWiki(editor, toolkit) {
827
899
  )}`,
828
900
  )
829
901
  }
902
+ const wikiByID = new Map()
830
903
  for (const wiki of wikis?.items ?? []) {
831
904
  const wikiID = String(wiki.wiki_id ?? "")
832
905
  if (!wikiID || seen.has(wikiID)) continue
@@ -836,10 +909,11 @@ export function registerWiki(editor, toolkit) {
836
909
  continue
837
910
  }
838
911
  seen.add(wikiID)
912
+ wikiByID.set(wikiID, wiki)
839
913
  lines.push(
840
914
  `- ${neutralizeFenceClosers(oneLine(wikiID, 120))} [wiki] ${neutralizeFenceClosers(
841
915
  oneLine(wiki.name ?? "", 200),
842
- )} (${neutralizeFenceClosers(oneLine(wiki.status ?? "?", 40))}${wiki.page_count ? `, ${wiki.page_count} pages` : ""})`,
916
+ )} (${neutralizeFenceClosers(oneLine(wikiStateOf(wiki), 40))}${wiki.page_count ? `, ${wiki.page_count} pages` : ""})`,
843
917
  )
844
918
  }
845
919
  for (const graph of graphs?.items ?? []) {
@@ -852,7 +926,7 @@ export function registerWiki(editor, toolkit) {
852
926
  )} (${neutralizeFenceClosers(oneLine(graph.status ?? "?", 40))})`,
853
927
  )
854
928
  }
855
- if (lines.length === 0) return text(emptyKnowledge(input, spaceContext))
929
+ if (lines.length === 0) return answer(emptyKnowledge(input, spaceContext))
856
930
  // Each wiki's source files, so the next call can read a page by name
857
931
  // (filename) instead of searching for its path first. Bounded: the
858
932
  // first five wikis, fifteen names each.
@@ -860,21 +934,33 @@ export function registerWiki(editor, toolkit) {
860
934
  const listed = await Promise.all(wikiRows.slice(0, 5).map((row) => sourceFiles(scoped, row.id)))
861
935
  wikiRows.slice(0, 5).forEach((row, index) => {
862
936
  const { names, more } = listed[index]
863
- if (names.length === 0) return
864
- lines[row.index] = `${row.line}\n files (pass as filename): ${names.map((name) => neutralizeFenceClosers(oneLine(name, 120))).join(", ")}${more ? `, +${more} more` : ""}`
937
+ const extra = []
938
+ if (names.length > 0) {
939
+ extra.push(` files (pass as filename): ${names.map((name) => neutralizeFenceClosers(oneLine(name, 120))).join(", ")}${more ? `, +${more} more` : ""}`)
940
+ }
941
+ // While a wiki ingests the hub lists no pages; the last ready set
942
+ // this engine saw is listed instead, saying it is stale (A2).
943
+ const state = wikiByID.has(row.id) ? wikiStateOf(wikiByID.get(row.id)) : "ready"
944
+ const stale = state === "ready" ? [] : cache.pages(row.id).slice(0, 10)
945
+ if (stale.length > 0) {
946
+ extra.push(
947
+ ` pages (pass as ref): ${stale.map((page) => neutralizeFenceClosers(oneLine(page.ref, 120))).join(", ")}. The wiki is ${oneLine(state, 40)}, so these are the last ready set, stale until it finishes.`,
948
+ )
949
+ }
950
+ if (extra.length > 0) lines[row.index] = `${row.line}\n${extra.join("\n")}`
865
951
  })
866
- return text(["<knowledge_assets>", ...lines, "</knowledge_assets>"].join("\n"))
952
+ return answer(["<knowledge_assets>", ...lines, "</knowledge_assets>"].join("\n"))
867
953
  }
868
954
 
869
955
  if (action === "read") {
870
956
  const target = await wikiFor(input, scoped, "read")
871
- if (target.empty) return text(emptyKnowledge(input, spaceContext))
872
- if (target.error) return text(target.error)
957
+ if (target.empty) return answer(emptyKnowledge(input, spaceContext))
958
+ if (target.error) return answer(target.error)
873
959
  const { wikiID, note } = target
874
- if (toolkit.runtime.records?.isRecordsWiki(wikiID)) return text(RECORDS_REFUSAL)
960
+ if (toolkit.runtime.records?.isRecordsWiki(wikiID)) return answer(RECORDS_REFUSAL)
875
961
  const ref = String(input?.ref ?? input?.path ?? "").trim()
876
962
  const name = ref || filenameOf(input)
877
- if (!name) return text("invalid filename")
963
+ if (!name) return answer("invalid filename")
878
964
  // The source file first: it is what the agent writes, and it is
879
965
  // current at once, while the extracted page lags until ingestion
880
966
  // finishes (a model that re-read the page after a write saw the old
@@ -891,25 +977,25 @@ export function registerWiki(editor, toolkit) {
891
977
  const found = await read(scoped, wikiID, target)
892
978
  if (found && isRecordsText(found.content)) {
893
979
  toolkit.runtime.records?.noteRecordsWiki(wikiID)
894
- return text(RECORDS_REFUSAL)
980
+ return answer(RECORDS_REFUSAL)
895
981
  }
896
982
  if (found) {
897
983
  const safe = quarantineText(found.content.slice(0, 12_000))
898
984
  const after = quarantineNote(safe.removed)
899
- return text(
985
+ return answer(
900
986
  `${note}<knowledge source="${neutralizeFenceClosers(oneLine(found.source, 120))}">\n${neutralizeFenceClosers(
901
987
  safe.text,
902
988
  )}\n</knowledge>${after ? `\n${after}` : ""}`,
903
989
  )
904
990
  }
905
991
  }
906
- return text(`${note}${await notFound(scoped, wikiID, name)}`)
992
+ return answer(`${note}${await notFound(scoped, wikiID, name)}`)
907
993
  }
908
994
 
909
995
  if (action === "status") {
910
996
  const target = await wikiFor(input, scoped, "status")
911
- if (target.empty) return text(emptyKnowledge(input, spaceContext))
912
- if (target.error) return text(target.error)
997
+ if (target.empty) return answer(emptyKnowledge(input, spaceContext))
998
+ if (target.error) return answer(target.error)
913
999
  const { wikiID } = target
914
1000
  const [wiki, pages] = await Promise.all([
915
1001
  backend.getWiki({ scope: scoped, wikiID }),
@@ -918,29 +1004,58 @@ export function registerWiki(editor, toolkit) {
918
1004
  // While it ingests the hub lists no pages; its own count is the answer then.
919
1005
  const listed = Array.isArray(pages?.items) ? pages.items.length : 0
920
1006
  const pageCount = listed || Number(wiki?.page_count) || 0
921
- const status = String(wiki?.status ?? "unknown")
1007
+ const state = wikiStateOf(wiki)
1008
+ if (state === "ready" && Array.isArray(pages?.items)) cache.rememberPages(wikiID, listedPages(pages))
1009
+ const error = state === "failed" ? wikiErrorOf(wiki, cache.error(wikiID)) : ""
922
1010
  return text(
923
- `wiki: ${oneLine(wiki?.wiki_id ?? wikiID, 120)}\nname: ${oneLine(wiki?.name ?? "", 200)}\nstatus: ${oneLine(status, 40)}${
924
- status === "processing" ? " (ingesting: writes and deletes are refused until it is ready)" : ""
925
- }\npages: ${pageCount}`,
1011
+ `wiki: ${oneLine(wiki?.wiki_id ?? wikiID, 120)}\nname: ${oneLine(wiki?.name ?? "", 200)}\nstatus: ${oneLine(state, 40)}${
1012
+ state === "processing" ? " (ingesting: a write during it is queued until it finishes)" : ""
1013
+ }\npages: ${pageCount}${error ? `\nerror: ${oneLine(error, 400)}` : ""}`,
926
1014
  )
927
1015
  }
928
1016
 
929
1017
  const query = String(input?.query ?? "").trim()
930
- if (!query) return text("nothing to search: query is empty")
1018
+ if (!query) return answer("nothing to search: query is empty")
931
1019
  const ids = input?.knowledge_id
932
1020
  ? [String(input.knowledge_id)]
933
1021
  : await discoverKnowledge(backend, log, assetType, scoped)
934
- if (ids.length === 0) return text(emptyKnowledge(input, spaceContext))
1022
+ if (ids.length === 0) return answer(emptyKnowledge(input, spaceContext))
935
1023
  const result = await searchKnowledge(backend, ids.slice(0, 8), query, scoped, {
936
1024
  maxChars: config.recallChars,
937
1025
  })
938
- if (!result) return text("no knowledge results")
939
- return text(assetType === "code_graph" ? result : `${result}\n\n${READ_HINT}`)
1026
+ if (!result) return answer("no knowledge results")
1027
+ return answer(assetType === "code_graph" ? result : `${result}\n\n${READ_HINT}`)
940
1028
  } catch (error) {
941
1029
  log.warn("wiki failed", error)
942
- return fail(errorMessage(error))
1030
+ return failure(errorMessage(error))
943
1031
  }
944
1032
  },
1033
+ }
1034
+ editor.add(wiki)
1035
+ // The read-only twin (jelly #74), for the reason `mem.pages` gives: a host
1036
+ // that offers the `memory` resource and keeps the declaration's `readOnly: true`.
1037
+ if (toolkit.readOnlyTwins === true) editor.add({
1038
+ name: "wikis",
1039
+ description:
1040
+ "Read a document: list, search, read and status, and never a write (mem_wiki writes and deletes).",
1041
+ input: {
1042
+ type: "object",
1043
+ properties: {
1044
+ action: { type: "string", enum: [...WIKI_READ_ACTIONS], description: "Required. list, search, read, status." },
1045
+ query: { type: "string", description: "search: the query" },
1046
+ knowledge_id: { type: "string", description: "search: one id from list" },
1047
+ wiki_id: { type: "string", description: "read, status: the wiki id" },
1048
+ ref: { type: "string", description: "read: a hit's `path` or a page id" },
1049
+ type: { type: "string", description: "list, search: wiki, code-graph, all" },
1050
+ space: { type: "string", description: "A space id; the session's by default" },
1051
+ },
1052
+ required: ["action"],
1053
+ additionalProperties: false,
1054
+ },
1055
+ options: { namespace: "mem" },
1056
+ execute: async (input, context) =>
1057
+ WIKI_READ_ACTIONS.includes(String(input?.action ?? ""))
1058
+ ? wiki.execute(input, context)
1059
+ : text(`not read: mem_wikis reads only (${WIKI_READ_ACTIONS.join(", ")}). To change a document, use mem_wiki with action "${oneLine(input?.action, 40)}", which asks where it must.`),
945
1060
  })
946
1061
  }