@joe-broadhead/opencode-mem 0.9.12 → 0.11.2

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 (144) hide show
  1. package/CHANGELOG.md +1934 -2
  2. package/README.md +29 -17
  3. package/SECURITY.md +3 -1
  4. package/docs/agent-instructions.md +17 -0
  5. package/docs/agent-protocol.md +8 -8
  6. package/docs/permissions.md +22 -4
  7. package/package.json +7923 -217
  8. package/shared/page-paths.js +44 -0
  9. package/skills/mem.pages/SKILL.md +8 -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 +627 -33
  20. package/src/config.js +79 -6
  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 +21 -5
  88. package/src/recall.js +104 -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 +409 -90
  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 +47 -5
  104. package/src/tools/held-write.js +36 -13
  105. package/src/tools/index.js +27 -0
  106. package/src/tools/ingest.js +27 -2
  107. package/src/tools/memory.js +52 -14
  108. package/src/tools/page.js +95 -9
  109. package/src/tools/recall.js +208 -4
  110. package/src/tools/records-kit.js +2 -1
  111. package/src/tools/share.js +42 -3
  112. package/src/tools/shared.js +44 -4
  113. package/src/tools/space-lifecycle.js +278 -0
  114. package/src/tools/spaces.js +373 -29
  115. package/src/tools/status.js +9 -2
  116. package/src/tools/wiki.js +34 -4
  117. package/src/util.js +110 -6
  118. package/src/vendor/source-contract/README.md +24 -0
  119. package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
  120. package/src/vendor/source-contract/VENDOR.json +81 -0
  121. package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
  122. package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
  123. package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
  124. package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
  125. package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
  126. package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
  127. package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
  128. package/src/vendor/source-contract/cursor.js +26 -0
  129. package/src/vendor/source-contract/events.js +257 -0
  130. package/src/vendor/source-contract/registry.js +23 -0
  131. package/src/vendor/source-contract/tools-rpc.js +42 -0
  132. package/src/views/access-reads.js +256 -0
  133. package/src/views/communities.js +77 -0
  134. package/src/views/contracts.js +1183 -36
  135. package/src/views/inbox-bytes.js +103 -0
  136. package/src/views/overdue.js +1 -1
  137. package/src/views/profile.js +31 -0
  138. package/src/views/receipt.js +81 -0
  139. package/src/views/records-reads.js +869 -37
  140. package/src/views/rpc.js +159 -11
  141. package/src/views/shape.js +8 -5
  142. package/views/memory.html +16 -3
  143. package/views/pages.html +2 -2
  144. package/views/remembered.html +130 -0
@@ -0,0 +1,1936 @@
1
+ /**
2
+ * #58's operations, as plain plugin functions: one per action, each taking
3
+ * `(context, input)` and answering `{ ok: true, … }` or throwing an
4
+ * `OperationError` with #58's code (src/ops/codes.js).
5
+ *
6
+ * Nothing here asks, prints or decides for the person. Each function is the
7
+ * operation only, so the action framework can register it behind its own
8
+ * preview, ask and verified-caller path: a `…Preview` function answers the
9
+ * facts the person confirms against, read from the services, and the operation
10
+ * performs it.
11
+ *
12
+ * The rules it keeps, without exception:
13
+ * - The control plane decides access. Nothing here derives a role, and a role
14
+ * this plugin does not read is not invented.
15
+ * - A team page stays append-only for a bearer: the store refuses a move,
16
+ * delete or edit, and that refusal is passed on, never worked around by a
17
+ * copy, a delete and re-create, or a move round-trip.
18
+ * - A shared-space write needs the person's proofs, which the framework adds;
19
+ * these functions never fake one.
20
+ * - Every change is one the services audit (records' own audit for a record,
21
+ * control's for a space, a grant or a request).
22
+ */
23
+ import { createHash } from "node:crypto"
24
+ import { forwardCopies } from "./copy-lineage.js"
25
+ import { slug } from "../util.js"
26
+ import { copyPathFor } from "../../shared/page-paths.js"
27
+ import { pageTypeFor } from "../tools/records-kit.js"
28
+ import { recordsOf } from "../tools/share.js"
29
+ import { MAX_INPUT_BYTES } from "../action-grant.js"
30
+ import { PAGE_TRANSCRIPT_BYTES } from "../views/contracts.js"
31
+ import { CODES, OperationError, fromService } from "./codes.js"
32
+
33
+ /**
34
+ * The most pages one folder move takes. Jelly caps a preview's answer, and an
35
+ * action's, at 64 KiB, and a page's old and new path can each be 300 characters
36
+ * (§`PATH`), so one entry is at most ~620 bytes: 50 entries are ~31 KB, which
37
+ * fits with room for the rest of the answer. `paths` takes 50 for the same
38
+ * reason, and `records.move`'s own bound (200) is never reached. A larger folder
39
+ * is refused by name, never previewed as if it were smaller.
40
+ */
41
+ const MAX_FOLDER_PAGES = 50
42
+
43
+ /**
44
+ * The most a page's `fields` may hold, as the records service counts them: the
45
+ * JSON it writes, in bytes (`records/src/model.js` `LIMITS.fieldsBytes`).
46
+ */
47
+ const FIELDS_BYTES = 32 * 1024
48
+ /**
49
+ * The most a press's own JSON may be: the grant's input cap (ADR §4.4) less the
50
+ * room the ADR keeps for the envelope around it. Measured on the whole input,
51
+ * because a body, a transcript and fifty file links do not add up to a fixed
52
+ * number of characters and only the thing itself says how large it is.
53
+ */
54
+ const PRESS_BYTES = MAX_INPUT_BYTES - 4 * 1024
55
+ /** The most a save's `meeting` may hold, in JSON bytes: an id and two times. */
56
+ const MEETING_BYTES = 1024
57
+
58
+ /** A page path: the same shape records keeps (lower-case segments, at most four). */
59
+ const PATH = /^[a-z0-9][a-z0-9-]{0,63}(\/[a-z0-9][a-z0-9-]{0,63}){0,3}$/
60
+
61
+ /**
62
+ * The space roles that may write: the gateway's own data-plane write list
63
+ * (deploy/auth/role-guard.mjs). A role this plugin does not read is not
64
+ * invented; a `grant` role's rights are per page, from the context's grants.
65
+ */
66
+ const WRITER_ROLES = new Set(["editor", "admin", "owner"])
67
+
68
+ /** The wiki's structural pages, which mem_wiki keeps and a copy never takes. */
69
+ const STRUCTURAL_FILES = new Set(["index.md", "schema.md", "purpose.md"])
70
+
71
+ /** A wiki source file: flat, no folders, Markdown, at most 240 characters. */
72
+ const WIKI_FILE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,239}\.md$/
73
+
74
+ /** What mem_wiki takes as one file, and so what a copy takes. */
75
+ const WIKI_FILE_BYTES = 512 * 1024
76
+
77
+ /** A wiki id, as `mem_wiki` reads one. */
78
+ const WIKI_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{2,127}$/
79
+
80
+ /** A flat wiki source file name, or INVALID; nothing is written for a refusal. */
81
+ function wikiFileOf(value) {
82
+ const text = String(value ?? "").trim().replace(/^\/+/, "").replace(/\\/g, "/")
83
+ if (!text || text.includes("/") || text.includes("..") || !WIKI_FILE.test(text)) {
84
+ throw new OperationError("INVALID", `${JSON.stringify(value ?? null)} is not a wiki file name.`, 'Send a flat Markdown name such as "harbour-retro.md": a wiki holds no folders.')
85
+ }
86
+ if (STRUCTURAL_FILES.has(text.toLowerCase())) {
87
+ throw new OperationError("INVALID", `${text} is one of the wiki's structural pages, so a copy does not replace it.`, 'Send another name, for example "harbour-retro.md".')
88
+ }
89
+ return text
90
+ }
91
+
92
+ /** Whether a grant covers a page path (a folder grant ends in "/"). */
93
+ function grantCovers(prefix, path) {
94
+ return prefix.endsWith("/") ? String(path).startsWith(prefix) : prefix === path
95
+ }
96
+
97
+ /**
98
+ * Whether the person may write the space's pages: the console's `requireWriter`
99
+ * rule (`deploy/auth/console/pages.mjs`), from control's own answer. A member
100
+ * needs an editor role or more; a `grant` role needs an editor grant covering
101
+ * the page. Nothing here widens access.
102
+ */
103
+ function mayWritePage(space, path) {
104
+ const role = String(space?.role ?? "").toLowerCase()
105
+ if (role === "grant") {
106
+ const grants = Array.isArray(space?.grants) ? space.grants : []
107
+ return grants.some((grant) => String(grant?.role ?? "").toLowerCase() === "editor" && grantCovers(String(grant?.prefix ?? ""), path))
108
+ }
109
+ const kind = String(space?.space_kind ?? "").toLowerCase()
110
+ if (kind === "personal") return role === "" || WRITER_ROLES.has(role)
111
+ return WRITER_ROLES.has(role)
112
+ }
113
+
114
+ /** Whether the person may write the space's wiki (a page write, at the space's level). */
115
+ function mayWriteWiki(space) {
116
+ return mayWritePage(space, "")
117
+ }
118
+
119
+ const roleForAccess = (access) => {
120
+ const value = String(access ?? "").trim().toLowerCase()
121
+ if (value === "read") return "viewer"
122
+ if (value === "write") return "editor"
123
+ throw new OperationError("INVALID", `access is "read" or "write", not ${JSON.stringify(access ?? null)}.`, 'Send access: "read" or "write".')
124
+ }
125
+
126
+ function pathOf(value, what = "path") {
127
+ const text = String(value ?? "").trim()
128
+ if (!PATH.test(text)) throw new OperationError("INVALID", `${JSON.stringify(value ?? null)} is not a page ${what}.`, 'Send a path such as "projects/harbour" (lower case, words joined by hyphens, at most four segments).')
129
+ return text
130
+ }
131
+
132
+ function folderOf(value) {
133
+ const text = String(value ?? "").trim().replace(/^\/+|\/+$/g, "")
134
+ if (!text) return ""
135
+ if (!/^[a-z0-9][a-z0-9-]{0,63}(\/[a-z0-9][a-z0-9-]{0,63}){0,3}$/.test(text)) {
136
+ throw new OperationError("INVALID", `${JSON.stringify(value)} is not a folder.`, 'Send a folder such as "projects", or leave it out.')
137
+ }
138
+ return `${text}/`
139
+ }
140
+
141
+ /**
142
+ * @param {ReturnType<import("../tools/shared.js").createToolkit>} toolkit
143
+ */
144
+ export function createSpaceOperations(toolkit) {
145
+ const { control, config } = toolkit
146
+ const records = () => recordsOf(toolkit)
147
+
148
+ const userId = () => String(config?.user ?? "").trim()
149
+
150
+ function requireRecords() {
151
+ const client = records()
152
+ if (!client) throw new OperationError("SCOPE_MISSING", "this build has no records client, so pages are not reachable.", "Update opencode-mem, or ask the Memory server's operator whether the space has a records service.")
153
+ return client
154
+ }
155
+
156
+ /** One records call in a space, its failure in #58's words. */
157
+ async function call(method, body, space, context) {
158
+ try {
159
+ return await requireRecords().call(method, body, { space, sessionID: context?.sessionID })
160
+ } catch (error) {
161
+ throw fromService(error)
162
+ }
163
+ }
164
+
165
+ /**
166
+ * The origin space is told a record now lives elsewhere (records.copied,
167
+ * 0.11 review B2). A move deletes the original, and a space cannot read
168
+ * another space's file, so without this note a source removal could neither
169
+ * retract nor report the copy. `origin_event` keeps a moved record's copy
170
+ * reported after its original is gone. A failed note never fails the write
171
+ * that already happened.
172
+ */
173
+ async function noteCopies(copies, from, to, context) {
174
+ if (copies.length === 0) return true
175
+ try {
176
+ const answer = await call("records.copied", { to_space: to.space_id, copies }, from.space_id, context)
177
+ // A copy of a copy is noted in the space it came from: the store names the
178
+ // ancestor, and the chain is followed, one bounded hop at a time.
179
+ await forwardCopies((body, space) => call("records.copied", body, space, context), answer)
180
+ return true
181
+ } catch {
182
+ return false
183
+ }
184
+ }
185
+
186
+ /**
187
+ * A page op's refusal. A 403 from records means this caller may not dispose
188
+ * of that page (a team page is the person's, or a path they cannot write),
189
+ * which is #58's NOT_OWNER; the store's own words are kept.
190
+ */
191
+ function pageRefusal(error) {
192
+ if (Number(error?.status ?? error?.cause?.status) === 403) {
193
+ const failure = fromService(error)
194
+ return new OperationError("NOT_OWNER", failure.what, failure.next || "Only the person edits or deletes a team page; append a line, or ask them to.", { cause: error })
195
+ }
196
+ return fromService(error)
197
+ }
198
+
199
+ /** The space a call acts in: the named one, or the session's. */
200
+ async function spaceOf(context, requested) {
201
+ const resolved = await toolkit.resolveSpace({ space: requested }, context)
202
+ if (resolved?.error) throw new OperationError("SCOPE_MISSING", resolved.error, "Name a space you can open (mem_spaces list shows them), or bind this session.")
203
+ if (!resolved?.context?.space_id) throw new OperationError("SCOPE_MISSING", "no space was named and this session is not bound to one.", 'Send space: "<id>" from mem_spaces list.')
204
+ return resolved.context
205
+ }
206
+
207
+ /** One page by path in a space, or NOT_FOUND. */
208
+ async function pageAt(space, path, context) {
209
+ const answer = await call("records.get", { paths: [path] }, space, context)
210
+ const record = Array.isArray(answer?.records) ? answer.records.find((entry) => entry.path === path) : null
211
+ if (!record) throw new OperationError("NOT_FOUND", `no page at ${path} in that space.`, "Check the path with mem_page list, or write it first with page.save.")
212
+ return record
213
+ }
214
+
215
+ async function members(space) {
216
+ try {
217
+ const rows = await control.listMembers({ userId: userId(), spaceId: space })
218
+ return Array.isArray(rows) ? rows : []
219
+ } catch (error) {
220
+ throw fromService(error)
221
+ }
222
+ }
223
+
224
+ /** Who reads one path in a space: members, and the grants that cover it. */
225
+ async function readersOf(space, path) {
226
+ try {
227
+ const answer = await control.readers({ userId: userId(), spaceId: space, path })
228
+ return Array.isArray(answer?.readers) ? answer.readers : []
229
+ } catch (error) {
230
+ throw fromService(error)
231
+ }
232
+ }
233
+
234
+ /** A principal a preview names: a person, or honestly the group or role. */
235
+ const principal = (row) => {
236
+ if (row?.user_id) return { user_id: String(row.user_id), name: row.name ?? null, access: row.access ?? null }
237
+ if (row?.group_id) return { group_id: String(row.group_id), name: row.name ?? null, access: row.access ?? null, kind: "group" }
238
+ if (row?.org_role_id) return { org_role_id: String(row.org_role_id), name: row.name ?? null, access: row.access ?? null, kind: "org_role" }
239
+ if (row?.agent_id) return { agent_id: String(row.agent_id), name: row.name ?? null, access: row.access ?? null, kind: "agent" }
240
+ return null
241
+ }
242
+
243
+ const principalKey = (row) => row.user_id ?? row.group_id ?? row.org_role_id ?? row.agent_id
244
+
245
+ /** Who reads a page now, and who would read it where it lands. */
246
+ async function accessDelta(fromSpace, fromPath, toSpace, toPath) {
247
+ const [before, after] = await Promise.all([readersOf(fromSpace, fromPath), readersOf(toSpace, toPath)])
248
+ const was = new Map()
249
+ for (const row of before) {
250
+ const named = principal(row)
251
+ if (named) was.set(principalKey(named), named)
252
+ }
253
+ const now = new Map()
254
+ for (const row of after) {
255
+ const named = principal(row)
256
+ if (named) now.set(principalKey(named), named)
257
+ }
258
+ return {
259
+ gainAccess: [...now.entries()].filter(([key]) => !was.has(key)).map(([, row]) => row),
260
+ loseAccess: [...was.entries()].filter(([key]) => !now.has(key)).map(([, row]) => row),
261
+ }
262
+ }
263
+
264
+ // ---- A2: page.save ------------------------------------------------------
265
+
266
+ /**
267
+ * A meeting's own page path, from its id alone: one meeting, one page. Jelly
268
+ * sends a stable `path`; a save that names none still lands on the same page
269
+ * every time, whatever the page is called, so a re-save grows that page and
270
+ * never writes a second one. An id that is already a path segment is used as
271
+ * it is (`meetings/abc-defg-hij`); anything else is made one, with a digest of
272
+ * the id beside it so two meetings can never share a path.
273
+ */
274
+ function meetingPath(id) {
275
+ const raw = String(id ?? "")
276
+ const kept = raw.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "")
277
+ // An id that is already a path segment is used as it is. Anything else —
278
+ // upper case included, so `ABC` and `abc` never share a page — is made one,
279
+ // with a digest of the exact id beside it.
280
+ if (kept && kept === raw && kept.length <= 56) return `meetings/${kept}`
281
+ const digest = createHash("sha256").update(raw).digest("hex").slice(0, 10)
282
+ const head = kept.slice(0, 45).replace(/-+$/g, "")
283
+ return `meetings/${head ? `${head}-${digest}` : `meeting-${digest}`}`
284
+ }
285
+
286
+ /** The meeting a save names, or null: its id, and its times when it gives them. */
287
+ function meetingOf(value) {
288
+ if (value === undefined || value === null) return null
289
+ if (typeof value !== "object" || Array.isArray(value)) throw new OperationError("INVALID", "meeting needs its id.", 'Send meeting: {id: "<meeting id>", startedAt, endedAt}.')
290
+ const id = String(value.id ?? "").trim()
291
+ if (!id) throw new OperationError("INVALID", "meeting needs its id.", 'Send meeting: {id: "<meeting id>", startedAt, endedAt}.')
292
+ const bytes = Buffer.byteLength(JSON.stringify(value), "utf8")
293
+ if (bytes > MEETING_BYTES) {
294
+ throw new OperationError(
295
+ "INVALID",
296
+ `meeting is ${bytes.toLocaleString("en-US")} bytes of JSON, and a save takes ${MEETING_BYTES.toLocaleString("en-US")}.`,
297
+ "Send the meeting's id, its start and its end; nothing else rides there.",
298
+ )
299
+ }
300
+ return {
301
+ id,
302
+ ...(value.startedAt ? { startedAt: String(value.startedAt) } : {}),
303
+ ...(value.endedAt ? { endedAt: String(value.endedAt) } : {}),
304
+ }
305
+ }
306
+
307
+ /**
308
+ * A meeting's transcript, as the page keeps it for the meeting engine
309
+ * (`fields.transcript`), or "" when the save carries none. Text longer than
310
+ * the page's fields can hold is refused with the limit, never stored in part:
311
+ * a proposal must cite the transcript the person saved, not a cut of it.
312
+ */
313
+ function transcriptOf(value) {
314
+ if (value === undefined || value === null) return ""
315
+ if (typeof value !== "string") throw new OperationError("INVALID", "transcript must be text.", "Send the transcript as a string, or leave it out.")
316
+ if (!value.trim()) return ""
317
+ // The cap is bytes, as the store counts them: a transcript of 16,384
318
+ // characters is 49 KiB of Japanese and would be refused by the store after
319
+ // the act had already been spent. Never cut it: say the limit instead.
320
+ const bytes = Buffer.byteLength(value, "utf8")
321
+ if (bytes > PAGE_TRANSCRIPT_BYTES) {
322
+ throw new OperationError(
323
+ "INVALID",
324
+ `the transcript is ${bytes.toLocaleString("en-US")} UTF-8 bytes, and a meeting page's transcript takes ${PAGE_TRANSCRIPT_BYTES.toLocaleString("en-US")}.`,
325
+ "Save the meeting's notes in body, and link the transcript in files; a longer transcript waits for a Files address on the page.",
326
+ )
327
+ }
328
+ return value
329
+ }
330
+
331
+ /** The fields a save writes: the meeting, its files, and the transcript it carries. */
332
+ function saveFields(input, meeting) {
333
+ const files = Array.isArray(input.files) ? input.files.filter((file) => typeof file === "string" && file.trim()).slice(0, 50) : []
334
+ const transcript = transcriptOf(input.transcript)
335
+ return {
336
+ ...(meeting ? { meeting } : {}),
337
+ ...(files.length ? { files } : {}),
338
+ ...(transcript ? { transcript } : {}),
339
+ }
340
+ }
341
+
342
+ /** The bytes of a page's fields as the store measures them: the JSON it writes. */
343
+ function fieldsBytes(fields) {
344
+ const kept = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== null && value !== undefined))
345
+ return Buffer.byteLength(JSON.stringify(kept), "utf8")
346
+ }
347
+
348
+ /**
349
+ * Refuse fields the store would refuse, before it is asked: escaping (`"` and
350
+ * a newline are two bytes each) makes the JSON larger than the text, so the
351
+ * measure is the encoding the store writes, never the characters.
352
+ */
353
+ function checkFieldsBytes(fields) {
354
+ const bytes = fieldsBytes(fields)
355
+ if (bytes > FIELDS_BYTES) {
356
+ throw new OperationError(
357
+ "INVALID",
358
+ `these fields are ${bytes.toLocaleString("en-US")} bytes of JSON, and a page's fields take ${FIELDS_BYTES.toLocaleString("en-US")}.`,
359
+ "Shorten the transcript or the page's fields; a longer transcript waits for a Files address on the page.",
360
+ )
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Refuse a press larger than a grant carries, before it is signed or sent: a
366
+ * host signs the whole input, and a body, a transcript and fifty file links
367
+ * together are what is measured, never a guess added up from the declaration.
368
+ */
369
+ function checkPressBytes(input) {
370
+ const bytes = Buffer.byteLength(JSON.stringify(input), "utf8")
371
+ if (bytes > PRESS_BYTES) {
372
+ throw new OperationError(
373
+ "INVALID",
374
+ `this save is ${bytes.toLocaleString("en-US")} bytes of JSON, and a press carries ${PRESS_BYTES.toLocaleString("en-US")}.`,
375
+ "Save the page in two parts: the notes now, and the transcript with them in a later save.",
376
+ )
377
+ }
378
+ }
379
+
380
+ /** Where a save would put the page: the space, the path, its title and its type. */
381
+ async function savePlan(context, input = {}) {
382
+ const space = await spaceOf(context, input.space)
383
+ const body = String(input.body ?? "")
384
+ if (!body.trim()) throw new OperationError("INVALID", "a page needs text.", "Send body with what the page says.")
385
+ checkPressBytes(input)
386
+ const title = String(input.title ?? "").trim()
387
+ const meeting = meetingOf(input.meeting)
388
+ const folder = folderOf(input.folder ?? (meeting ? "meetings" : ""))
389
+ const path = input.path ? pathOf(input.path) : meeting ? meetingPath(meeting.id) : `${folder}${slug(title || body.split("\n")[0] || "page")}`
390
+ return { space, path, title, meeting, type: meeting ? "meeting" : pageTypeFor(path) }
391
+ }
392
+
393
+ /**
394
+ * What saving the page would write, read from the store: the path it lands at,
395
+ * whether a page is already there and at which version, and whether this space
396
+ * needs the approval a team page draws. Nothing here changes anything.
397
+ */
398
+ async function pageSavePreview(context, input = {}) {
399
+ const plan = await savePlan(context, input)
400
+ const found = await call("records.get", { paths: [plan.path] }, plan.space.space_id, context)
401
+ const current = Array.isArray(found?.records) ? found.records.find((entry) => entry.path === plan.path) : null
402
+ // The fields the save would write, measured as the store would: a preview
403
+ // that promised a save the store then refused would be a lie shown by the
404
+ // confirmation.
405
+ checkFieldsBytes({ ...(current?.fields ?? {}), ...saveFields(input, plan.meeting) })
406
+ return {
407
+ space: plan.space.space_id,
408
+ path: plan.path,
409
+ exists: Boolean(current),
410
+ version: Number(current?.version ?? 0),
411
+ type: String(plan.type),
412
+ ...(plan.title || current?.title ? { title: plan.title || String(current.title) } : {}),
413
+ approvalRequired: String(plan.space.space_kind ?? "").toLowerCase() !== "personal",
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Save a page. `meeting` marks it as a meeting (0.9.13's `meeting` page
419
+ * type); `folder` places it, `files` (names) ride on the page, and
420
+ * `transcript` is kept where the meeting engine reads it, in
421
+ * `fields.transcript`. A meeting's page is **its own**: a second save of the
422
+ * same meeting, at its path, updates that page and adds a version. A page at
423
+ * the path that is another meeting's or no meeting's is refused, as before.
424
+ */
425
+ async function pageSave(context, input = {}) {
426
+ const { space, path, title, type, meeting } = await savePlan(context, input)
427
+ const body = String(input.body ?? "")
428
+ const fields = saveFields(input, meeting)
429
+ const found = await call("records.get", { paths: [path] }, space.space_id, context)
430
+ const current = Array.isArray(found?.records) ? found.records.find((entry) => entry.path === path && entry.kind === "page") : null
431
+ if (current) {
432
+ // One page per meeting: the page this meeting already has grows. Anything
433
+ // else at the path is the caller's to name differently, so it is refused
434
+ // in the store's own words rather than merged into.
435
+ const theirs = meeting && String(current.fields?.meeting?.id ?? "") === meeting.id
436
+ if (!theirs) throw new OperationError("INVALID", `a page already lives at ${path}.`, "Name another path, or save the page that is there by opening it.")
437
+ const merged = { ...(current.fields ?? {}), ...fields }
438
+ checkFieldsBytes(merged)
439
+ const saved = await call(
440
+ "records.put",
441
+ {
442
+ record: {
443
+ id: String(current.id),
444
+ base_version: Number(current.version),
445
+ kind: "page",
446
+ type,
447
+ path,
448
+ ...(title ? { title } : {}),
449
+ body,
450
+ fields: merged,
451
+ },
452
+ },
453
+ space.space_id,
454
+ context,
455
+ )
456
+ const record = saved?.record ?? {}
457
+ return { ok: true, id: String(record.id ?? current.id), path: String(record.path ?? path), version: Number(record.version) || null, type: String(record.type ?? type) }
458
+ }
459
+ checkFieldsBytes(fields)
460
+ const saved = await call(
461
+ "records.put",
462
+ {
463
+ record: {
464
+ kind: "page",
465
+ type,
466
+ path,
467
+ ...(title ? { title } : {}),
468
+ body,
469
+ ...(Object.keys(fields).length > 0 ? { fields } : {}),
470
+ },
471
+ },
472
+ space.space_id,
473
+ context,
474
+ )
475
+ const record = saved?.record ?? {}
476
+ return { ok: true, id: String(record.id ?? ""), path: String(record.path ?? path), version: Number(record.version) || null, type: String(record.type ?? "") }
477
+ }
478
+
479
+ // ---- A3: page.move, and its preview ------------------------------------
480
+
481
+ /**
482
+ * Where a move takes what: one page (`path`), a whole folder (`prefix`) or up
483
+ * to fifty pages (`paths`), and the space it lands in. `mode` says which.
484
+ */
485
+ async function movePlan(context, input = {}) {
486
+ const from = await spaceOf(context, input.space)
487
+ const prefix = input.prefix === undefined || input.prefix === null ? null : String(input.prefix).trim()
488
+ const paths = Array.isArray(input.paths) ? input.paths : null
489
+ if (prefix !== null && paths !== null) throw new OperationError("INVALID", "a move names one page, a folder or a list of pages, never two at once.", "Send path, prefix or paths.")
490
+ const to = input.to?.space ? await spaceOf(context, input.to.space) : from
491
+ if (prefix !== null) {
492
+ const fromPrefix = folderOf(prefix)
493
+ if (!fromPrefix) throw new OperationError("INVALID", "name the folder to move.", 'Send prefix: "projects/old/".')
494
+ const toPrefix = folderOf(input.to?.path)
495
+ if (!toPrefix) throw new OperationError("INVALID", "name the folder the pages move to.", 'Send to: {path: "archive/projects/"}.')
496
+ if (fromPrefix === toPrefix) throw new OperationError("INVALID", `the pages are already in ${fromPrefix}.`, "Name a different folder.")
497
+ if (toPrefix.startsWith(fromPrefix) || fromPrefix.startsWith(toPrefix)) {
498
+ throw new OperationError("INVALID", `${fromPrefix} and ${toPrefix} are nested; a folder cannot move into itself or its parent.`, "Move it to a sibling folder, such as archive/projects/ for projects/.")
499
+ }
500
+ // One more than the cap, so a bigger folder is **detected** rather than
501
+ // previewed as if it were the cap (records.list never answers more than
502
+ // 200, so asking for the cap alone would hide the rest).
503
+ const listed = await call("records.list", { kind: "page", path_prefix: fromPrefix, limit: MAX_FOLDER_PAGES + 1 }, from.space_id, context)
504
+ const pages = Array.isArray(listed?.records) ? listed.records.filter((record) => typeof record?.path === "string") : []
505
+ if (pages.length === 0) throw new OperationError("NOT_FOUND", `no page is in ${fromPrefix}.`, "Check the folder with mem_page list.")
506
+ if (pages.length > MAX_FOLDER_PAGES || listed?.cursor) {
507
+ const held = pages.length > MAX_FOLDER_PAGES ? `more than ${MAX_FOLDER_PAGES}` : `${pages.length}`
508
+ throw new OperationError(
509
+ "INVALID",
510
+ `${fromPrefix} holds ${held} pages, and one folder move takes at most ${MAX_FOLDER_PAGES}, so nothing moved.`,
511
+ `Move the folders inside it one at a time, or the pages in parts of at most ${MAX_FOLDER_PAGES}.`,
512
+ )
513
+ }
514
+ return { from, to, mode: "prefix", prefix: fromPrefix, toPrefix, pages, crosses: from.space_id !== to.space_id }
515
+ }
516
+ if (paths !== null) {
517
+ if (paths.length === 0 || paths.length > 50) throw new OperationError("INVALID", "a bulk move takes 1 to 50 pages.", "Choose at most 50 paths.")
518
+ const folder = folderOf(input.to?.folder)
519
+ if (!folder) throw new OperationError("INVALID", "name the folder the pages move to.", 'Send to: {folder: "archive"}.')
520
+ const targets = [...new Set(paths.map((entry) => pathOf(entry)))].map((at) => ({ from: at, to: pathOf(`${folder}${at.split("/").pop()}`) }))
521
+ const found = await call("records.get", { paths: targets.map((entry) => entry.from) }, from.space_id, context)
522
+ const byPath = new Map((Array.isArray(found?.records) ? found.records : []).filter((record) => record?.kind === "page").map((record) => [record.path, record]))
523
+ const pages = targets.map((entry) => ({ ...entry, page: byPath.get(entry.from) ?? null }))
524
+ if (!pages.some((entry) => entry.page)) throw new OperationError("NOT_FOUND", "none of those pages is in that space.", "Check the paths with mem_page list.")
525
+ return { from, to, mode: "paths", pages, crosses: from.space_id !== to.space_id }
526
+ }
527
+ const path = pathOf(input.path)
528
+ const toPath = pathOf(input.to?.path, "path to move to")
529
+ const page = await pageAt(from.space_id, path, context)
530
+ return { from, to, mode: "page", path, toPath, page, crosses: from.space_id !== to.space_id }
531
+ }
532
+
533
+ /**
534
+ * What a move changes for other people: the readers who gain the pages (the
535
+ * target space's members, when it crosses spaces) and those who lose them.
536
+ * One page, a folder or a list; nothing here changes anything.
537
+ */
538
+ async function pageMovePreview(context, input = {}) {
539
+ const plan = await movePlan(context, input)
540
+ if (plan.mode !== "page") {
541
+ // A folder or a list: every page it would take, by its old and new path.
542
+ const moved = plan.mode === "prefix"
543
+ ? plan.pages.map((page) => ({ path: page.path, to: `${plan.toPrefix}${page.path.slice(plan.prefix.length)}` }))
544
+ : plan.pages.map((entry) => ({ path: entry.from, to: entry.to }))
545
+ return {
546
+ ok: true,
547
+ action: plan.mode === "prefix" ? "move_folder" : "bulk_move",
548
+ count: moved.length,
549
+ pages: moved.slice(0, MAX_FOLDER_PAGES),
550
+ affected: moved.length,
551
+ from: { space: plan.from.space_id, ...(plan.mode === "prefix" ? { prefix: plan.prefix } : {}) },
552
+ to: { space: plan.to.space_id, ...(plan.mode === "prefix" ? { prefix: plan.toPrefix } : {}) },
553
+ approvalRequired: String(plan.from.space_kind ?? "").toLowerCase() !== "personal" || String(plan.to.space_kind ?? "").toLowerCase() !== "personal",
554
+ }
555
+ }
556
+ // Who reads the page now, and who reads it where it lands: the members and
557
+ // the grants that cover each path. A move within a space still changes it
558
+ // when a folder grant covers one path and not the other.
559
+ const delta = await accessDelta(plan.from.space_id, plan.path, plan.to.space_id, plan.toPath)
560
+ return { ok: true, ...delta, affected: 1, from: { space: plan.from.space_id, path: plan.path }, to: { space: plan.to.space_id, path: plan.toPath } }
561
+ }
562
+
563
+ /**
564
+ * Move a page, within a space (records.move rewrites the links to it) or
565
+ * between spaces (the page is written to the target and the source copy is
566
+ * removed). A folder moves in one records.move with `path_prefix`, and a list
567
+ * of pages one records.move each, the taken ones reported and skipped. A team
568
+ * page is append-only for a bearer: the store's refusal is passed on, never
569
+ * worked around.
570
+ */
571
+ async function pageMove(context, input = {}) {
572
+ const plan = await movePlan(context, input)
573
+ if (plan.mode === "prefix") {
574
+ if (plan.crosses) throw new OperationError("INVALID", "a folder moves within one space.", "Move the pages between spaces one at a time with path, or copy the folder's pages.")
575
+ let moved
576
+ try {
577
+ moved = await call("records.move", { path_prefix: plan.prefix, to_prefix: plan.toPrefix }, plan.from.space_id, context)
578
+ } catch (error) {
579
+ throw pageRefusal(error)
580
+ }
581
+ const rows = Array.isArray(moved?.moved) ? moved.moved : []
582
+ // Counts and a bounded list: an answer stays under the 64 KiB Jelly caps.
583
+ return {
584
+ ok: true,
585
+ count: rows.length,
586
+ pages: rows.slice(0, MAX_FOLDER_PAGES),
587
+ rewritten: Number(moved?.rewritten_links) || 0,
588
+ from: { space: plan.from.space_id, prefix: plan.prefix },
589
+ to: { space: plan.to.space_id, prefix: plan.toPrefix },
590
+ }
591
+ }
592
+ if (plan.mode === "paths") {
593
+ const results = []
594
+ let rewritten = 0
595
+ for (const entry of plan.pages) {
596
+ if (!entry.page) {
597
+ results.push({ path: entry.from, to: entry.to, outcome: "refused", reason: "there is no page at that path" })
598
+ continue
599
+ }
600
+ if (plan.crosses) {
601
+ // Between spaces: write the page in the target, then remove the source.
602
+ let written
603
+ try {
604
+ written = await call("records.put", { record: { kind: "page", type: entry.page.type, path: entry.to, title: entry.page.title, body: entry.page.body, fields: { ...(entry.page.fields ?? {}), moved_from: { space: plan.from.space_id, path: entry.from } } } }, plan.to.space_id, context)
605
+ } catch (error) {
606
+ const failure = pageRefusal(error)
607
+ results.push({ path: entry.from, to: entry.to, outcome: "refused", reason: failure.what })
608
+ continue
609
+ }
610
+ const made = written?.record ?? {}
611
+ await noteCopies([{ record: entry.page.id, copy_id: String(made.id ?? "") || null, origin_event: entry.page.source?.event ?? null }], plan.from, plan.to, context)
612
+ try {
613
+ await call("records.delete", { ids: [entry.page.id] }, plan.from.space_id, context)
614
+ } catch (error) {
615
+ const record = written?.record ?? {}
616
+ throw new OperationError("INVALID", `${entry.from} was copied to ${entry.to} but the original could not be removed (${error.message}).`, "Delete the original with page.delete, or keep both.", { extra: { partial: { id: String(record.id ?? ""), path: entry.to } } })
617
+ }
618
+ results.push({ path: entry.from, to: entry.to, outcome: "done", id: String(written?.record?.id ?? "") })
619
+ continue
620
+ }
621
+ try {
622
+ const moved = await call("records.move", { id: entry.page.id, path: entry.to }, plan.from.space_id, context)
623
+ rewritten += Number(moved?.rewritten_links) || 0
624
+ results.push({ path: entry.from, to: entry.to, outcome: "done", id: String(moved?.record?.id ?? entry.page.id) })
625
+ } catch (error) {
626
+ const failure = pageRefusal(error)
627
+ results.push({ path: entry.from, to: entry.to, outcome: "refused", reason: failure.what })
628
+ }
629
+ }
630
+ const done = results.filter((entry) => entry.outcome === "done")
631
+ if (done.length === 0) {
632
+ const first = results[0]
633
+ throw new OperationError("INVALID", `nothing moved: ${results.length} of ${results.length} pages were refused.`, "Resolve each page, then move again.", { extra: { results } })
634
+ }
635
+ return { ok: true, count: done.length, pages: results.slice(0, MAX_FOLDER_PAGES), refused: results.filter((entry) => entry.outcome !== "done").length, rewritten, partial: done.length !== results.length }
636
+ }
637
+ if (!plan.crosses) {
638
+ let moved
639
+ try {
640
+ moved = await call("records.move", { id: plan.page.id, path: plan.toPath }, plan.from.space_id, context)
641
+ } catch (error) {
642
+ // A team page is append-only for a bearer: the store's refusal is the
643
+ // person's own rule, and it is passed on, never worked around.
644
+ throw pageRefusal(error)
645
+ }
646
+ const record = moved?.record ?? {}
647
+ return { ok: true, id: String(record.id ?? plan.page.id), path: String(record.path ?? plan.toPath), version: Number(record.version) || null }
648
+ }
649
+ // #58 review, finding 9: a page in a shared space is not moved out from
650
+ // here. The store refuses to delete a team page for a bearer, so a move
651
+ // that copied first would leave a copy behind; it is refused before
652
+ // anything is written.
653
+ if (plan.crosses && String(plan.from.space_kind ?? "").toLowerCase() === "shared") {
654
+ throw new OperationError(
655
+ "NOT_OWNER",
656
+ `${plan.path} is in a shared space, so a copy of it is not a move: the original stays a team page.`,
657
+ "Copy it with page.copy and ask the person to delete the original in Memory's console.",
658
+ )
659
+ }
660
+ let written
661
+ try {
662
+ written = await call(
663
+ "records.put",
664
+ {
665
+ record: {
666
+ kind: "page",
667
+ type: plan.page.type,
668
+ path: plan.toPath,
669
+ title: plan.page.title,
670
+ body: plan.page.body,
671
+ fields: { ...(plan.page.fields ?? {}), moved_from: { space: plan.from.space_id, path: plan.path } },
672
+ },
673
+ },
674
+ plan.to.space_id,
675
+ context,
676
+ )
677
+ } catch (error) {
678
+ throw pageRefusal(error)
679
+ }
680
+ const record = written?.record ?? {}
681
+ await noteCopies([{ record: plan.page.id, copy_id: String(record.id ?? "") || null, origin_event: plan.page.source?.event ?? null }], plan.from, plan.to, context)
682
+ try {
683
+ await call("records.delete", { ids: [plan.page.id] }, plan.from.space_id, context)
684
+ } catch (error) {
685
+ // The copy stays: say so plainly rather than report a move that half
686
+ // happened, and tell the action layer it is `partial` — the copy exists,
687
+ // so the receipt must not say `refused`. The person can delete the source.
688
+ throw new OperationError("INVALID", `the page was copied to ${plan.toPath} but the original at ${plan.path} could not be removed (${error.message}).`, "Delete the original with page.delete, or keep both.", {
689
+ extra: { partial: { id: String(record.id ?? ""), path: String(record.path ?? plan.toPath) } },
690
+ })
691
+ }
692
+ return { ok: true, id: String(record.id ?? ""), path: String(record.path ?? plan.toPath), version: Number(record.version) || null }
693
+ }
694
+
695
+ // ---- A4: page.delete, wiki.delete, and the wiki preview -----------------
696
+
697
+ async function pageDelete(context, input = {}) {
698
+ const space = await spaceOf(context, input.space)
699
+ const paths = deletePathsOf(input)
700
+ const pages = []
701
+ for (const path of paths) pages.push({ path, page: await pageAt(space.space_id, path, context) })
702
+ try {
703
+ await call("records.delete", { ids: pages.map((entry) => entry.page.id) }, space.space_id, context)
704
+ } catch (error) {
705
+ throw pageRefusal(error)
706
+ }
707
+ if (pages.length === 1) return { ok: true, id: pages[0].page.id, path: pages[0].path, count: 1 }
708
+ return { ok: true, count: pages.length, pages: pages.map((entry) => ({ id: entry.page.id, path: entry.path })) }
709
+ }
710
+
711
+ /** The paths one delete names: `path`, or up to fifty `paths`, never both. */
712
+ function deletePathsOf(input) {
713
+ const one = input.path === undefined || input.path === null || input.path === "" ? null : pathOf(input.path)
714
+ const many = Array.isArray(input.paths) ? [...new Set(input.paths.map((entry) => pathOf(entry)))] : null
715
+ if (one !== null && many !== null) throw new OperationError("INVALID", "a delete names one page or a list of pages, never both.", "Send path or paths.")
716
+ if (one !== null) return [one]
717
+ if (many === null || many.length === 0) throw new OperationError("INVALID", "name the page or pages to delete.", 'Send path: "projects/harbour", or paths: ["projects/harbour"].')
718
+ if (many.length > 50) throw new OperationError("INVALID", "one delete takes at most 50 pages.", "Choose at most 50 paths.")
719
+ return many
720
+ }
721
+
722
+ /**
723
+ * The pages a delete would remove — every one it names, each with its version
724
+ * — and whether this space is one where a delete needs the approval Memory's
725
+ * console draws (a team page is append-only for anything but its own person).
726
+ * Nothing here changes anything.
727
+ */
728
+ async function pageDeletePreview(context, input = {}) {
729
+ const space = await spaceOf(context, input.space)
730
+ const paths = deletePathsOf(input)
731
+ const found = await call("records.get", { paths }, space.space_id, context)
732
+ const byPath = new Map((Array.isArray(found?.records) ? found.records : []).filter((record) => typeof record?.path === "string").map((record) => [record.path, record]))
733
+ const pages = paths.map((path) => {
734
+ const page = byPath.get(path)
735
+ return {
736
+ path,
737
+ exists: Boolean(page),
738
+ version: Number(page?.version ?? 0),
739
+ ...(page?.type ? { type: String(page.type) } : {}),
740
+ ...(page?.title ? { title: String(page.title) } : {}),
741
+ }
742
+ })
743
+ return {
744
+ space: space.space_id,
745
+ count: pages.length,
746
+ // Every page the delete will remove, never just the first.
747
+ pages,
748
+ ...(pages.length === 1 ? { path: pages[0].path, exists: pages[0].exists, version: pages[0].version } : {}),
749
+ approvalRequired: String(space.space_kind ?? "").toLowerCase() !== "personal",
750
+ }
751
+ }
752
+
753
+ /**
754
+ * What deleting a wiki changes, read from the store: how many pages go, who
755
+ * loses access to them, and how many pages in *other* wikis link into this
756
+ * one. Nothing here changes anything.
757
+ */
758
+ async function wikiDeletePreview(context, input = {}) {
759
+ const space = await spaceOf(context, input.space)
760
+ const wikiID = String(input.wiki ?? "").trim()
761
+ if (!wikiID) throw new OperationError("INVALID", "name the wiki to delete.", 'Send wiki: "<wiki id>" from mem_wiki list.')
762
+ // The space the input names, not the session's: the wiki the person showed
763
+ // is in that space, and a scope read from elsewhere finds (or misses) the
764
+ // wrong one.
765
+ const scope = wikiScope(space, context)
766
+ let pages = 0
767
+ try {
768
+ const listed = await toolkit.backend.listWikiPages({ scope, wikiID })
769
+ // The hub's answer is `{items, total}`; `pages` and `count` are kept as
770
+ // fallbacks for an older shape. Counting only one of them reported 0
771
+ // pages for a wiki that had pages, which is not a fact to confirm against.
772
+ pages = Array.isArray(listed?.items)
773
+ ? listed.items.length
774
+ : Array.isArray(listed?.pages)
775
+ ? listed.pages.length
776
+ : Number(listed?.count) || 0
777
+ } catch (error) {
778
+ throw fromService(error)
779
+ }
780
+ // Links into this wiki from other wikis: the hub exposes a wiki's own
781
+ // graph, not the edges pointing at it, and this build has no read for
782
+ // them. Answering 0 would be a claim the store cannot support, so it is
783
+ // answered as unknown until a read exists (`null`, never a made-up 0).
784
+ let linksFromOtherWikis = null
785
+ if (typeof toolkit.backend?.wikiIncomingLinks === "function") {
786
+ try {
787
+ const incoming = await toolkit.backend.wikiIncomingLinks({ scope, wikiID })
788
+ linksFromOtherWikis = Array.isArray(incoming) ? incoming.length : null
789
+ } catch {
790
+ linksFromOtherWikis = null
791
+ }
792
+ }
793
+ // Who loses the wiki's pages: the space's readers at its own root, in the
794
+ // space the input named. A personal space has one member, so its answer is
795
+ // that person — the owner the delete belongs to.
796
+ const rows = await readersOf(space.space_id)
797
+ const loseAccess = rows.map(principal).filter(Boolean)
798
+ return {
799
+ ok: true,
800
+ pages,
801
+ loseAccess,
802
+ linksFromOtherWikis,
803
+ wiki: wikiID,
804
+ space: space.space_id,
805
+ }
806
+ }
807
+
808
+ /** Delete a whole wiki (the hub's own delete, through the gateway). */
809
+ async function wikiDelete(context, input = {}) {
810
+ const space = await spaceOf(context, input.space)
811
+ const wikiID = String(input.wiki ?? "").trim()
812
+ if (!wikiID) throw new OperationError("INVALID", "name the wiki to delete.", 'Send wiki: "<wiki id>" from mem_wiki list.')
813
+ try {
814
+ await toolkit.backend.deleteWiki({ scope: wikiScope(space, context), wikiIDs: [wikiID] })
815
+ } catch (error) {
816
+ throw fromService(error)
817
+ }
818
+ return { ok: true, wiki: wikiID, space: space.space_id }
819
+ }
820
+
821
+ // ---- A5: space.create ---------------------------------------------------
822
+
823
+ /** Create a shared space: a team or a topic, invite-only or open, with members. */
824
+ async function spaceCreate(context, input = {}) {
825
+ const name = String(input.name ?? "").trim()
826
+ if (!name) throw new OperationError("INVALID", "a new space needs a name.", 'Send name: "Harbour team".')
827
+ const kind = input.kind === undefined ? undefined : String(input.kind)
828
+ if (kind !== undefined && !["team", "topic"].includes(kind)) throw new OperationError("INVALID", `kind is "team" or "topic", not ${JSON.stringify(kind)}.`, 'Send kind: "team" or kind: "topic".')
829
+ const visibility = input.visibility === undefined ? undefined : String(input.visibility)
830
+ if (visibility !== undefined && !["invite", "open"].includes(visibility)) throw new OperationError("INVALID", `visibility is "invite" or "open", not ${JSON.stringify(visibility)}.`, 'Send visibility: "invite" or "open".')
831
+ const people = Array.isArray(input.members) ? input.members : []
832
+ const members = people.map((entry) => {
833
+ const id = typeof entry === "string" ? entry : String(entry?.user_id ?? entry?.person ?? entry?.email ?? "").trim()
834
+ if (!id) throw new OperationError("INVALID", "each member is a user id.", 'Send members: ["<user id>", …] from mem_spaces members.')
835
+ const role = typeof entry === "object" && entry?.role ? String(entry.role) : undefined
836
+ return { user_id: id, ...(role ? { role } : {}) }
837
+ })
838
+ try {
839
+ const made = await control.createSpace({ userId: userId(), name, ...(kind ? { kind } : {}), ...(visibility ? { visibility } : {}), ...(members.length ? { members } : {}) })
840
+ return { ok: true, id: made.space?.space_id ?? null, name: made.space?.name ?? name, kind: made.flavor ?? kind ?? "team", visibility: made.visibility ?? visibility ?? "invite", members: made.members ?? [] }
841
+ } catch (error) {
842
+ throw fromService(error)
843
+ }
844
+ }
845
+
846
+ // ---- A6: share.grant, share.revoke, and their previews ------------------
847
+
848
+ /**
849
+ * The control target a share names. A page, folder or wiki is a catalog
850
+ * resource; a space is itself. The lookup is a read.
851
+ */
852
+ async function shareTarget(input) {
853
+ const space = await spaceOf({}, input.target?.space ?? input.space)
854
+ const named = ["wiki", "folder", "page"].filter((key) => input.target?.[key] !== undefined && input.target?.[key] !== null)
855
+ if (named.length > 1) throw new OperationError("INVALID", "name one page, folder or wiki, not several.", 'Send target: {space: "<id>", page: "projects/harbour"}.')
856
+ const kind = named[0] ?? "space"
857
+ if (kind === "space") {
858
+ const id = String(input.target?.space ?? input.space ?? "")
859
+ const row = (await control.listSpaces({ userId: userId() }))?.find?.((entry) => entry.space_id === id)
860
+ if (!row) throw new OperationError("NOT_FOUND", `no space ${id} you can open.`, "Check the id with mem_spaces list.")
861
+ return { space: id, target_type: "space", target_id: id, label: row.name ?? id, access: "space" }
862
+ }
863
+ const value = String(input.target[kind])
864
+ const upstream = kind === "page" ? `records:${pathOf(value)}` : kind === "folder" ? `records:${folderOf(value)}` : value
865
+ let rows = []
866
+ try {
867
+ rows = await control.listResources({ userId: userId(), spaceId: space.space_id })
868
+ } catch (error) {
869
+ throw fromService(error)
870
+ }
871
+ const found = (Array.isArray(rows) ? rows : []).find((row) => String(row.upstream_id ?? "") === upstream || String(row.id) === value)
872
+ if (!found) {
873
+ throw new OperationError("NOT_FOUND", `nothing is shared from ${space.space_id} as ${upstream}.`, "Share it first (mem_share grant registers the page or folder), or check the path with mem_page list.")
874
+ }
875
+ // The catalog row names the target's own owner: a page's owner hands it on,
876
+ // and need not be the space's owner (control's `resource.owner_user_id`).
877
+ return { space: space.space_id, target_type: "resource", target_id: String(found.id), label: found.name ?? upstream, access: kind, owner_user_id: String(found.owner_user_id ?? "") || undefined }
878
+ }
879
+
880
+ /** The person a share names: a user id from the roster or the lookup. */
881
+ async function personFor(space, value) {
882
+ const given = String(value ?? "").trim()
883
+ if (!given) throw new OperationError("INVALID", "name the person to share with.", 'Send person: "<user id>", or an exact email.')
884
+ if (given.includes("@")) {
885
+ try {
886
+ const found = await control.lookupUser({ userId: userId(), email: given })
887
+ if (found?.user_id) return String(found.user_id)
888
+ } catch (error) {
889
+ throw fromService(error, "NOT_FOUND")
890
+ }
891
+ throw new OperationError("NOT_FOUND", `no one in your organisation has the email ${given}.`, "Check the address, or share with a user id from mem_spaces members.")
892
+ }
893
+ return given
894
+ }
895
+
896
+ /**
897
+ * A space-wide grant to someone who is already a member with at least that
898
+ * role adds nothing, so the action refuses it (`ALREADY_MEMBER`) and points
899
+ * at their membership. A page or folder grant is not this: it narrows.
900
+ */
901
+ async function assertNotAlreadyMember(target, person, role) {
902
+ if (target.target_type !== "space") return
903
+ const rows = await members(target.space)
904
+ const mine = rows.find((row) => String(row.user_id ?? "") === person)
905
+ if (!mine) return
906
+ const rank = { viewer: 1, editor: 2, admin: 3, owner: 4 }
907
+ if ((rank[String(mine.role)] ?? 0) >= (rank[role] ?? 0)) {
908
+ throw new OperationError("ALREADY_MEMBER", `${person} is already a ${mine.role} of this space, so this grant adds nothing.`, "Change their member role instead (mem_spaces role), or share a page or folder with them.")
909
+ }
910
+ }
911
+
912
+ async function shareGrantPreview(context, input = {}) {
913
+ const target = await shareTarget(input)
914
+ const person = await personFor(target.space, input.person)
915
+ const role = roleForAccess(input.access)
916
+ await assertNotAlreadyMember(target, person, role)
917
+ try {
918
+ const preview = await control.previewGrant({ userId: userId(), grant: { target_type: target.target_type, target_id: target.target_id, principal_type: "user", principal_id: person, role, space_id: target.space } })
919
+ return { ok: true, ...preview, target: { ...preview.target, space: target.space } }
920
+ } catch (error) {
921
+ throw mapShare(error, target, person)
922
+ }
923
+ }
924
+
925
+ async function shareGrant(context, input = {}) {
926
+ const target = await shareTarget(input)
927
+ const person = await personFor(target.space, input.person)
928
+ const role = roleForAccess(input.access)
929
+ await assertNotAlreadyMember(target, person, role)
930
+ try {
931
+ const grant = await control.createGrant({ userId: userId(), grant: { target_type: target.target_type, target_id: target.target_id, principal_type: "user", principal_id: person, role, space_id: target.space } })
932
+ return { ok: true, grant: grant?.id ?? null, target: { type: target.target_type, id: target.target_id, label: target.label }, person: { user_id: person }, access: String(input.access) }
933
+ } catch (error) {
934
+ throw mapShare(error, target, person)
935
+ }
936
+ }
937
+
938
+ /** The grant a revoke names: the one on this target that gives this person access. */
939
+ async function grantOn(target, person) {
940
+ let rows = []
941
+ try {
942
+ rows = target.target_type === "resource"
943
+ ? await control.listGrants({ userId: userId(), spaceId: target.space, resourceId: target.target_id })
944
+ // A space-wide grant to another person is only visible to its owner or
945
+ // an admin of the space, and control answers that list for them alone.
946
+ : await control.listGrants({ userId: userId(), spaceId: target.space, scope: "space" })
947
+ } catch (error) {
948
+ throw fromService(error)
949
+ }
950
+ const found = (Array.isArray(rows) ? rows : []).find((row) => String(row.principal_type) === "user" && String(row.principal_id) === person && row.target_type === target.target_type && String(row.target_id) === target.target_id)
951
+ if (!found) throw new OperationError("NOT_FOUND", `that person has no grant on ${target.label}.`, "Check who has access with mem_share list, or revoke a membership instead.")
952
+ return found
953
+ }
954
+
955
+ /** A listed grant's id: the control client normalises it to `grant_id`. */
956
+ function grantIdOf(grant) {
957
+ return String(grant?.grant_id ?? grant?.id ?? "")
958
+ }
959
+
960
+ async function shareRevokePreview(context, input = {}) {
961
+ const target = await shareTarget(input)
962
+ const person = await personFor(target.space, input.person)
963
+ const grant = await grantOn(target, person)
964
+ try {
965
+ const preview = await control.previewRevoke({ userId: userId(), grantId: grantIdOf(grant) })
966
+ return { ok: true, ...preview, target: { ...preview.target, space: target.space } }
967
+ } catch (error) {
968
+ throw mapShare(error, target, person)
969
+ }
970
+ }
971
+
972
+ async function shareRevoke(context, input = {}) {
973
+ const target = await shareTarget(input)
974
+ const person = await personFor(target.space, input.person)
975
+ const grant = await grantOn(target, person)
976
+ try {
977
+ await control.deleteGrant({ userId: userId(), grantId: grantIdOf(grant) })
978
+ return { ok: true, target: { type: target.target_type, id: target.target_id, label: target.label }, person: { user_id: person } }
979
+ } catch (error) {
980
+ throw mapShare(error, target, person)
981
+ }
982
+ }
983
+
984
+ /** A share's refusal in #58's words: a page or folder you do not own is NOT_OWNER. */
985
+ function mapShare(error, target, person) {
986
+ const failure = fromService(error)
987
+ if (failure.code === "NOT_OWNER" || (Number(error?.status) === 403 && target.target_type === "resource")) {
988
+ return new OperationError("NOT_OWNER", `you do not own ${target.label}, and you are not an editor of its space, so you cannot share it.`, "Ask its owner or a space editor to share it, or share something of your own.", { cause: error })
989
+ }
990
+ if (failure.code === "ALREADY_MEMBER") {
991
+ return new OperationError("ALREADY_MEMBER", failure.what, "Change their member role instead (mem_spaces role), or revoke a different grant.", { cause: error })
992
+ }
993
+ void person
994
+ throw failure
995
+ }
996
+
997
+ // ---- A7: share.transfer, and share.decide's two answers ---------------
998
+
999
+ async function shareTransfer(context, input = {}) {
1000
+ const target = await shareTarget(input)
1001
+ const to = await personFor(target.space, input.to)
1002
+ try {
1003
+ const asked = await control.requestTransfer({ userId: userId(), target: { [target.target_type === "space" ? "space" : "page"]: target.target_id }, to, ...(context?.p2 ? { p2: context.p2 } : {}) })
1004
+ return { ok: true, requestId: asked.requestId, state: asked.state || "pending" }
1005
+ } catch (error) {
1006
+ const failure = fromService(error)
1007
+ if (failure.code === "NOT_OWNER") throw new OperationError("NOT_OWNER", `only the owner of ${target.label} can hand it over.`, "Ask the owner to hand it over.", { cause: error })
1008
+ if (failure.code === "REQUEST_PENDING") throw new OperationError("REQUEST_PENDING", `a handover of ${target.label} is already waiting for that person.`, "Wait for them to accept or decline it, or ask again later.", { cause: error })
1009
+ throw failure
1010
+ }
1011
+ }
1012
+
1013
+ /**
1014
+ * What a handover would ask, and of whom: the owner now, the person who would
1015
+ * own the space or page once they accept it, and that it is a request rather
1016
+ * than a change. Nothing here changes anything.
1017
+ */
1018
+ async function shareTransferPreview(context, input = {}) {
1019
+ const target = await shareTarget(input)
1020
+ const to = await personFor(target.space, input.to)
1021
+ const rows = await members(target.space)
1022
+ // The owner who hands it over is the **target's** own: for a space, its
1023
+ // owner; for a page or folder, the person the catalog row names, which need
1024
+ // not be the space's owner (control's `resource.owner_user_id`). The preview
1025
+ // refuses what the act will refuse, and nothing else.
1026
+ const spaceOwner = rows.find((row) => String(row.role ?? "").toLowerCase() === "owner")
1027
+ const ownerId = target.target_type === "resource" ? String(target.owner_user_id ?? "") : String(spaceOwner?.user_id ?? "")
1028
+ if (!ownerId || ownerId !== userId()) {
1029
+ throw new OperationError("NOT_OWNER", `only the owner of ${target.label} can hand it over.`, "Ask the owner to hand it over.")
1030
+ }
1031
+ const ownerNow = { user_id: ownerId, name: rows.find((row) => String(row.user_id ?? "") === ownerId)?.name ?? null }
1032
+ return {
1033
+ ok: true,
1034
+ state: "pending",
1035
+ affected: 1,
1036
+ target: { type: target.target_type, id: target.target_id, label: target.label, space: target.space },
1037
+ from: ownerNow,
1038
+ ownerNow,
1039
+ to: { user_id: to },
1040
+ }
1041
+ }
1042
+
1043
+ async function shareAccept(context, input = {}) {
1044
+ const requestId = String(input.requestId ?? "").trim()
1045
+ if (!requestId) throw new OperationError("INVALID", "name the handover request to accept.", "Send requestId from share.transfer's answer, or from the handover list.")
1046
+ try {
1047
+ const done = await control.decideTransfer({ userId: userId(), requestId, decision: "accept", ...(context?.p2 ? { p2: context.p2 } : {}) })
1048
+ return { ok: true, state: done.state || "accepted", target: done.target }
1049
+ } catch (error) {
1050
+ throw fromService(error)
1051
+ }
1052
+ }
1053
+
1054
+ async function shareDecline(context, input = {}) {
1055
+ const requestId = String(input.requestId ?? "").trim()
1056
+ if (!requestId) throw new OperationError("INVALID", "name the handover request to decline.", "Send requestId from share.transfer's answer, or from the handover list.")
1057
+ try {
1058
+ const done = await control.decideTransfer({ userId: userId(), requestId, decision: "decline", ...(input.note ? { note: String(input.note) } : {}), ...(context?.p2 ? { p2: context.p2 } : {}) })
1059
+ return { ok: true, state: done.state || "declined", target: done.target }
1060
+ } catch (error) {
1061
+ throw fromService(error)
1062
+ }
1063
+ }
1064
+
1065
+ // ---- A8: page.copy ------------------------------------------------------
1066
+
1067
+ /**
1068
+ * The scope a knowledge call for one space's wiki takes: the space the input
1069
+ * names, never the session's. A wiki is an asset of one space, and a scope
1070
+ * read from somewhere else asks the knowledge service about another space's
1071
+ * container — which the gateway then refuses for the named wiki (`/v3/wiki/page/ls`
1072
+ * answers `403`), or, worse, finds a same-named wiki there.
1073
+ */
1074
+ function wikiScope(space, context) {
1075
+ if (typeof toolkit.scopeFor !== "function") return toolkit.sharedScope(context)
1076
+ return toolkit.scopeFor(space, {
1077
+ // Only the keys the call actually carries: an `undefined` member is not
1078
+ // part of a scope, and the space a caller names goes alone.
1079
+ ...(typeof context?.sessionID === "string" ? { sessionID: context.sessionID } : {}),
1080
+ ...(typeof context?.agent === "string" ? { agent: context.agent } : {}),
1081
+ })
1082
+ }
1083
+
1084
+ /** The wiki the space holds, as the hub has it; a wiki it does not hold is NOT_FOUND. */
1085
+ async function wikiAt(space, wikiID, context) {
1086
+ const given = String(wikiID ?? "").trim()
1087
+ if (!WIKI_ID.test(given)) throw new OperationError("INVALID", `${JSON.stringify(wikiID ?? null)} is not a wiki id.`, 'Send wiki: "<wiki id>" from mem_wiki list.')
1088
+ if (!toolkit.backend || typeof toolkit.backend.getWiki !== "function") {
1089
+ throw new OperationError("SCOPE_MISSING", "this build has no knowledge service, so a wiki cannot be written.", "Update opencode-mem, or ask the Memory server's operator whether the space has a knowledge service.")
1090
+ }
1091
+ if (toolkit.runtime?.records?.isRecordsWiki?.(given)) {
1092
+ throw new OperationError("INVALID", `the "${given}" wiki holds commitments, and is not a document wiki.`, "Use mem_commitments for commitments, or copy into a document wiki from mem_wiki list.")
1093
+ }
1094
+ try {
1095
+ return await toolkit.backend.getWiki({ scope: wikiScope(space, context), wikiID: given })
1096
+ } catch (error) {
1097
+ // The gateway answers 403 for a wiki outside the space's catalog, as the
1098
+ // console says: it is not there for this caller, which is not a write.
1099
+ if (Number(error?.status) === 403 || Number(error?.status) === 404) {
1100
+ throw new OperationError("NOT_FOUND", `wiki ${given} is not in ${space.space_id}, or you have no access to it.`, "Check the wiki's id with mem_wiki list, and name its space with to.space when it is another space.")
1101
+ }
1102
+ throw fromService(error)
1103
+ }
1104
+ }
1105
+
1106
+ /** A wiki source file's text, or null when it is not there. */
1107
+ async function wikiFileAt(scoped, wikiID, filename) {
1108
+ let data
1109
+ try {
1110
+ data = await toolkit.backend.readWikiRaw({ scope: scoped, wikiID, filenames: [filename] })
1111
+ } catch (error) {
1112
+ throw fromService(error)
1113
+ }
1114
+ const item = (Array.isArray(data?.items) ? data.items : []).find((entry) => entry?.filename === filename)
1115
+ if (!item || item.not_found) return null
1116
+ return String(item.content ?? "")
1117
+ }
1118
+
1119
+ /** The wiki's name and id, in the words a confirmation shows. */
1120
+ function wikiLabel(wiki) {
1121
+ const name = String(wiki?.name ?? "").trim()
1122
+ return name ? `${name} (${wiki.id})` : wiki.id
1123
+ }
1124
+
1125
+ /** The file a copy writes: the page's words, and a line naming where they came from. */
1126
+ function copyBody(page, from, path) {
1127
+ const words = String(page.body ?? "").replace(/\s+$/, "")
1128
+ return `${words}\n\n_Copied from ${from.space_id}/${path}._\n`
1129
+ }
1130
+
1131
+ /** A hub refusal of the copy's own write, in the words that say what to do next. */
1132
+ function wikiWriteRefusal(error, wiki, filename) {
1133
+ const what = String(error?.what ?? error?.message ?? "")
1134
+ if (Number(error?.status) === 409 || /wiki is processing/i.test(what)) {
1135
+ return new OperationError("INVALID", `${wikiLabel(wiki)} is ingesting an earlier write and refuses writes until it finishes; nothing was copied.`, "Retry once mem_wiki status shows the wiki ready.")
1136
+ }
1137
+ if (/invalid path/i.test(what) || /\bENOENT\b/.test(what)) {
1138
+ return new OperationError("INVALID", `the wiki refused "${filename}" as a file name; nothing was copied.`, 'Send a flat name such as "harbour-retro.md".')
1139
+ }
1140
+ return fromService(error)
1141
+ }
1142
+
1143
+ /** Where a copy goes, and the page it comes from. */
1144
+ async function copyPlan(context, input = {}) {
1145
+ const from = await spaceOf(context, input.from?.space ?? input.space)
1146
+ const path = pathOf(input.from?.path ?? input.path)
1147
+ // The console's own rule (pages.mjs `copyPlan`): a page is copied out only
1148
+ // by someone who may write it where it is, so a reader cannot lift a
1149
+ // team's words elsewhere — into a wiki its members can search, say.
1150
+ if (!mayWritePage(from, path)) {
1151
+ throw new OperationError(
1152
+ "NOT_OWNER",
1153
+ `${path} is in ${from.space_id}, where you are ${from.role ? `a ${String(from.role)}` : "a reader"}: copying a page needs write access in the space it is in.`,
1154
+ "Ask an editor or an admin of that space to make the copy, or copy a page in a space you write.",
1155
+ )
1156
+ }
1157
+ const page = await pageAt(from.space_id, path, context)
1158
+ const wikiID = String(input.to?.wiki ?? "").trim()
1159
+ if (wikiID) {
1160
+ // A copy into a wiki leaves records for the hub: one flat source file,
1161
+ // named by the shared page-path rule (shared/page-paths.js), which the
1162
+ // console uses too, and named by the page's own name only: a wiki file
1163
+ // has no folders, so a deep path would make a long, unreadable name.
1164
+ if (input.to?.folder) {
1165
+ throw new OperationError("INVALID", "a wiki holds flat source files, so there is no folder to copy into.", 'Send to: {wiki: "<wiki id>"}, and a flat file name with path when you want one.')
1166
+ }
1167
+ const to = input.to?.space ? await spaceOf(context, input.to.space) : from
1168
+ if (!mayWriteWiki(to)) {
1169
+ throw new OperationError(
1170
+ "NOT_OWNER",
1171
+ `you are ${to.role ? `a ${String(to.role)}` : "a reader"} of ${to.space_id}, so you cannot write into its wiki.`,
1172
+ "Ask an editor or an admin of that space to make the copy, or copy into a space you write.",
1173
+ )
1174
+ }
1175
+ const wiki = await wikiAt(to, wikiID, context)
1176
+ const leaf = String(page.path ?? path).split("/").at(-1) || "page"
1177
+ const targetPath = input.to?.path ? wikiFileOf(input.to.path) : wikiFileOf(`${copyPathFor({ page, path: leaf })}.md`)
1178
+ return { from, to, page, samePage: path, targetPath, wiki: { id: wikiID, name: String(wiki?.name ?? "") } }
1179
+ }
1180
+ const to = input.to?.space ? await spaceOf(context, input.to.space) : from
1181
+ const samePage = page.path
1182
+ const folder = folderOf(input.to?.folder)
1183
+ // One name for a copy, shared with the console (shared/page-paths.js): a
1184
+ // valid segment, and the `-copy` suffix kept whole however long the title.
1185
+ const targetPath = input.to?.path ? pathOf(input.to.path) : pathOf(copyPathFor({ page, path: samePage, folder }))
1186
+ return { from, to, page, samePage, targetPath }
1187
+ }
1188
+
1189
+ /**
1190
+ * Where a copy goes, and the page it comes from: the declared answer names the
1191
+ * source (whether it is there, at which version) and the destination (the path
1192
+ * it lands at, and whether that space needs the approval a team page draws).
1193
+ * A wiki destination names the wiki and the exact file the copy lands at.
1194
+ * #58 A8.
1195
+ */
1196
+ async function pageCopyPreview(context, input = {}) {
1197
+ const plan = await copyPlan(context, input)
1198
+ const folder = String(input.to?.folder ?? "").trim().replace(/^\/+|\/+$/g, "")
1199
+ if (plan.wiki) {
1200
+ return {
1201
+ from: {
1202
+ space: plan.from.space_id,
1203
+ path: plan.samePage,
1204
+ exists: true,
1205
+ version: Number(plan.page.version) || 0,
1206
+ ...(plan.page.title ? { title: String(plan.page.title) } : {}),
1207
+ },
1208
+ to: {
1209
+ space: plan.to.space_id,
1210
+ wiki: plan.wiki.id,
1211
+ ...(plan.wiki.name ? { wikiName: plan.wiki.name } : {}),
1212
+ path: plan.targetPath,
1213
+ // A wiki write draws no records approval: the action's own `always`
1214
+ // confirmation is the whole ask, so the preview says so.
1215
+ approvalRequired: false,
1216
+ },
1217
+ }
1218
+ }
1219
+ return {
1220
+ from: {
1221
+ space: plan.from.space_id,
1222
+ path: plan.samePage,
1223
+ exists: true,
1224
+ version: Number(plan.page.version) || 0,
1225
+ ...(plan.page.title ? { title: String(plan.page.title) } : {}),
1226
+ },
1227
+ to: {
1228
+ space: plan.to.space_id,
1229
+ ...(folder ? { folder } : {}),
1230
+ path: plan.targetPath,
1231
+ approvalRequired: String(plan.to.space_kind ?? "").toLowerCase() !== "personal",
1232
+ },
1233
+ }
1234
+ }
1235
+
1236
+ /**
1237
+ * The page's version the person confirmed, or NEEDS_APPROVAL. The console
1238
+ * requires the version its preview showed; so does this, so a press signed
1239
+ * for one version never copies a later one.
1240
+ */
1241
+ function versionOf(input) {
1242
+ const seen = input.version === undefined || input.version === null ? undefined : Number(input.version)
1243
+ if (!Number.isInteger(seen) || seen < 1) {
1244
+ throw new OperationError("NEEDS_APPROVAL", "a copy is signed for the page as the preview showed it, and this press carries no version.", "Press it from the copy's preview, which supplies the version.")
1245
+ }
1246
+ return seen
1247
+ }
1248
+
1249
+ /** Copy a page, marked with where it came from (`fields.copied_from`, or the file's own line). */
1250
+ async function pageCopy(context, input = {}) {
1251
+ const seen = versionOf(input)
1252
+ const plan = await copyPlan(context, input)
1253
+ const { from, to, page, samePage, targetPath } = plan
1254
+ if (Number(page.version) !== seen) {
1255
+ throw new OperationError("VERSION_CONFLICT", `${samePage} is at version ${Number(page.version)}, not ${seen}: it changed after the preview, and nothing was copied.`, "Read the copy's preview again, then press again.")
1256
+ }
1257
+ if (plan.wiki) {
1258
+ // The file name is part of what the grant signs: a press without the
1259
+ // name the preview showed would not cover its target.
1260
+ if (!String(input.to?.path ?? "").trim()) {
1261
+ throw new OperationError("NEEDS_APPROVAL", `a copy into ${wikiLabel(plan.wiki)} is signed for the file the preview showed, and this press names none.`, `Press it from the preview, which sends to.path: "${targetPath}".`)
1262
+ }
1263
+ return wikiCopy(context, plan)
1264
+ }
1265
+ const written = await call(
1266
+ "records.put",
1267
+ {
1268
+ record: {
1269
+ kind: "page",
1270
+ type: page.type,
1271
+ path: targetPath,
1272
+ title: page.title,
1273
+ body: page.body,
1274
+ fields: { ...(page.fields ?? {}), copied_from: { space: from.space_id, path: samePage } },
1275
+ },
1276
+ },
1277
+ to.space_id,
1278
+ context,
1279
+ )
1280
+ const record = written?.record ?? {}
1281
+ await noteCopies([{ record: page.id, copy_id: String(record.id ?? "") || null, origin_event: page.source?.event ?? null }], from, to, context)
1282
+ return { ok: true, id: String(record.id ?? ""), path: String(record.path ?? targetPath), from: { space: from.space_id, path: samePage } }
1283
+ }
1284
+
1285
+ /**
1286
+ * Write the copy into the wiki as one source file, never over a file already
1287
+ * there, then start its ingest so search finds it. A wiki the caller cannot
1288
+ * write was refused in the plan, before anything was read.
1289
+ */
1290
+ async function wikiCopy(context, plan) {
1291
+ const { from, to, page, samePage, targetPath, wiki } = plan
1292
+ if (typeof toolkit.backend.writeWikiRaw !== "function" || typeof toolkit.backend.readWikiRaw !== "function") {
1293
+ throw new OperationError("SCOPE_MISSING", "this build has no knowledge service, so a wiki cannot be written.", "Update opencode-mem, or ask the Memory server's operator whether the space has a knowledge service.")
1294
+ }
1295
+ const scoped = wikiScope(to, context)
1296
+ const body = copyBody(page, from, samePage)
1297
+ // What mem_wiki takes as one file, so what a copy takes: a bigger page is
1298
+ // refused before anything is written.
1299
+ if (Buffer.byteLength(body) > WIKI_FILE_BYTES) {
1300
+ throw new OperationError("INVALID", `the copy would be ${Buffer.byteLength(body)} bytes, and a wiki file takes at most ${WIKI_FILE_BYTES}; nothing was copied.`, "Shorten the page, or copy it into a records space instead.")
1301
+ }
1302
+ if ((await wikiFileAt(scoped, wiki.id, targetPath)) !== null) {
1303
+ throw new OperationError(
1304
+ "INVALID",
1305
+ `${targetPath} is already in ${wikiLabel(wiki)}, and a copy never overwrites an existing file.`,
1306
+ `Send to: {wiki: "${wiki.id}", path: "<another name>.md"}, or change the file in the wiki itself.`,
1307
+ )
1308
+ }
1309
+ try {
1310
+ await toolkit.backend.writeWikiRaw({ scope: scoped, wikiID: wiki.id, files: [{ filename: targetPath, content: body }] })
1311
+ } catch (error) {
1312
+ throw wikiWriteRefusal(error, wiki, targetPath)
1313
+ }
1314
+ let ingested = true
1315
+ try {
1316
+ await toolkit.backend.ingestWiki({ scope: scoped, wikiID: wiki.id })
1317
+ } catch {
1318
+ // The file is written; the ingest can be run later (mem_wiki ingest).
1319
+ ingested = false
1320
+ }
1321
+ return { ok: true, wiki: wiki.id, path: targetPath, ingested, from: { space: from.space_id, path: samePage } }
1322
+ }
1323
+
1324
+ // ---- A8 (widened): one copy, a page or the person's own memories --------
1325
+
1326
+ /**
1327
+ * Copy what the input names into a space: a page (the console's Send a copy)
1328
+ * or the person's own memories (the console's copy into a shared space). One
1329
+ * action, `op` picks which; nothing is removed from the source.
1330
+ */
1331
+ async function shareCopy(context, input = {}) {
1332
+ const op = String(input.op ?? "")
1333
+ if (op === "page") return { ...(await pageCopy(context, input)), op }
1334
+ if (op !== "memories") throw new OperationError("INVALID", `op is "page" or "memories", not ${JSON.stringify(input.op ?? null)}.`, 'Send op: "page" or op: "memories".')
1335
+ // A wiki holds documents, not memories: the page copy is the one that lands there.
1336
+ if (input.to?.wiki !== undefined && input.to !== null && String(input.to.wiki ?? "").trim()) {
1337
+ throw new OperationError("INVALID", "a wiki holds documents, not memories, so a memories copy does not name one.", 'Send op: "page" with to: {wiki: "<wiki id>"} to copy a page there.')
1338
+ }
1339
+ const ids = Array.isArray(input.ids) ? [...new Set(input.ids.map((entry) => String(entry ?? "").trim()))].filter(Boolean) : []
1340
+ if (ids.length === 0 || ids.length > 100) throw new OperationError("INVALID", "choose 1 to 100 memories to copy.", "Send ids: [\"<memory id>\", …].")
1341
+ // The console's rule (sharing.mjs): the person's own memories leave their
1342
+ // **personal** space, and only with a reason the copy carries.
1343
+ const from = await spaceOf(context, input.from?.space)
1344
+ if (String(from.space_kind ?? "").toLowerCase() !== "personal") {
1345
+ throw new OperationError("INVALID", "memories are copied from your own personal space, not a shared one.", "Copy the page with share.grant, or copy from Personal.")
1346
+ }
1347
+ const reason = typeof input.note === "string" ? input.note.trim().replace(/\s+/g, " ") : ""
1348
+ if (!reason || reason.length > 300) throw new OperationError("INVALID", "say why the space should see these; it is recorded on each copy.", 'Send note: "the team plans the deploy".')
1349
+ if (!input.to?.space) throw new OperationError("INVALID", "name the space the copies go to.", 'Send to: {space: "<id>"}.')
1350
+ const to = await spaceOf(context, input.to.space)
1351
+ if (to.space_id === from.space_id) throw new OperationError("INVALID", "the copies would land in the space they come from.", "Name another space.")
1352
+ if (String(to.space_kind ?? "").toLowerCase() === "personal") throw new OperationError("INVALID", "copies go to a shared space.", "Name a shared space.")
1353
+ const found = await call("records.get", { ids }, from.space_id, context)
1354
+ const byId = new Map((Array.isArray(found?.records) ? found.records : []).map((record) => [String(record?.id), record]))
1355
+ const sources = []
1356
+ for (const id of ids) {
1357
+ const record = byId.get(id)
1358
+ if (!record) throw new OperationError("NOT_FOUND", `${id} is not in that space, so nothing was copied.`, "Read the list again, then copy.")
1359
+ if (record.kind !== "memory") throw new OperationError("INVALID", `${id} is a ${record.kind}, and only memories are copied here.`, "Share a page with share.grant.")
1360
+ if (record.status !== "current") throw new OperationError("NOT_PENDING", `${id} is ${record.status}, so it is not copied.`, "Copy the current memory.")
1361
+ if (record.owner && record.owner !== userId()) throw new OperationError("NOT_OWNER", `${id} belongs to someone else, so it is not yours to copy.`, "Copy one of your own memories.")
1362
+ if (String(record.body ?? record.title ?? "").trim().length > 8000) throw new OperationError("INVALID", `${id} is longer than a copy takes (8000 characters).`, "Keep the memory shorter, then copy it.")
1363
+ sources.push(record)
1364
+ }
1365
+ const written = []
1366
+ for (const record of sources) {
1367
+ try {
1368
+ // Fresh fields, as the console writes them: where it came from, and the
1369
+ // reason the person gave. Nothing of the source's own fields crosses.
1370
+ // The source's own `stated_by` is kept, as the console keeps it: a
1371
+ // memory the agent concluded stays the agent's, and one the person
1372
+ // wrote stays theirs.
1373
+ const made = await call("records.put", { record: { kind: "memory", type: record.type ?? "fact", title: record.title, body: record.body, ...(record.stated_by ? { stated_by: record.stated_by } : {}), fields: { copied_from: { space: from.space_id, id: record.id }, rationale: reason } } }, to.space_id, context)
1374
+ written.push({ from: record.id, id: String(made?.record?.id ?? ""), event: typeof record.source?.event === "string" ? record.source.event : null })
1375
+ } catch (error) {
1376
+ // Nothing is left half-copied: the copies already written are removed.
1377
+ for (const entry of written) await call("records.delete", { ids: [entry.id] }, to.space_id, context).catch(() => null)
1378
+ throw fromService(error)
1379
+ }
1380
+ }
1381
+ const registered = await noteCopies(written.map((entry) => ({ record: entry.from, copy_id: entry.id || null, origin_event: entry.event ?? null })), from, to, context)
1382
+ return { ok: true, op, count: written.length, ids: written.map((entry) => entry.id), from: { space: from.space_id }, to: { space: to.space_id }, ...(registered ? {} : { copy_note_missing: true }) }
1383
+ }
1384
+
1385
+ /** What a copy would take and where it would land; nothing is written. */
1386
+ async function shareCopyPreview(context, input = {}) {
1387
+ const op = String(input.op ?? "")
1388
+ if (op === "page") return { ...(await pageCopyPreview(context, input)), op }
1389
+ if (op !== "memories") throw new OperationError("INVALID", `op is "page" or "memories", not ${JSON.stringify(input.op ?? null)}.`, 'Send op: "page" or op: "memories".')
1390
+ if (input.to?.wiki !== undefined && input.to !== null && String(input.to.wiki ?? "").trim()) {
1391
+ throw new OperationError("INVALID", "a wiki holds documents, not memories, so a memories copy does not name one.", 'Send op: "page" with to: {wiki: "<wiki id>"} to copy a page there.')
1392
+ }
1393
+ const ids = Array.isArray(input.ids) ? input.ids.map((entry) => String(entry ?? "")).filter(Boolean) : []
1394
+ const from = await spaceOf(context, input.from?.space)
1395
+ const to = await spaceOf(context, input.to?.space)
1396
+ const found = ids.length === 0 ? { records: [] } : await call("records.get", { ids }, from.space_id, context)
1397
+ const rows = Array.isArray(found?.records) ? found.records : []
1398
+ return {
1399
+ ok: true,
1400
+ op,
1401
+ count: rows.length,
1402
+ memories: rows.slice(0, 50).map((record) => ({ id: String(record.id), type: String(record.type ?? "fact"), title: String(record.title ?? "").slice(0, 160), status: String(record.status ?? "") })),
1403
+ missing: ids.filter((id) => !rows.some((record) => String(record.id) === id)),
1404
+ note: typeof input.note === "string" ? input.note.slice(0, 300) : "",
1405
+ from: { space: from.space_id },
1406
+ to: { space: to.space_id, approvalRequired: String(to.space_kind ?? "").toLowerCase() !== "personal" },
1407
+ }
1408
+ }
1409
+
1410
+ // ---- A memory organiser: move, retire, restore or confirm ---------------
1411
+
1412
+ /**
1413
+ * Move, retire, restore or confirm the memories the input names. A move is
1414
+ * the console's own: a copy into the target, read back, then the sources
1415
+ * deleted; the other three are `records.revise` over the same ids. Every op
1416
+ * is reversible by another in this act, and the preview names which one this
1417
+ * is.
1418
+ */
1419
+ async function memoryOrganise(context, input = {}) {
1420
+ const op = String(input.op ?? "")
1421
+ // No `move`: a move changes who can see a memory, so it is a different
1422
+ // consequence and waits for its own action (#59 §4.5).
1423
+ if (!["retire", "restore", "confirm"].includes(op)) throw new OperationError("INVALID", `op is "retire", "restore" or "confirm", not ${JSON.stringify(input.op ?? null)}.`, "Send one of them; move memories in Memory's console.")
1424
+ const ids = Array.isArray(input.ids) ? [...new Set(input.ids.map((entry) => String(entry ?? "").trim()))].filter(Boolean) : []
1425
+ if (ids.length === 0 || ids.length > 100) throw new OperationError("INVALID", "choose 1 to 100 memories.", 'Send ids: ["<memory id>", …].')
1426
+ const from = await spaceOf(context, input.space)
1427
+ const answer = await call("records.revise", { ids, action: op }, from.space_id, context)
1428
+ const results = Array.isArray(answer?.results) ? answer.results : []
1429
+ const done = results.filter((entry) => entry?.ok)
1430
+ if (done.length === 0) {
1431
+ const first = results[0]?.error ?? {}
1432
+ throw new OperationError("NOT_PENDING", `nothing changed: ${results.length} of ${results.length} memories could not be ${op === "confirm" ? "confirmed" : `${op}d`}.`, String(first.message ?? "Read the list again, then choose the memories that are there."))
1433
+ }
1434
+ return { ok: true, op, count: done.length, ids: done.map((entry) => entry.id), failed: results.length - done.length }
1435
+ }
1436
+
1437
+ /** What one organiser op would change: the op's own name, and how many memories. */
1438
+ async function memoryOrganisePreview(context, input = {}) {
1439
+ const op = String(input.op ?? "")
1440
+ if (!["retire", "restore", "confirm"].includes(op)) throw new OperationError("INVALID", `op is "retire", "restore" or "confirm", not ${JSON.stringify(input.op ?? null)}.`, "Send one of them; move memories in Memory's console.")
1441
+ const ids = Array.isArray(input.ids) ? input.ids.map((entry) => String(entry ?? "")).filter(Boolean) : []
1442
+ const from = await spaceOf(context, input.space)
1443
+ const found = ids.length === 0 ? { records: [] } : await call("records.get", { ids }, from.space_id, context)
1444
+ const rows = Array.isArray(found?.records) ? found.records : []
1445
+ return {
1446
+ ok: true,
1447
+ // The preview names the op: leaving a space and confirming a memory are
1448
+ // not the same thing to the person pressing.
1449
+ op,
1450
+ label: op === "retire" ? "Retire memories" : op === "restore" ? "Restore memories" : "Confirm memories",
1451
+ count: rows.length,
1452
+ memories: rows.slice(0, 50).map((record) => ({ id: String(record.id), title: String(record.title ?? "").slice(0, 160), status: String(record.status ?? "") })),
1453
+ missing: ids.filter((id) => !rows.some((record) => String(record.id) === id)),
1454
+ from: { space: from.space_id },
1455
+ }
1456
+ }
1457
+
1458
+ // ---- A13's move: a commitment between spaces ----------------------------
1459
+
1460
+ /**
1461
+ * Move one commitment to another space: the console's own move (copy into the
1462
+ * target, read back, then the source removed). Nothing is removed until its
1463
+ * copy reads back.
1464
+ */
1465
+ async function commitmentMove(context, input = {}) {
1466
+ const from = await spaceOf(context, input.space)
1467
+ const id = String(input.id ?? "").trim()
1468
+ if (!id) throw new OperationError("INVALID", "name the commitment to move.", 'Send id: "<rec_…>".')
1469
+ if (!input.to?.space) throw new OperationError("INVALID", "name the space the commitment moves to.", 'Send to: {space: "<id>"}.')
1470
+ const to = await spaceOf(context, input.to.space)
1471
+ if (to.space_id === from.space_id) throw new OperationError("INVALID", "the commitment is already in that space.", "Name another space.")
1472
+ const found = await call("records.get", { ids: [id] }, from.space_id, context)
1473
+ const record = (Array.isArray(found?.records) ? found.records : []).find((entry) => String(entry?.id) === id && entry.kind === "commitment")
1474
+ if (!record) throw new OperationError("NOT_FOUND", `no commitment ${id} in that space.`, "List them with mem.commitments.")
1475
+ if (input.revision !== undefined && Number(input.revision) !== Number(record.version)) {
1476
+ throw new OperationError("VERSION_CONFLICT", `it changed since you saw it (now version ${record.version}).`, "Read it again, then move it.")
1477
+ }
1478
+ let written
1479
+ try {
1480
+ written = await call("records.put", { record: { kind: "commitment", type: record.type ?? "commitment", title: record.title, body: record.body, stated_by: record.stated_by, fields: { ...(record.fields ?? {}), moved_from: { space: from.space_id, id: record.id } } } }, to.space_id, context)
1481
+ } catch (error) {
1482
+ throw fromService(error)
1483
+ }
1484
+ const copy = written?.record ?? {}
1485
+ await noteCopies([{ record: record.id, copy_id: String(copy.id ?? "") || null, origin_event: record.source?.event ?? null }], from, to, context)
1486
+ try {
1487
+ await call("records.delete", { ids: [record.id] }, from.space_id, context)
1488
+ } catch (error) {
1489
+ throw new OperationError("INVALID", `the commitment is in the target space but the original could not be removed (${error.message}).`, "Delete the original with commitment.delete, or keep both.", { extra: { partial: { id: String(copy.id ?? "") } } })
1490
+ }
1491
+ return { ok: true, id: String(copy.id ?? ""), from: { space: from.space_id }, to: { space: to.space_id } }
1492
+ }
1493
+
1494
+
1495
+
1496
+ // ---- A9: proposals ------------------------------------------------------
1497
+
1498
+ /** Suggest an edit to a page (or a new page), at the version read. */
1499
+ async function proposalCreate(context, input = {}) {
1500
+ const space = await spaceOf(context, input.space)
1501
+ const note = input.note === undefined ? undefined : String(input.note)
1502
+ const parent = folderOf(input.parent)
1503
+ // The wiki a new page would land in (`opencode-mem#63`, `#76`): a folder
1504
+ // names the place inside a wiki, and a space may hold several, so `parent`
1505
+ // alone does not say which one. Absent is "the space's own wiki", which a
1506
+ // read reports as no wiki rather than the wrong one.
1507
+ const wiki = input.wiki === undefined || input.wiki === null ? "" : String(input.wiki).trim()
1508
+ if (wiki && !WIKI_ID.test(wiki)) {
1509
+ throw new OperationError("INVALID", `${JSON.stringify(input.wiki ?? null)} is not a wiki id.`, 'Send wiki: "<wiki id>" from mem_wiki list, or leave it out for the space\'s own wiki.')
1510
+ }
1511
+ // The wiki is resolved **in the target space**, as a copy into a wiki is
1512
+ // (`copyPlan`): a wiki the space does not hold, or holds for someone else, is
1513
+ // refused here rather than stored as a destination nothing could honour
1514
+ // (opencode-mem#63, #76, review R2).
1515
+ const named = wiki ? await wikiAt(space, wiki, context) : null
1516
+ /** The wiki the proposal names, as `proposals.create` takes it, once it is the space's. */
1517
+ const wikiField = named ? { wiki } : {}
1518
+ // An added line: the only change an agent may propose to a team page.
1519
+ if (input.section !== undefined || input.text !== undefined) {
1520
+ const targetId = String(input.id ?? input.target_id ?? "").trim()
1521
+ const targetPath = input.path ?? input.targetPath
1522
+ if (!targetId && !targetPath) throw new OperationError("INVALID", "an added line names the page it goes on.", 'Send {target_id, section, text}.')
1523
+ let pageId = targetId || null
1524
+ if (!pageId) {
1525
+ const found = await call("records.get", { paths: [pathOf(targetPath)] }, space.space_id, context)
1526
+ pageId = Array.isArray(found?.records) ? found.records[0]?.id ?? null : null
1527
+ if (!pageId) throw new OperationError("NOT_FOUND", `no page at ${targetPath} in that space.`, "Check the path with mem_page list.")
1528
+ }
1529
+ const made = await call(
1530
+ "proposals.create",
1531
+ { target_id: pageId, section: String(input.section ?? ""), text: String(input.text ?? ""), ...wikiField, ...(note ? { note } : {}) },
1532
+ space.space_id,
1533
+ context,
1534
+ )
1535
+ const proposal = made?.proposal ?? {}
1536
+ return { ok: true, id: String(proposal.id ?? ""), target: { id: pageId, path: made?.target?.path ?? null } }
1537
+ }
1538
+ if (input.path || input.targetPath) {
1539
+ const path = pathOf(input.path ?? input.targetPath)
1540
+ const existing = await call("records.get", { paths: [path] }, space.space_id, context)
1541
+ const target = Array.isArray(existing?.records) ? existing.records.find((entry) => entry.path === path) : null
1542
+ const baseVersion = input.baseVersion ?? input.base_version
1543
+ const made = await call(
1544
+ "proposals.create",
1545
+ {
1546
+ ...(target ? { target_id: target.id, ...(baseVersion !== undefined ? { base_version: Number(baseVersion) } : {}) } : { path }),
1547
+ body: String(input.body ?? ""),
1548
+ ...(input.title ? { title: String(input.title) } : {}),
1549
+ ...wikiField,
1550
+ ...(note ? { note } : {}),
1551
+ },
1552
+ space.space_id,
1553
+ context,
1554
+ )
1555
+ const proposal = made?.proposal ?? {}
1556
+ return { ok: true, id: String(proposal.id ?? ""), target: target ? { id: target.id, path, version: target.version } : { path } }
1557
+ }
1558
+ const title = String(input.title ?? "").trim()
1559
+ if (!title) throw new OperationError("INVALID", "a proposal needs the page it changes, or a title and a parent for a new page.", 'Send path, or parent and title.')
1560
+ const path = `${parent}${slug(title)}`
1561
+ const made = await call("proposals.create", { path, title, body: String(input.body ?? ""), ...wikiField, ...(note ? { note } : {}) }, space.space_id, context)
1562
+ const proposal = made?.proposal ?? {}
1563
+ return { ok: true, id: String(proposal.id ?? ""), target: { path } }
1564
+ }
1565
+
1566
+ /** A proposal, as the person deciding it sees it: what it would change, its state and version. */
1567
+ async function proposalDecidePreview(context, input = {}) {
1568
+ const space = await spaceOf(context, input.space)
1569
+ const key = String(input.id ?? "").trim()
1570
+ const id = key.startsWith("proposal:") ? key.slice("proposal:".length) : key
1571
+ if (!id) throw new OperationError("INVALID", "name the proposal to decide.", "Send id from the proposal list, or from the Inbox.")
1572
+ const found = await call("records.get", { ids: [id] }, space.space_id, context)
1573
+ const record = Array.isArray(found?.records) ? found.records.find((entry) => entry.id === id) : null
1574
+ if (!record) return { found: false, id, version: 0, state: "", kind: "", space: space.space_id, text: "" }
1575
+ let held = ""
1576
+ if (record.type === "team_write") {
1577
+ try {
1578
+ held = String(JSON.parse(record.body)?.records?.[0]?.body ?? "")
1579
+ } catch {
1580
+ held = ""
1581
+ }
1582
+ }
1583
+ return {
1584
+ found: true,
1585
+ id: record.id,
1586
+ version: Number(record.version) || 0,
1587
+ state: String(record.status ?? ""),
1588
+ kind: String(record.type ?? ""),
1589
+ space: space.space_id,
1590
+ text: String(held || record.fields?.payload?.body || record.body || "").slice(0, 4000),
1591
+ }
1592
+ }
1593
+
1594
+ /** Accept a proposal, optionally with the person's own edits (a different body). */
1595
+ async function proposalAccept(context, input = {}) {
1596
+ const space = await spaceOf(context, input.space)
1597
+ const id = String(input.id ?? "").trim()
1598
+ if (!id) throw new OperationError("INVALID", "name the proposal to accept.", "Send id from proposal.create, or from the proposal list.")
1599
+ const edits = input.edits
1600
+ const decision = edits === undefined ? "accept" : "edit"
1601
+ const payload = edits === undefined ? undefined : typeof edits === "object" && edits !== null ? edits : { body: String(edits) }
1602
+ try {
1603
+ const done = await call("review.decide", { id, decision, ...(payload ? { payload } : {}), ...(input.confirmPinned === true ? { confirm_pinned: true } : {}) }, space.space_id, context)
1604
+ // The answer names the record the decision made, by its id: Jelly holds
1605
+ // every answer to the action's declared `output`, where `applied` is a
1606
+ // string and nothing else. Records answers the whole record; the act
1607
+ // answers what it is.
1608
+ const appliedId = typeof done?.applied?.id === "string" ? done.applied.id : null
1609
+ return { ok: true, id, state: String(done?.proposal?.status ?? "accepted"), ...(appliedId ? { applied: appliedId } : {}) }
1610
+ } catch (error) {
1611
+ throw fromService(error)
1612
+ }
1613
+ }
1614
+
1615
+ /** Ask for changes on an open proposal: a note, and nothing applied. */
1616
+ async function proposalAskChanges(context, input = {}) {
1617
+ const space = await spaceOf(context, input.space)
1618
+ const id = String(input.id ?? "").trim()
1619
+ const note = String(input.note ?? "").trim()
1620
+ if (!id) throw new OperationError("INVALID", "name the proposal to ask about.", "Send id and note.")
1621
+ if (!note) throw new OperationError("INVALID", "say what should change.", 'Send note: "keep the November date".')
1622
+ try {
1623
+ const done = await call("proposals.askChanges", { id, note }, space.space_id, context)
1624
+ return { ok: true, id, state: String(done?.proposal?.status ?? "proposed") }
1625
+ } catch (error) {
1626
+ throw fromService(error)
1627
+ }
1628
+ }
1629
+
1630
+ /** Reject a proposal: it closes, and no page changes. */
1631
+ async function proposalReject(context, input = {}) {
1632
+ const space = await spaceOf(context, input.space)
1633
+ const id = String(input.id ?? "").trim()
1634
+ if (!id) throw new OperationError("INVALID", "name the proposal to reject.", "Send id.")
1635
+ try {
1636
+ const done = await call("review.decide", { id, decision: "reject", ...(input.note ? { reason: String(input.note) } : {}) }, space.space_id, context)
1637
+ return { ok: true, id, state: String(done?.proposal?.status ?? "rejected") }
1638
+ } catch (error) {
1639
+ throw fromService(error)
1640
+ }
1641
+ }
1642
+
1643
+ // ---- A11: space.join's two ops (join, request) ------------------------
1644
+
1645
+ // ---- A11: deciding a join request, and who may join --------------------
1646
+
1647
+ /** The pending join request an owner or admin may decide, by id. */
1648
+ async function joinRequestById(requestId) {
1649
+ const id = String(requestId ?? "").trim()
1650
+ if (!id) throw new OperationError("INVALID", "name the join request.", "Send requestId from the join-request list.")
1651
+ let answer
1652
+ try {
1653
+ answer = await control.listJoinRequests({ userId: userId() })
1654
+ } catch (error) {
1655
+ throw fromService(error)
1656
+ }
1657
+ const rows = Array.isArray(answer?.requests) ? answer.requests : []
1658
+ const found = rows.find((row) => String(row.id ?? "") === id)
1659
+ if (!found) throw new OperationError("NOT_FOUND", `no join request ${id} is waiting in a space you administer.`, "Read the open requests, or check that you own or administer the space.")
1660
+ return found
1661
+ }
1662
+
1663
+ /**
1664
+ * What deciding a join request changes: the asker gains read access, and
1665
+ * with a decline nobody does. A read: nothing here changes anything.
1666
+ */
1667
+ async function joinRequestPreview(context, input = {}) {
1668
+ const row = await joinRequestById(input.requestId)
1669
+ const person = row.user?.user_id ? { user_id: String(row.user.user_id), name: row.user.name ?? null } : null
1670
+ return {
1671
+ ok: true,
1672
+ requestId: String(row.id),
1673
+ space: { id: String(row.space?.id ?? ""), name: row.space?.name ?? null },
1674
+ user: person,
1675
+ note: row.note ?? null,
1676
+ gainAccess: person ? [{ ...person, access: "read" }] : [],
1677
+ loseAccess: [],
1678
+ affected: 1,
1679
+ }
1680
+ }
1681
+
1682
+ /** Approve or decline a join request: the space's owner or admins decide it. */
1683
+ async function joinRequestDecide(context, input = {}) {
1684
+ const decision = String(input.decision ?? "").trim()
1685
+ if (!["approve", "decline"].includes(decision)) {
1686
+ throw new OperationError("INVALID", `decision is "approve" or "decline", not ${JSON.stringify(input.decision ?? null)}.`, 'Send decision: "approve" or "decline".')
1687
+ }
1688
+ const row = await joinRequestById(input.requestId)
1689
+ try {
1690
+ const done = await control.decideJoinRequest({
1691
+ userId: userId(),
1692
+ requestId: String(row.id),
1693
+ decision,
1694
+ ...(input.note ? { note: String(input.note) } : {}),
1695
+ })
1696
+ return { ok: true, requestId: String(row.id), state: done.state || (decision === "approve" ? "accepted" : "declined"), space: { id: String(row.space?.id ?? ""), name: row.space?.name ?? null } }
1697
+ } catch (error) {
1698
+ const failure = fromService(error)
1699
+ if (failure.code === "NOT_OWNER" || Number(error?.status) === 403) {
1700
+ throw new OperationError("NOT_OWNER", failure.what, "Only the space's owner or an admin of it decides who joins.", { cause: error })
1701
+ }
1702
+ throw failure
1703
+ }
1704
+ }
1705
+
1706
+ /**
1707
+ * What changing who may join would change, read from the store: the members
1708
+ * now, the requests that would become direct joins, and who could then find
1709
+ * the space. The organisation's own roster is not a list this build can read,
1710
+ * so the answer names the population, never people it cannot see.
1711
+ */
1712
+ async function spaceVisibilityPreview(context, input = {}) {
1713
+ const space = await spaceOf(context, input.space)
1714
+ const to = String(input.visibility ?? "").trim()
1715
+ if (!["invite", "open"].includes(to)) {
1716
+ throw new OperationError("INVALID", `visibility is "invite" or "open", not ${JSON.stringify(input.visibility ?? null)}.`, 'Send visibility: "invite" or "open".')
1717
+ }
1718
+ let listed
1719
+ try {
1720
+ listed = await control.listSpaces({ userId: userId() })
1721
+ } catch (error) {
1722
+ throw fromService(error)
1723
+ }
1724
+ const row = (Array.isArray(listed) ? listed : []).find((entry) => String(entry.space_id ?? "") === space.space_id)
1725
+ const from = String(row?.visibility ?? "invite")
1726
+ const rows = await members(space.space_id)
1727
+ let pendingRequests = 0
1728
+ if (to === "open") {
1729
+ try {
1730
+ const answer = await control.listJoinRequests({ userId: userId() })
1731
+ pendingRequests = (Array.isArray(answer?.requests) ? answer.requests : []).filter((entry) => String(entry.space?.id ?? "") === space.space_id).length
1732
+ } catch {
1733
+ // Only an owner or admin reads the list; the count is then unknown.
1734
+ pendingRequests = 0
1735
+ }
1736
+ }
1737
+ return {
1738
+ ok: true,
1739
+ space: { id: space.space_id, name: space.name ?? row?.name ?? null },
1740
+ from,
1741
+ to,
1742
+ members: rows.length,
1743
+ pendingRequests,
1744
+ discoverable:
1745
+ to === "open"
1746
+ ? "every active member of your organisation could find and join it, without an invitation"
1747
+ : "only the people you add could reach it; it would not be listed to anyone",
1748
+ unaffected: to === "open" ? [] : [],
1749
+ }
1750
+ }
1751
+
1752
+ /** Change who may join a shared space: its owner's own act, in the console. */
1753
+ async function spaceVisibility(context, input = {}) {
1754
+ const space = await spaceOf(context, input.space)
1755
+ const visibility = String(input.visibility ?? "").trim()
1756
+ if (!["invite", "open"].includes(visibility)) {
1757
+ throw new OperationError("INVALID", `visibility is "invite" or "open", not ${JSON.stringify(input.visibility ?? null)}.`, 'Send visibility: "invite" or "open".')
1758
+ }
1759
+ try {
1760
+ const done = await control.updateVisibility({ userId: userId(), spaceId: space.space_id, visibility, ...(context?.p2 ? { p2: context.p2 } : {}) })
1761
+ return { ok: true, space: { id: space.space_id, name: done.space?.name ?? space.name ?? null }, visibility: done.visibility || visibility }
1762
+ } catch (error) {
1763
+ throw fromService(error)
1764
+ }
1765
+ }
1766
+
1767
+ /**
1768
+ * A space's lifecycle, one op at a time: rename it, archive it, unarchive it,
1769
+ * or leave it. Each is G2-P at the control plane, so the reservation the act
1770
+ * carries is sent with the request; a bare key is refused `NEEDS_APPROVAL`.
1771
+ */
1772
+ async function spaceManage(context, input = {}) {
1773
+ const op = String(input.op ?? "")
1774
+ if (!["rename", "archive", "unarchive", "leave"].includes(op)) throw new OperationError("INVALID", `op is "rename", "archive", "unarchive" or "leave", not ${JSON.stringify(input.op ?? null)}.`, "Send one of them.")
1775
+ const space = await spaceOf(context, input.space)
1776
+ const p2 = context?.p2 ?? null
1777
+ try {
1778
+ if (op === "rename") {
1779
+ const name = String(input.name ?? "").trim()
1780
+ if (!name || name.length > 120) throw new OperationError("INVALID", "a new name is 1 to 120 characters.", 'Send name: "Harbour team".')
1781
+ const done = await control.updateSpace({ userId: userId(), spaceId: space.space_id, name, p2 })
1782
+ return { ok: true, op, space: { id: space.space_id, name: done.space?.name ?? name } }
1783
+ }
1784
+ // Unarchiving is the console's plain status change: it needs no digest,
1785
+ // because it only ever makes a space reachable again.
1786
+ if (op === "unarchive") {
1787
+ // No digest (it only makes the space reachable again), but the
1788
+ // reservation still travels: control is G2-P and answers a bare key
1789
+ // `NEEDS_APPROVAL`.
1790
+ const done = await control.updateSpace({ userId: userId(), spaceId: space.space_id, status: "active", p2 })
1791
+ return { ok: true, op, space: { id: space.space_id, name: done.space?.name ?? null } }
1792
+ }
1793
+ if (op === "archive" || op === "leave") {
1794
+ // The digest is the state the person was shown. A press from a real
1795
+ // Jelly cannot send it back — the host presses with the same input it
1796
+ // previewed — so Memory's preview snapshot supplies it
1797
+ // (docs/design/actions-0.11-preview-snapshots.md); a caller that does
1798
+ // name one keeps its own, checked here against control's state now. A
1799
+ // press with neither is refused rather than filled in: a digest this
1800
+ // build invented would not be the state the person saw.
1801
+ const digest = String(input.expectedDigest ?? "").trim()
1802
+ if (!digest) {
1803
+ throw new OperationError(
1804
+ "INVALID",
1805
+ `a ${op === "leave" ? "leave" : "archive"} is signed for the space's state as the person saw it, and this press carries no digest.`,
1806
+ `${op === "leave" ? "Leave" : "Archive"} it from its preview, which supplies the digest, so the press is for exactly that state.`,
1807
+ )
1808
+ }
1809
+ const preview = await control.previewSpace({ userId: userId(), spaceId: space.space_id, action: op })
1810
+ if (digest !== preview.digest) {
1811
+ throw new OperationError("VERSION_CONFLICT", `the space changed since it was shown (${preview.summary || op}).`, "Read it again, then press again.")
1812
+ }
1813
+ if (op === "leave") {
1814
+ const done = await control.leaveSpace({ userId: userId(), spaceId: space.space_id, expectedDigest: digest, p2 })
1815
+ return { ok: true, op, left: done.left === true, space: { id: space.space_id } }
1816
+ }
1817
+ const done = await control.updateSpace({ userId: userId(), spaceId: space.space_id, status: "archived", expectedDigest: digest, p2 })
1818
+ return { ok: true, op, space: { id: space.space_id, name: done.space?.name ?? null } }
1819
+ }
1820
+ } catch (error) {
1821
+ if (error instanceof OperationError) throw error
1822
+ throw fromService(error)
1823
+ }
1824
+ throw new OperationError("INVALID", `"${op}" is not a space change this build makes.`, "Send rename, archive, unarchive or leave.")
1825
+ }
1826
+
1827
+ /** What one space op would change, with the op's own name; nothing is changed. */
1828
+ async function spaceManagePreview(context, input = {}) {
1829
+ const op = String(input.op ?? "")
1830
+ if (!["rename", "archive", "unarchive", "leave"].includes(op)) throw new OperationError("INVALID", `op is "rename", "archive", "unarchive" or "leave", not ${JSON.stringify(input.op ?? null)}.`, "Send one of them.")
1831
+ const space = await spaceOf(context, input.space)
1832
+ if (op === "rename" || op === "unarchive") {
1833
+ // Neither takes a digest: a rename changes the space's name and nothing
1834
+ // else, and unarchiving only makes it reachable again. Control's preview
1835
+ // reads only the two changes it guards (archive, leave).
1836
+ if (op === "rename") {
1837
+ const name = String(input.name ?? "").trim()
1838
+ if (!name || name.length > 120) throw new OperationError("INVALID", "a new name is 1 to 120 characters.", 'Send name: "Harbour team".')
1839
+ return { ok: true, op, label: "Rename the space", space: { id: space.space_id, name: space.name ?? null }, to: name, reversible: true }
1840
+ }
1841
+ return { ok: true, op, label: "Unarchive the space", space: { id: space.space_id, name: space.name ?? null }, summary: "The space is reachable again for every member", reversible: true }
1842
+ }
1843
+ try {
1844
+ const preview = await control.previewSpace({ userId: userId(), spaceId: space.space_id, action: op })
1845
+ return {
1846
+ ok: true,
1847
+ // The preview names the op: leaving is not the same press as archiving.
1848
+ op,
1849
+ label: op === "leave" ? "Leave the space" : op === "archive" ? "Archive the space" : "Unarchive the space",
1850
+ space: { id: space.space_id, name: preview.space?.name ?? space.name ?? null },
1851
+ summary: preview.summary,
1852
+ reversible: preview.reversible,
1853
+ expectedDigest: preview.digest,
1854
+ }
1855
+ } catch (error) {
1856
+ throw fromService(error)
1857
+ }
1858
+ }
1859
+
1860
+ /** Join an open space. */
1861
+ async function spaceJoin(context, input = {}) {
1862
+ const space = String(input.space ?? "").trim()
1863
+ if (!space) throw new OperationError("INVALID", "name the space to join.", "Send space: \"<id>\" from the list of spaces to join.")
1864
+ try {
1865
+ const joined = await control.joinSpace({ userId: userId(), spaceId: space })
1866
+ return { ok: true, state: joined.state || "joined", space: space }
1867
+ } catch (error) {
1868
+ throw fromService(error)
1869
+ }
1870
+ }
1871
+
1872
+ /** Ask to join an invite-only space, with a note. */
1873
+ async function spaceRequestJoin(context, input = {}) {
1874
+ const space = String(input.space ?? "").trim()
1875
+ if (!space) throw new OperationError("INVALID", "name the space to ask to join.", "Send space: \"<id>\" from the list of spaces to join.")
1876
+ try {
1877
+ const asked = await control.requestJoinSpace({ userId: userId(), spaceId: space, ...(input.note ? { note: String(input.note) } : {}) })
1878
+ return { ok: true, state: asked.state || "pending", requestId: asked.requestId }
1879
+ } catch (error) {
1880
+ throw fromService(error)
1881
+ }
1882
+ }
1883
+
1884
+ return {
1885
+ // A2
1886
+ pageSave,
1887
+ pageSavePreview,
1888
+ // A3
1889
+ pageMove,
1890
+ pageMovePreview,
1891
+ // A4
1892
+ pageDelete,
1893
+ pageDeletePreview,
1894
+ wikiDelete,
1895
+ wikiDeletePreview,
1896
+ // A5
1897
+ spaceCreate,
1898
+ // A6
1899
+ shareGrant,
1900
+ shareGrantPreview,
1901
+ shareRevoke,
1902
+ shareRevokePreview,
1903
+ // A7
1904
+ shareTransfer,
1905
+ shareTransferPreview,
1906
+ shareAccept,
1907
+ shareDecline,
1908
+ // A8
1909
+ pageCopy,
1910
+ pageCopyPreview,
1911
+ shareCopy,
1912
+ shareCopyPreview,
1913
+ // A memory organiser
1914
+ memoryOrganise,
1915
+ memoryOrganisePreview,
1916
+ // A13's move
1917
+ commitmentMove,
1918
+ // A9
1919
+ proposalCreate,
1920
+ proposalDecidePreview,
1921
+ proposalAccept,
1922
+ proposalAskChanges,
1923
+ proposalReject,
1924
+ // A11
1925
+ spaceJoin,
1926
+ spaceRequestJoin,
1927
+ spaceManage,
1928
+ spaceManagePreview,
1929
+ joinRequestDecide,
1930
+ joinRequestPreview,
1931
+ spaceVisibility,
1932
+ spaceVisibilityPreview,
1933
+ }
1934
+ }
1935
+
1936
+ export { CODES }