@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
package/src/actions.js ADDED
@@ -0,0 +1,1690 @@
1
+ /**
2
+ * Memory's actions in Jelly: what a person's own page may change, as the person,
3
+ * under a host-signed action grant (#58 section A; the ADR is
4
+ * docs/design/adr-verified-caller-grants.md).
5
+ *
6
+ * Jelly draws the confirmation, signs one `jelly-act+jwt` for that one action and
7
+ * that one input, and carries it to the plugin's `act.<name>`. This module is the
8
+ * plugin's side of that contract:
9
+ *
10
+ * 1. **The declaration** (`ACTIONS`): what Jelly is told Memory offers, which
11
+ * page may call each one, the confirmation it draws, and the class of device
12
+ * it needs. `package.json`'s `jelly.actions` must equal it
13
+ * (`test/actions.test.js`), and Jelly's own schema checks it
14
+ * (`npm run check:jelly:master`).
15
+ * 2. **The verifier** (`createPluginVerifier`): the grant's signature, audience,
16
+ * action, class, times, input digest and single use, in this engine, against
17
+ * the public half of the host's key the engine was handed
18
+ * (`globalThis[Symbol.for("jelly.action-key")]`), or the plugin option
19
+ * `actionKeysFile` on a host that publishes a file instead. It is the first of
20
+ * two doors: records verifies the same grant again, binds it to the caller's
21
+ * own identity and spends its `jti` in the ledger (`acts.apply`). Neither door
22
+ * trusts the other.
23
+ * 3. **The handlers** (`createActionHandlers`): run the act as the person who
24
+ * clicked (`asVerifiedView`, never the engine owner's credential, never a
25
+ * pasted key), call records' `acts.apply` with the input and the grant
26
+ * unchanged, and answer the receipt or a `CODE: what happened. Next step: …`
27
+ * refusal.
28
+ * 4. **The previews** (`createActionReads`): the read a Jelly `always`
29
+ * confirmation shows first, and the one A12's About-you flow calls. A preview
30
+ * changes nothing.
31
+ *
32
+ * **Agents never carry a grant.** No tool, `rpc` method or plugin option mints
33
+ * one or accepts one: the only caller of `acts.apply` here is an `act.<name>`
34
+ * handler, which Jelly's own RPC fence refuses to anything but the host's call.
35
+ * An agent's change keeps its own door: the tool, its ask, and a held write.
36
+ *
37
+ * **Dark by default.** `config.actions` is off, so every act answers
38
+ * `ACTIONS_OFF` and nothing is sent to records; records' `RECORDS_ACTIONS_ENABLED`
39
+ * is empty too, so even a call that got past this engine changes nothing. The
40
+ * declaration itself is static (Jelly reads `package.json`), so a release that
41
+ * must draw no control withdraws `jelly.actions`; the flag makes the declared
42
+ * controls inert until Jelly's eight confirmations on #49 settle.
43
+ */
44
+ import { createHash, createPublicKey } from "node:crypto"
45
+ import { GRANT_AUDIENCE, GRANT_TYP, canonicalJson, keyThumbprint, verifyActionGrant } from "./action-grant.js"
46
+ import { createActionKeys } from "./action-grant-keys.js"
47
+ import { asVerifiedView } from "./credentials.js"
48
+ import { HELD_WRITE_TITLE, completeHeldWrite } from "./tools/held-write.js"
49
+ import { MIN_ERASE_CHARS, eraseLines, matchingLines } from "./views/profile.js"
50
+ import { pageBody, pageMeeting, pageTranscript } from "./views/contracts.js"
51
+ import { oneLine } from "./util.js"
52
+
53
+ /** Where Jelly publishes its action key's public half in an engine (`@jelly/opencode`). */
54
+ export const PUBLISHED_ACTION_KEY = Symbol.for("jelly.action-key")
55
+
56
+ /** The `jellySpeaker` input key the host fills with the person whose device clicked. */
57
+ const SPEAKER = "jellySpeaker"
58
+
59
+ /**
60
+ * Jelly's cap on a confirmation's preview, as Jelly defines it
61
+ * (`ACTION_PREVIEW_MAX_CHARS = 4000`, `protocol/contracts/src/plugin-actions.ts:244`).
62
+ * The host renders the preview as the indented JSON of the whole answer and
63
+ * slices past the cap (`backend/host/src/plugin-actions/service.ts:344,380`;
64
+ * `plain` at `:469`), so a longer answer is shown with its tail cut.
65
+ */
66
+ export const JELLY_PREVIEW_MAX_CHARS = 4000
67
+
68
+ /**
69
+ * The longest edited words a held write may carry, so that **nothing unseen
70
+ * lands**: 4,000 less the 500 the answer's own envelope and JSON escaping take
71
+ * at most. The same limit is declared at records (`records/src/held-text.js`),
72
+ * where the press is refused again; the test holds the two to each other.
73
+ */
74
+ export const HELD_EDITS_MAX = 3500
75
+
76
+ /** The edited words' JSON length, as Jelly's `plain` counts it, and the limit. */
77
+ function heldEditsProblem(text) {
78
+ if (typeof text !== "string" || !text) return null
79
+ const length = JSON.stringify(text).length - 2
80
+ return length > HELD_EDITS_MAX ? { length, limit: HELD_EDITS_MAX } : null
81
+ }
82
+
83
+ /** An answer Jelly would show whole: its indented JSON fits the preview cap. */
84
+ function shownWhole(answer) {
85
+ return (JSON.stringify(answer, null, 2) ?? "null").length <= JELLY_PREVIEW_MAX_CHARS
86
+ }
87
+
88
+ /** The refusal both the preview and the press answer, in one sentence family. */
89
+ function heldEditsRefusal(problem) {
90
+ return `the corrected words are ${problem.length} characters of preview text, and a confirmation shows at most ${problem.limit}, so their end would land unseen`
91
+ }
92
+
93
+ /**
94
+ * The four actions whose control path needs **P2** — a verified host grant the
95
+ * space-lifecycle gateway and control can check. P2 is built and dark at the
96
+ * deployment: it works only where `P2_RESERVATION_KEY` is set to the same value
97
+ * in records, the gateway and control (docs/design/p2-control.md). On now, with
98
+ * Jelly 0.4.0-beta.20's protocol major 7 (48 actions); a deployment without the
99
+ * key refuses each press with `P2_UNAVAILABLE`, naming the missing secret.
100
+ */
101
+ export const ACTIONS_NEED_CONTROL_P2 = true
102
+
103
+ /** The actions held back while `ACTIONS_NEED_CONTROL_P2` is off. */
104
+ export const HELD_FOR_CONTROL_P2 = Object.freeze(["share.transfer", "share.decide", "space.visibility", "space.manage"])
105
+
106
+ /**
107
+ * The two acts built for Jelly's #77 and #78, now declared: Jelly 0.4.0-beta.20
108
+ * carries protocol major 7 and caps a declaration at 48 actions, so 28 declared
109
+ * plus the four for control's P2 plus these two are 34. Nothing was merged or
110
+ * trimmed to make room. `memory.saveLine` is not built and is not declared here.
111
+ */
112
+ export const ACTIONS_NEED_ROOM = true
113
+
114
+ /** The acts that waited on room under Jelly's old cap; declared now (`ACTIONS_NEED_ROOM`). */
115
+ export const HELD_FOR_CAP = Object.freeze(["suggestion.dismiss", "held.decide"])
116
+
117
+ /** The action somewhere the host draws no control yet (a host bug, or a stale declaration). */
118
+ const noControl = "This Memory build declares no such action, so nothing changed."
119
+
120
+ const text = (max = 300) => ({ type: "string", maxLength: max })
121
+ const id = { type: "string", maxLength: 200 }
122
+
123
+ /** An action's input: its own fields and the optional speaker the host fills, never required of a page. */
124
+ function actionInput(properties = {}, required = []) {
125
+ return {
126
+ type: "object",
127
+ additionalProperties: false,
128
+ ...(required.length > 0 ? { required } : {}),
129
+ properties: { ...properties, [SPEAKER]: { type: "string" } },
130
+ }
131
+ }
132
+
133
+ /**
134
+ * An action's answer: the receipt of what changed, or a coded refusal. Both are
135
+ * this one shape, because Jelly holds every answer to it.
136
+ */
137
+ const actionOutput = {
138
+ type: "object",
139
+ required: ["ok"],
140
+ properties: {
141
+ ok: { type: "boolean" },
142
+ /** The record the act changed, when there is one. */
143
+ id: id,
144
+ /** Its new version, where the act made one. */
145
+ version: { type: "integer", minimum: 0 },
146
+ /** A commitment's or a proposal's state now. */
147
+ state: text(40),
148
+ /** The record a review's accept made, when it made one. */
149
+ applied: id,
150
+ // The shared space a private held write stays out of, or (a space act's
151
+ // answer) the space it changed, as `{id, name}`: both shapes are answers
152
+ // the acts make, so the declaration admits either.
153
+ space: { anyOf: [text(200), { type: "object", properties: { id: text(200), name: text(200) }, additionalProperties: false }] },
154
+ /** How many lines or records the act changed. */
155
+ count: { type: "integer", minimum: 0 },
156
+ /** The erasure receipt's state, and the profile snapshot it was signed for. */
157
+ snapshot: text(64),
158
+ erased: { type: "integer", minimum: 0 },
159
+ /** A refusal: the code the page shows, and the sentence under it. */
160
+ code: text(40),
161
+ message: text(600),
162
+ },
163
+ }
164
+
165
+ /**
166
+ * `page.save`'s answer (Jelly's #61): the shared receipt, and where the page
167
+ * landed. Jelly reads `path` to save the same meeting's page again and `type` to
168
+ * know it is a `meeting`, so the declaration names both rather than leaving a
169
+ * host to guess from `id`.
170
+ */
171
+
172
+ const pageSaveOutput = {
173
+ ...actionOutput,
174
+ properties: { ...actionOutput.properties, path: text(300), type: text(40) },
175
+ }
176
+
177
+ /**
178
+ * The actions to declare, in `jelly.actions`. Each name is also the act records
179
+ * applies and the key its history records, so one word runs end to end.
180
+ *
181
+ * `views` names the plugin's own pages that may call it (Jelly's page grant), and
182
+ * `tool` names the agent's door to the same change: whatever a person does here,
183
+ * an agent given Memory can do too, through the tool and its ask.
184
+ */
185
+ export const ACTIONS = Object.freeze([
186
+ // A13: a commitment's five controls. Its own private memory, so `chat`, and
187
+ // the press is the whole confirmation: done, cancelled and snoozed can all be
188
+ // put back.
189
+ ...[
190
+ ["commitment.done", "mark a commitment done", "Marked done."],
191
+ ["commitment.cancel", "drop a commitment", "Dropped."],
192
+ ["commitment.reopen", "reopen a commitment", "Reopened."],
193
+ ].map(([name, label, done]) => ({
194
+ name,
195
+ label,
196
+ target: "engine",
197
+ class: "chat",
198
+ confirm: "never",
199
+ views: ["commitments"],
200
+ done,
201
+ input: actionInput({ id, space: text(128), revision: { type: "integer", minimum: 1 } }, ["id", "space", "revision"]),
202
+ output: actionOutput,
203
+ tool: "mem.commitments",
204
+ })),
205
+ {
206
+ name: "commitment.snooze",
207
+ label: "snooze a commitment to another day",
208
+ target: "engine",
209
+ class: "chat",
210
+ confirm: "never",
211
+ views: ["commitments"],
212
+ done: "Snoozed.",
213
+ input: actionInput({ id, due: text(40), space: text(128), revision: { type: "integer", minimum: 1 } }, ["id", "due", "space", "revision"]),
214
+ output: actionOutput,
215
+ tool: "mem.commitments",
216
+ },
217
+ {
218
+ name: "commitment.edit",
219
+ label: "change what a commitment says",
220
+ target: "engine",
221
+ class: "chat",
222
+ confirm: "never",
223
+ views: ["commitments"],
224
+ done: "Changed.",
225
+ input: actionInput({ id, what: text(300), due: text(40), space: text(128), revision: { type: "integer", minimum: 1 } }, ["id", "what", "space", "revision"]),
226
+ output: actionOutput,
227
+ tool: "mem.commitments",
228
+ },
229
+ // A13's two more controls: adding one, deleting one. Add is the person's own
230
+ // private memory, so `chat` and no confirmation; a delete cannot be put back,
231
+ // so it is an owner device's, always confirmed. Jelly binds neither by name.
232
+ {
233
+ name: "commitment.create",
234
+ label: "add a commitment",
235
+ target: "engine",
236
+ class: "chat",
237
+ confirm: "never",
238
+ views: ["commitments"],
239
+ done: "Added.",
240
+ input: actionInput({ space: text(128), what: text(300), due: text(40) }, ["what"]),
241
+ output: actionOutput,
242
+ tool: "mem.commitments",
243
+ },
244
+ {
245
+ name: "commitment.delete",
246
+ label: "delete a commitment",
247
+ target: "engine",
248
+ class: "local",
249
+ confirm: "always",
250
+ // The words the person is deleting, so the confirmation says what goes and
251
+ // not only which id.
252
+ preview: "commitment.delete.preview",
253
+ summary: ["what"],
254
+ views: ["commitments"],
255
+ done: "Deleted.",
256
+ input: actionInput({ id, space: text(128), what: text(300), revision: { type: "integer", minimum: 1 } }, ["id", "revision"]),
257
+ output: actionOutput,
258
+ tool: "mem.commitments",
259
+ },
260
+ // A commitment to another space: the console's own move (a copy, read back,
261
+ // then the source removed), so it can end `partial`.
262
+ {
263
+ name: "commitment.move",
264
+ label: "move a commitment to another space",
265
+ target: "engine",
266
+ class: "chat",
267
+ confirm: "always",
268
+ preview: "commitment.move.preview",
269
+ // The words that move, and where they go.
270
+ summary: ["what", "to"],
271
+ views: ["commitments"],
272
+ done: "Moved.",
273
+ input: actionInput({ space: text(128), id, what: text(300), revision: { type: "integer", minimum: 1 }, to: { type: "object", additionalProperties: false, required: ["space"], properties: { space: text(128) } } }, ["space", "id", "revision", "to"]),
274
+ output: actionOutput,
275
+ tool: "mem.commitments",
276
+ op: "commitmentMove",
277
+ },
278
+ // A10: Keep, Edit and Forget of what is not saved yet, and a held write's
279
+ // accept, private or decline. `op` is the discriminator: Jelly's schema lets
280
+ // one action take a discriminating input, so five controls cost one name of
281
+ // the 32 the declaration has.
282
+ {
283
+ name: "review.decide",
284
+ label: "decide what Memory held for you",
285
+ target: "engine",
286
+ class: "chat",
287
+ confirm: "always",
288
+ preview: "review.decide.preview",
289
+ summary: ["op"],
290
+ views: ["review", "today"],
291
+ done: "Decided.",
292
+ input: actionInput({ id, op: { type: "string", enum: ["accept", "edit", "reject", "private", "decline"] }, revision: { type: "integer", minimum: 1 }, text: text(4000) }, ["id", "op"]),
293
+ output: actionOutput,
294
+ tool: "mem.spaces",
295
+ },
296
+ // Jelly's answer 5: the class is per action. A memory the person confirms or
297
+ // corrects is a chat act, session-confirmed; forgetting it cannot be taken
298
+ // back, so it is its own action, an owner device's, always confirmed. A
299
+ // member's forget stays on the agent's tool (`mem_forget` and its ask).
300
+ {
301
+ name: "memory.revise",
302
+ label: "confirm, correct or add a memory",
303
+ target: "engine",
304
+ class: "chat",
305
+ confirm: "session",
306
+ preview: "memory.revise.preview",
307
+ summary: ["action"],
308
+ views: ["memory"],
309
+ done: "Kept.",
310
+ // `add` writes a new memory (the console's own add); `confirm` and `correct`
311
+ // change one at the version the person saw, so `id` and `revision` are
312
+ // required only for those two. It is the records store's act; a learned atom
313
+ // in the memory core still needs a grant door that does not exist, so
314
+ // `learned/correct` stays console-only (§6).
315
+ input: actionInput({ space: text(128), id, revision: { type: "integer", minimum: 1 }, action: { type: "string", enum: ["confirm", "correct", "add"] }, content: text(56 * 1024) }, ["space", "action"]),
316
+ output: actionOutput,
317
+ tool: "mem.revise",
318
+ },
319
+ // Memories retired, restored or confirmed: one class, one confirmation, and
320
+ // one consequence (the memory stays in its space). A move is **not** here: it
321
+ // changes who can see a memory, so it is a different consequence and needs its
322
+ // own action; this release does not add one (#59 §4.5).
323
+ {
324
+ name: "memory.organise",
325
+ label: "retire, restore or confirm memories",
326
+ target: "engine",
327
+ class: "chat",
328
+ confirm: "always",
329
+ preview: "memory.organise.preview",
330
+ summary: ["op"],
331
+ views: ["memory"],
332
+ done: "Changed.",
333
+ input: actionInput({
334
+ space: text(128),
335
+ op: { type: "string", enum: ["retire", "restore", "confirm"] },
336
+ ids: { type: "array", maxItems: 100, items: id },
337
+ }, ["space", "op", "ids"]),
338
+ output: actionOutput,
339
+ tool: "mem.revise",
340
+ op: "memoryOrganise",
341
+ previewOp: "memoryOrganisePreview",
342
+ },
343
+ {
344
+ name: "memory.forget",
345
+ label: "forget a memory",
346
+ target: "engine",
347
+ class: "local",
348
+ confirm: "always",
349
+ summary: ["id"],
350
+ views: ["memory"],
351
+ done: "Forgotten.",
352
+ input: actionInput({ id, revision: { type: "integer", minimum: 1 } }, ["id", "revision"]),
353
+ output: actionOutput,
354
+ tool: "mem.revise",
355
+ },
356
+ // The Inbox's own decision (Jelly's answers 2 and 6): Memory's key for the
357
+ // item, the decisions the Inbox offers, and the version it showed. It routes
358
+ // to the same review and held-write decisions a review makes.
359
+ {
360
+ name: "inbox.decide",
361
+ label: "decide what waits in your Inbox",
362
+ target: "engine",
363
+ class: "chat",
364
+ confirm: "always",
365
+ preview: "inbox.decide.preview",
366
+ summary: ["decision"],
367
+ views: ["today", "review"],
368
+ done: "Decided.",
369
+ input: actionInput({ itemId: text(200), decision: { type: "string", enum: ["accept", "private", "decline"] }, revision: { type: "integer", minimum: 1 } }, ["itemId", "decision", "revision"]),
370
+ output: actionOutput,
371
+ tool: "mem.spaces",
372
+ },
373
+ // A1: a page's words, at the version the person saw. A team space needs the
374
+ // approval the person's own page draws, so the act answers NEEDS_APPROVAL
375
+ // there and writes nothing.
376
+ {
377
+ name: "page.write",
378
+ label: "write a page in Memory",
379
+ target: "engine",
380
+ class: "chat",
381
+ confirm: "always",
382
+ preview: "page.write.preview",
383
+ summary: ["path"],
384
+ views: ["pages"],
385
+ done: "Saved.",
386
+ // A grant carries at most 64 KiB of input (`MAX_INPUT_BYTES`, ADR §4.4):
387
+ // the body is bounded below that with room for the path, the space and the
388
+ // speaker. A larger page is written by the agent (`mem_page write`) or in
389
+ // Memory's console, where no grant is needed.
390
+ input: actionInput({ space: text(128), path: text(300), body: text(58 * 1024), expectVersion: { type: "integer", minimum: 0 } }, ["space", "path", "body"]),
391
+ output: actionOutput,
392
+ tool: "mem.page",
393
+ },
394
+ // A15: a held team write, edited by its author or kept in their own space.
395
+ {
396
+ name: "write.decide",
397
+ label: "edit a held write, or keep it private",
398
+ target: "engine",
399
+ class: "chat",
400
+ confirm: "always",
401
+ preview: "write.decide.preview",
402
+ summary: ["op"],
403
+ views: ["review", "today"],
404
+ done: "Done.",
405
+ input: actionInput({ id, op: { type: "string", enum: ["edit", "private"] }, revision: { type: "integer", minimum: 1 }, text: text(4000) }, ["id", "op"]),
406
+ output: actionOutput,
407
+ tool: "mem.spaces",
408
+ },
409
+ // #78: a held team write's three decisions, as one action (the cap is tight:
410
+ // one name runs end to end, as `proposal.decide` does). `accept` answers
411
+ // `accepting`, and the handler completes the shared write the one way held
412
+ // writes are completed; `edit` corrects the held words; `drop` saves nothing.
413
+ {
414
+ name: "held.decide",
415
+ needsRoom: true,
416
+ label: "accept, edit or drop a held write",
417
+ target: "engine",
418
+ class: "chat",
419
+ confirm: "always",
420
+ preview: "held.decide.preview",
421
+ // The confirmation shows the op and the words the press would land: for an
422
+ // edit, or an accept with edits, the preview's final text is those words.
423
+ summary: ["op", "edits"],
424
+ views: ["review", "today"],
425
+ done: "Decided.",
426
+ input: actionInput({ id, op: { type: "string", enum: ["accept", "edit", "drop"] }, edits: text(4000), revision: { type: "integer", minimum: 1 } }, ["id", "op"]),
427
+ output: actionOutput,
428
+ tool: "mem.spaces",
429
+ // The version the person was shown is the preview's, never the page's: a
430
+ // press spends the preview's snapshot (records' `previewRequired`).
431
+ stateBound: true,
432
+ },
433
+ // #77: the suggestion card's two answers. "Not now" hides that suggestion
434
+ // once; `forever` also stops suggestions of its kind. It hides, never
435
+ // decides: the proposal still waits in review.
436
+ {
437
+ name: "suggestion.dismiss",
438
+ needsRoom: true,
439
+ label: "hide a suggestion, or stop suggestions of its kind",
440
+ target: "engine",
441
+ class: "chat",
442
+ confirm: "always",
443
+ preview: "suggestion.dismiss.preview",
444
+ summary: ["forever"],
445
+ views: ["today", "review"],
446
+ done: "Hidden.",
447
+ input: actionInput({ id, forever: { type: "boolean" }, revision: { type: "integer", minimum: 1 } }, ["id"]),
448
+ output: actionOutput,
449
+ tool: "mem.spaces",
450
+ stateBound: true,
451
+ },
452
+ // A12: erase a phrase from what Memory holds about you. `local`: it cannot be
453
+ // taken back, so only an owner device signs it (ADR §4.7).
454
+ {
455
+ name: "profile.erase",
456
+ label: "erase a phrase from what Memory holds about you",
457
+ target: "engine",
458
+ class: "local",
459
+ confirm: "always",
460
+ preview: "profile.erase.preview",
461
+ summary: ["phrase"],
462
+ views: ["memory"],
463
+ done: "Erased.",
464
+ input: actionInput({ phrase: text(200), snapshot: text(43) }, ["phrase", "snapshot"]),
465
+ output: actionOutput,
466
+ tool: "mem.forget",
467
+ },
468
+ // ---- A2–A9 and A11: the space and sharing operations (src/ops) ----------
469
+ //
470
+ // Each runs as the person whose device pressed: the plugin verifies the
471
+ // grant, then the operation makes the change under the person's own
472
+ // credential, and the control plane or records decides access.
473
+
474
+ {
475
+ name: "page.save",
476
+ label: "save a page in Memory",
477
+ target: "engine",
478
+ class: "chat",
479
+ confirm: "always",
480
+ preview: "page.save.preview",
481
+ summary: ["path"],
482
+ views: ["pages"],
483
+ done: "Saved.",
484
+ input: actionInput({ space: text(128), path: text(300), folder: text(200), title: text(300), body: pageBody, meeting: pageMeeting, transcript: pageTranscript, files: { type: "array", maxItems: 50, items: text(300) } }, ["body"]),
485
+ output: pageSaveOutput,
486
+ tool: "mem.page",
487
+ op: "pageSave",
488
+ previewOp: "pageSavePreview",
489
+ },
490
+ {
491
+ name: "page.move",
492
+ label: "move a page",
493
+ target: "engine",
494
+ class: "chat",
495
+ confirm: "always",
496
+ preview: "page.move.preview",
497
+ summary: ["path", "prefix", "paths"],
498
+ views: ["pages"],
499
+ done: "Moved.",
500
+ // One page (`path`), a folder (`prefix`) or up to fifty pages (`paths`): one
501
+ // consequence, so one name. `to.folder` is where a list of pages lands.
502
+ input: actionInput({
503
+ space: text(128),
504
+ path: text(300),
505
+ prefix: text(300),
506
+ paths: { type: "array", maxItems: 50, items: text(300) },
507
+ to: { type: "object", additionalProperties: false, properties: { space: text(128), path: text(300), folder: text(200) } },
508
+ }, ["space"]),
509
+ output: actionOutput,
510
+ tool: "mem.page",
511
+ op: "pageMove",
512
+ previewOp: "pageMovePreview",
513
+ },
514
+ {
515
+ name: "page.delete",
516
+ label: "delete a page",
517
+ target: "engine",
518
+ class: "local",
519
+ confirm: "always",
520
+ preview: "page.delete.preview",
521
+ summary: ["path", "paths"],
522
+ views: ["pages"],
523
+ done: "Deleted.",
524
+ // One page (`path`) or up to fifty (`paths`). It stays `local`, and the
525
+ // preview lists every page the press removes.
526
+ input: actionInput({ space: text(128), path: text(300), paths: { type: "array", maxItems: 50, items: text(300) } }, ["space"]),
527
+ output: actionOutput,
528
+ tool: "mem.page",
529
+ op: "pageDelete",
530
+ previewOp: "pageDeletePreview",
531
+ },
532
+ {
533
+ name: "wiki.delete",
534
+ label: "delete a wiki",
535
+ target: "engine",
536
+ class: "local",
537
+ confirm: "always",
538
+ preview: "wiki.delete.preview",
539
+ summary: ["wiki"],
540
+ views: ["pages"],
541
+ done: "Deleted.",
542
+ input: actionInput({ space: text(128), wiki: id }, ["space", "wiki"]),
543
+ output: actionOutput,
544
+ tool: "mem.wiki",
545
+ op: "wikiDelete",
546
+ previewOp: "wikiDeletePreview",
547
+ },
548
+ {
549
+ name: "space.create",
550
+ label: "create a shared space",
551
+ target: "engine",
552
+ class: "chat",
553
+ // A new space that names members hands them access at once, so the
554
+ // confirmation is always drawn (`records/src/acts.js` refuses a weaker one).
555
+ confirm: "always",
556
+ summary: ["name"],
557
+ views: ["memory"],
558
+ done: "Created.",
559
+ input: actionInput({ name: text(120), kind: { type: "string", enum: ["team", "topic"] }, visibility: { type: "string", enum: ["invite", "open"] }, members: { type: "array", maxItems: 100, items: { type: "string" } } }, ["name"]),
560
+ output: actionOutput,
561
+ tool: "mem.spaces",
562
+ op: "spaceCreate",
563
+ },
564
+ {
565
+ name: "share.grant",
566
+ label: "share a space, wiki, folder or page",
567
+ target: "engine",
568
+ class: "chat",
569
+ confirm: "always",
570
+ preview: "share.grant.preview",
571
+ summary: ["person", "access"],
572
+ views: ["memory"],
573
+ done: "Shared.",
574
+ input: actionInput({ space: text(128), target: { type: "object" }, person: text(200), access: { type: "string", enum: ["read", "write"] } }, ["target", "person", "access"]),
575
+ output: actionOutput,
576
+ tool: "mem.share",
577
+ op: "shareGrant",
578
+ previewOp: "shareGrantPreview",
579
+ store: "target.space",
580
+ },
581
+ {
582
+ name: "share.revoke",
583
+ label: "take back someone's access",
584
+ target: "engine",
585
+ // It takes away someone else's access, which the person whose device
586
+ // pressed cannot put back: an owner device's, always confirmed (§4.7).
587
+ class: "local",
588
+ confirm: "always",
589
+ preview: "share.revoke.preview",
590
+ summary: ["person"],
591
+ views: ["memory"],
592
+ done: "Removed.",
593
+ input: actionInput({ space: text(128), target: { type: "object" }, person: text(200) }, ["target", "person"]),
594
+ output: actionOutput,
595
+ tool: "mem.share",
596
+ op: "shareRevoke",
597
+ previewOp: "shareRevokePreview",
598
+ store: "target.space",
599
+ },
600
+ {
601
+ name: "share.transfer",
602
+ needsControlP2: true,
603
+ label: "hand a space on to someone else",
604
+ target: "engine",
605
+ class: "local",
606
+ confirm: "always",
607
+ preview: "share.transfer.preview",
608
+ summary: ["to"],
609
+ views: ["memory"],
610
+ done: "Asked.",
611
+ input: actionInput({ space: text(128), target: { type: "object" }, to: text(200) }, ["space", "to"]),
612
+ output: actionOutput,
613
+ tool: "mem.share",
614
+ op: "shareTransfer",
615
+ previewOp: "shareTransferPreview",
616
+ // A handover changes the space its target names, so the grant is spent
617
+ // there, as the operation acts there.
618
+ store: "target.space",
619
+ },
620
+ {
621
+ name: "share.decide",
622
+ needsControlP2: true,
623
+ label: "accept or decline a space handed to you",
624
+ target: "engine",
625
+ class: "chat",
626
+ confirm: "never",
627
+ summary: ["op"],
628
+ views: ["memory"],
629
+ done: "Decided.",
630
+ // One handover answer, `op` picks accept or decline: one class, one
631
+ // confirmation (neither removes anything), so one name instead of two.
632
+ input: actionInput({ op: { type: "string", enum: ["accept", "decline"] }, requestId: id, note: text(300) }, ["op", "requestId"]),
633
+ output: actionOutput,
634
+ tool: "mem.share",
635
+ op: { by: "op", accept: "shareAccept", decline: "shareDecline" },
636
+ // A handover answer names only the request: it is spent in the person's own store.
637
+ store: null,
638
+ },
639
+ {
640
+ name: "share.copy",
641
+ label: "copy a page or your memories into a space",
642
+ target: "engine",
643
+ class: "chat",
644
+ confirm: "always",
645
+ preview: "share.copy.preview",
646
+ summary: ["op"],
647
+ views: ["pages", "memory"],
648
+ done: "Copied.",
649
+ // One consequence (a copy lands; nothing is removed), so one name for the
650
+ // console's two copies: a page, or the person's own memories.
651
+ input: actionInput({
652
+ op: { type: "string", enum: ["page", "memories"] },
653
+ from: { type: "object", additionalProperties: false, properties: { space: text(128), path: text(300) } },
654
+ to: { type: "object", additionalProperties: false, properties: { space: text(128), folder: text(200), path: text(300), wiki: text(128) } },
655
+ ids: { type: "array", maxItems: 100, items: id },
656
+ // The page's version the preview showed: a copy never takes a later one.
657
+ version: { type: "integer", minimum: 1 },
658
+ // The reason a memories copy carries, recorded on each copy (the
659
+ // console's rationale): required when `op` is memories.
660
+ note: text(300),
661
+ }, ["op"]),
662
+ output: actionOutput,
663
+ tool: "mem.page",
664
+ op: "shareCopy",
665
+ previewOp: "shareCopyPreview",
666
+ store: "from.space",
667
+ // A copy is signed for the page's version and lands at a file its preview
668
+ // computed, and a host's press sends neither: the preview keeps them
669
+ // (`PREVIEW_SNAPSHOTS`), and the press spends them once.
670
+ stateBound: true,
671
+ },
672
+ {
673
+ name: "proposal.create",
674
+ label: "suggest an edit to a page",
675
+ target: "engine",
676
+ class: "chat",
677
+ confirm: "session",
678
+ summary: ["path"],
679
+ views: ["pages"],
680
+ done: "Suggested.",
681
+ input: actionInput(
682
+ { space: text(128), path: text(300), wiki: text(128), parent: text(300), title: text(300), body: text(56 * 1024), note: text(2000), baseVersion: { type: "integer", minimum: 1 } },
683
+ ["body"],
684
+ ),
685
+ output: actionOutput,
686
+ tool: "mem.page",
687
+ op: "proposalCreate",
688
+ },
689
+ {
690
+ name: "proposal.decide",
691
+ label: "decide a suggested edit",
692
+ target: "engine",
693
+ class: "chat",
694
+ confirm: "always",
695
+ preview: "proposal.decide.preview",
696
+ summary: ["op"],
697
+ views: ["review", "pages"],
698
+ done: "Decided.",
699
+ input: actionInput({ space: text(128), id, op: { type: "string", enum: ["accept", "askChanges", "reject"] }, edits: text(56 * 1024), note: text(2000) }, ["id", "op"]),
700
+ output: actionOutput,
701
+ tool: "mem.spaces",
702
+ op: { by: "op", accept: "proposalAccept", askChanges: "proposalAskChanges", reject: "proposalReject" },
703
+ previewOp: "proposalDecidePreview",
704
+ },
705
+ {
706
+ name: "space.join",
707
+ label: "join an open space, or ask to",
708
+ target: "engine",
709
+ class: "chat",
710
+ confirm: "never",
711
+ summary: ["op"],
712
+ views: ["memory"],
713
+ done: "Joined.",
714
+ // `op` picks joining an open space or asking to join one that is not. Both
715
+ // are "get me into a space", and neither removes anything, so one name.
716
+ input: actionInput({ space: text(128), op: { type: "string", enum: ["join", "request"] }, note: text(300) }, ["space", "op"]),
717
+ output: actionOutput,
718
+ tool: "mem.spaces",
719
+ op: { by: "op", join: "spaceJoin", request: "spaceRequestJoin" },
720
+ store: null,
721
+ },
722
+ // A11: deciding who joins. The person who administers the space approves or
723
+ // declines a waiting request; approving gives the asker read access.
724
+ {
725
+ name: "space.joinRequest.decide",
726
+ label: "decide who joins a space",
727
+ target: "engine",
728
+ class: "chat",
729
+ confirm: "always",
730
+ preview: "space.joinRequest.preview",
731
+ summary: ["decision"],
732
+ views: ["memory"],
733
+ done: "Decided.",
734
+ input: actionInput({ requestId: id, decision: { type: "string", enum: ["approve", "decline"] }, note: text(300) }, ["requestId", "decision"]),
735
+ output: actionOutput,
736
+ tool: "mem.spaces",
737
+ op: "joinRequestDecide",
738
+ previewOp: "joinRequestPreview",
739
+ // A request names a request, not a store: it is spent in the person's own.
740
+ store: null,
741
+ },
742
+ // A11: changing who can find or join a space. `local`: it disposes of other
743
+ // people's access, and the owner's device is the only one that signs it; the
744
+ // control plane answers a bare key `NEEDS_APPROVAL` (G2-P).
745
+ {
746
+ name: "space.visibility",
747
+ needsControlP2: true,
748
+ label: "change who can find or join a space",
749
+ target: "engine",
750
+ class: "local",
751
+ confirm: "always",
752
+ preview: "space.visibility.preview",
753
+ summary: ["visibility"],
754
+ views: ["memory"],
755
+ done: "Changed.",
756
+ input: actionInput({ space: text(128), visibility: { type: "string", enum: ["invite", "open"] } }, ["space", "visibility"]),
757
+ output: actionOutput,
758
+ tool: "mem.spaces",
759
+ op: "spaceVisibility",
760
+ previewOp: "spaceVisibilityPreview",
761
+ },
762
+ // A11's lifecycle, held behind the same P2: renaming, archiving, unarchiving
763
+ // and leaving a space. The preview names the op, because leaving is not the
764
+ // same press as renaming.
765
+ {
766
+ name: "space.manage",
767
+ needsControlP2: true,
768
+ label: "rename, archive, unarchive or leave a space",
769
+ target: "engine",
770
+ // Leaving a space cannot be undone, so the class is an owner device's —
771
+ // and rename, archive and unarchive are safe under the stricter class.
772
+ class: "local",
773
+ confirm: "always",
774
+ preview: "space.manage.preview",
775
+ summary: ["op"],
776
+ views: ["memory"],
777
+ done: "Changed.",
778
+ input: actionInput({ space: text(128), op: { type: "string", enum: ["rename", "archive", "unarchive", "leave"] }, name: text(120), expectedDigest: text(200) }, ["space", "op"]),
779
+ output: actionOutput,
780
+ tool: "mem.spaces",
781
+ op: "spaceManage",
782
+ previewOp: "spaceManagePreview",
783
+ // Archiving or leaving is committed at the state the person was shown
784
+ // (`expectedDigest`), and a host's press never sends it: the preview keeps
785
+ // it (`PREVIEW_SNAPSHOTS`), and the press spends it once.
786
+ stateBound: true,
787
+ },
788
+ ])
789
+
790
+ /**
791
+ * What Jelly is told: each action without the framework's `op`, `previewOp`,
792
+ * `store`, `stateBound` and the P2/room markers. Both switches are on (Jelly
793
+ * 0.4.0-beta.20, protocol major 7), so all 34 are declared.
794
+ */
795
+ export const DECLARED_ACTIONS = Object.freeze(
796
+ ACTIONS.filter((action) => (ACTIONS_NEED_CONTROL_P2 || action.needsControlP2 !== true) && (ACTIONS_NEED_ROOM || action.needsRoom !== true)).map(
797
+ ({ op: _op, previewOp: _previewOp, store: _store, needsControlP2: _p2, needsRoom: _room, stateBound: _bound, ...action }) => action,
798
+ ),
799
+ )
800
+
801
+ /** The action names, in declaration order. */
802
+ export const ACTION_NAMES = Object.freeze(ACTIONS.map((action) => action.name))
803
+
804
+ /** The names as this engine registers them: `act.<name>`. */
805
+ export const ACTION_METHODS = Object.freeze(ACTION_NAMES.map((name) => `act.${name}`))
806
+
807
+ /** The engine methods this module registers, which no `rpc` method may be. */
808
+ const ALLOWED = Object.freeze(
809
+ Object.fromEntries(
810
+ ACTIONS.map((action) => [
811
+ action.name,
812
+ { minClass: action.class, inputKeys: Object.fromEntries(Object.entries(action.input.properties ?? {}).filter(([key]) => key !== SPEAKER).map(([key, schema]) => [key, typeOf(schema)])) },
813
+ ]),
814
+ ),
815
+ )
816
+
817
+ /** The declared JSON type of one input key, in the verifier's words (§4.4 step 10). */
818
+ function typeOf(schema) {
819
+ if (Array.isArray(schema?.enum)) return "string"
820
+ if (schema?.type === "integer" || schema?.type === "number") return "integer"
821
+ if (schema?.type === "boolean") return "boolean"
822
+ if (schema?.type === "array") return "array"
823
+ if (schema?.type === "object") return "object"
824
+ return "string"
825
+ }
826
+
827
+ // ---------------------------------------------------------------------------
828
+ // Refusals: `CODE: what happened. Next step: …`
829
+
830
+ /**
831
+ * The codes the plugin answers with. #58's family (`NOT_FOUND`,
832
+ * `VERSION_CONFLICT`, `SPACE_READ_ONLY`, `NOT_OWNER`, `NEEDS_APPROVAL`,
833
+ * `ALREADY_MEMBER`, `REQUEST_PENDING`, `SCOPE_MISSING`) is what a page shows;
834
+ * the ADR's `grant_*` codes are kept for the door's own refusals, because they
835
+ * say which check refused and nothing about the record.
836
+ */
837
+ const CODES = Object.freeze({
838
+ not_found: "NOT_FOUND",
839
+ version_conflict: "VERSION_CONFLICT",
840
+ revision_conflict: "VERSION_CONFLICT",
841
+ not_pending: "NOT_PENDING",
842
+ needs_approval: "NEEDS_APPROVAL",
843
+ forbidden: "SPACE_READ_ONLY",
844
+ space_read_only: "SPACE_READ_ONLY",
845
+ not_owner: "NOT_OWNER",
846
+ grant_required: "NEEDS_APPROVAL",
847
+ grant_unavailable: "SCOPE_MISSING",
848
+ grant_keys_stale: "SCOPE_MISSING",
849
+ invalid_action: "NOT_PENDING",
850
+ invalid_request: "SCOPE_MISSING",
851
+ invalid_record: "SCOPE_MISSING",
852
+ invalid_id: "NOT_FOUND",
853
+ team_delete_console_only: "NEEDS_APPROVAL",
854
+ page_lines_kept: "NEEDS_APPROVAL",
855
+ })
856
+
857
+ /** What this module refuses in its own words, and the code the page shows. */
858
+ const OWN_REFUSALS = Object.freeze({
859
+ ACTIONS_OFF: ["ACTIONS_OFF", "Actions are off on this Memory engine, so this control changes nothing.", "Ask whoever runs Memory to turn its actions on; until then, make the change in Memory's console or through the agent."],
860
+ NOTHING_DECLARED: ["NOT_FOUND", noControl, "Update Memory, or choose the control its pages draw today."],
861
+ NO_GRANT: ["GRANT_REQUIRED", "This action arrived with no grant from the person's host, so Memory cannot tell that a person chose it.", "Choose it in the person's own page in the host, which draws the confirmation and signs one grant for that click."],
862
+ NO_SPEAKER: ["GRANT_MEMBER", "This action did not name the person it is for.", "Choose it in the person's own page in the host, which fills the speaker."],
863
+ NOT_CONFIGURED: ["GRANT_UNAVAILABLE", "No action key is configured for this engine, so no grant can be verified.", "Ask whoever runs the host to hand Memory its action key, or set actionKeysFile."],
864
+ BAD_GRANT: ["GRANT_INVALID", "The grant is not one this host's key signed for this action and this input.", "Press again in the host. An agent cannot take an action; its tool asks a different door."],
865
+ NO_OPERATION: ["INVALID", "This action's own `op` names no operation Memory runs, so nothing changed and no grant was spent.", "Choose one of the operations the action declares, and press again."],
866
+ P2_UNAVAILABLE: [
867
+ "P2_UNAVAILABLE",
868
+ "This Memory deployment has no P2 reservation key, so a press here cannot reach its control plane.",
869
+ "Set the same P2_RESERVATION_KEY (32 bytes or longer) in records, the gateway and control, then press again; until then, make this change in Memory's console.",
870
+ ],
871
+ })
872
+
873
+ /** One sentence in Memory's family: `CODE: what happened. Next step: …`. */
874
+ export function refusalWords(code, what, next) {
875
+ const sentence = String(what ?? "").trim().replace(/\s+/g, " ").replace(/\.+$/, "")
876
+ return `${code}: ${sentence || "Nothing changed"}. Next step: ${String(next ?? "Nothing was changed.").trim()}`
877
+ }
878
+
879
+ /** `{ok: false, code, message}` for one code, from this module or a records refusal. */
880
+ function refusal(code, what, next) {
881
+ return { ok: false, code, message: refusalWords(code, what, next) }
882
+ }
883
+
884
+ /** A records or transport failure as the action's own answer. */
885
+ function answerFor(error) {
886
+ const code = CODES[error?.code] ?? (String(error?.code ?? "").startsWith("grant_") ? String(error.code).toUpperCase() : "UNAVAILABLE")
887
+ const what = error?.what ?? error?.message ?? "Memory could not apply that"
888
+ const next = error?.next ?? "Try again. If it keeps failing, make the change in Memory's console."
889
+ // Jelly's answer 6: a conflict or a decided item carries its current state, so
890
+ // the host can say "already done" rather than show a failure.
891
+ const named = error?.body?.error ?? {}
892
+ const state = typeof named.state === "string" ? named.state : undefined
893
+ const status = typeof named.status === "string" ? named.status : undefined
894
+ const version = Number.isSafeInteger(named.version) ? named.version : undefined
895
+ const id = typeof named.id === "string" ? named.id : undefined
896
+ return { ...refusal(code, what, next), ...(state ? { state } : {}), ...(status ? { status } : {}), ...(version === undefined ? {} : { version }), ...(id ? { id } : {}) }
897
+ }
898
+
899
+ // ---------------------------------------------------------------------------
900
+ // The verifier: the host's key, as this engine has it
901
+
902
+ /**
903
+ * The host's key as an entry the verifier reads. Jelly hands every engine
904
+ * `{kid, jwk}` and nothing else; the grant's `iss` names the host, and the
905
+ * signature over the payload authenticates it, so the entry takes `iss` from the
906
+ * (not-yet-trusted) payload — a grant whose signature fails is refused before
907
+ * any claim is used. A host that publishes a key file instead gets the file's
908
+ * entries, `iss` and all.
909
+ */
910
+ function publishedKeyEntry(published) {
911
+ if (!published || typeof published !== "object") return null
912
+ const jwk = published.jwk
913
+ if (!jwk || jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string") return null
914
+ let kid
915
+ let key
916
+ try {
917
+ kid = keyThumbprint({ kty: "OKP", crv: "Ed25519", x: jwk.x })
918
+ if (typeof published.kid === "string" && published.kid !== kid) return null
919
+ key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: jwk.x }, format: "jwk" })
920
+ } catch {
921
+ return null
922
+ }
923
+ return { kid, key }
924
+ }
925
+
926
+ /** The `iss` a grant names, read without trusting it (the signature decides). */
927
+ function issuerOf(grant) {
928
+ if (typeof grant !== "string") return null
929
+ const part = grant.split(".")[1]
930
+ if (!part) return null
931
+ try {
932
+ const claims = JSON.parse(Buffer.from(part, "base64url").toString("utf8"))
933
+ return typeof claims?.iss === "string" && claims.iss.length >= 1 && claims.iss.length <= 128 ? claims.iss : null
934
+ } catch {
935
+ return null
936
+ }
937
+ }
938
+
939
+ /**
940
+ * The plugin's verifier: one key (the host's), one `jti` set, and the acts this
941
+ * build declares. A second verifier would not know the first's spent grants, so
942
+ * make one and keep it.
943
+ */
944
+ export function createPluginVerifier({ keyFile = null, maxAgeHours = 24, now = () => Math.floor(Date.now() / 1000), log = () => {} } = {}) {
945
+ // The same age limit records applies: a file an operator writes or a puller
946
+ // stamps must not verify for ever. 0 disables it.
947
+ const hours = Number.isFinite(Number(maxAgeHours)) && Number(maxAgeHours) >= 0 ? Math.min(Math.floor(Number(maxAgeHours)), 8760) : 24
948
+ const file = keyFile ? createActionKeys({ file: keyFile, audience: GRANT_AUDIENCE, maxAgeMs: hours * 3_600_000, now: () => now() * 1000, log }) : null
949
+
950
+ /** The entries a grant may be verified against, now. */
951
+ function entriesFor(grant) {
952
+ if (file) return file.stale() ? [] : file.check().entries
953
+ const published = publishedKeyEntry(globalThis?.[PUBLISHED_ACTION_KEY])
954
+ if (!published) return []
955
+ const iss = issuerOf(grant)
956
+ if (!iss) return []
957
+ return [{ ...published, iss, mbrIss: "", aud: GRANT_AUDIENCE, typ: GRANT_TYP, extraInput: [SPEAKER] }]
958
+ }
959
+
960
+ /** Why no grant can verify at all, or null. */
961
+ function unavailable() {
962
+ if (file) {
963
+ if (file.stale()) return "the action key file is older than the allowed age"
964
+ return file.available() ? null : file.problem?.() ?? "the action key file is missing"
965
+ }
966
+ return publishedKeyEntry(globalThis?.[PUBLISHED_ACTION_KEY]) ? null : "this engine was handed no action key"
967
+ }
968
+
969
+ /**
970
+ * Verify one grant for one act and one input.
971
+ *
972
+ * @returns {{ ok: true, claims: object } | { ok: false, code: string, what: string, next: string }}
973
+ */
974
+ function verify(act, { input, grant } = {}) {
975
+ if (typeof grant !== "string" || !grant) return { ok: false, ...own("NO_GRANT") }
976
+ const reason = unavailable()
977
+ if (reason) return { ok: false, ...own("NOT_CONFIGURED"), what: `No action key is configured for this engine: ${reason}` }
978
+ const entries = entriesFor(grant)
979
+ if (entries.length === 0) return { ok: false, ...own("NOT_CONFIGURED") }
980
+ const verdict = verifyActionGrant({ grant, input, act, allowed: ALLOWED, keys: { entries }, audience: GRANT_AUDIENCE, now: now() })
981
+ if (!verdict.ok) {
982
+ // The verifier's `detail` is not sent: it would say which byte to change.
983
+ // Its code is the ADR's (§4.9), uppercased into Memory's code family.
984
+ const named = own(verdict.code === "grant_unavailable" ? "NOT_CONFIGURED" : "BAD_GRANT")
985
+ return { ok: false, code: verdict.code === "grant_unavailable" || verdict.code === "grant_replayed" ? named.code : verdict.code.toUpperCase(), what: named.what, next: named.next }
986
+ }
987
+ // The plugin does not spend the grant. Only records' ledger is the
988
+ // authority: a plugin's own set is cold after a restart, and answering a
989
+ // replay from it would hide the first use's receipt (ADR §4.8). The plugin
990
+ // verifies, records rules.
991
+ return { ok: true, claims: verdict.claims }
992
+ }
993
+
994
+ return { verify, unavailable, entriesFor }
995
+ }
996
+
997
+ /** A refusal this module owns, as `{code, what, next}`. */
998
+ function own(name) {
999
+ const [code, what, next] = OWN_REFUSALS[name] ?? ["SCOPE_MISSING", noControl, "Report it to Memory's maintainer."]
1000
+ return { code, what, next }
1001
+ }
1002
+
1003
+ /**
1004
+ * The `act.<name>` methods and handlers, as `ctx.rpc.register` takes them.
1005
+ *
1006
+ * Every handler: the flag, the grant, then the person's own credential, then
1007
+ * records. Nothing is written before all four hold, and a failure answers one
1008
+ * sentence a page can show.
1009
+ *
1010
+ * An action with an `op` is a **space or sharing act** (A2–A9, A11): records
1011
+ * reserves its grant (verifies it, binds it, spends it once, audits it), the
1012
+ * `src/ops` function runs it as the person, and `acts.settle` makes the receipt
1013
+ * terminal. The operations enforce their own rules — ownership, a team page's
1014
+ * protections, G2-P on a transfer — so this layer neither repeats nor skips one.
1015
+ *
1016
+ * @param {{ config: any, runtime: any, verifier: any, personalScopes?: () => Promise<Array<{ context: any, scope: any }>>, operations?: Record<string, Function> | null, log?: any }} input
1017
+ */
1018
+ export function createActionHandlers({ config, runtime, verifier, personalScopes = async () => [], operations = null, log = () => {} }) {
1019
+ const methods = {}
1020
+ const handlers = {}
1021
+ for (const action of ACTIONS) {
1022
+ const method = `act.${action.name}`
1023
+ methods[method] = { input: { type: "object", required: ["grant"], additionalProperties: true, properties: { input: { type: "object" }, grant: { type: "string" } } }, output: actionOutput }
1024
+ handlers[method] = async (call = {}) => {
1025
+ if (!config.actions) return refusal(own("ACTIONS_OFF").code, own("ACTIONS_OFF").what, own("ACTIONS_OFF").next)
1026
+ const input = call?.input ?? null
1027
+ if (input !== null && (typeof input !== "object" || Array.isArray(input))) {
1028
+ const named = own("BAD_GRANT")
1029
+ return refusal(named.code, named.what, named.next)
1030
+ }
1031
+ if (!Object.hasOwn(ALLOWED, action.name)) {
1032
+ const named = own("NOTHING_DECLARED")
1033
+ return refusal(named.code, named.what, named.next)
1034
+ }
1035
+ const checked = verifier.verify(action.name, { input, grant: call?.grant })
1036
+ if (!checked.ok) return refusal(checked.code, checked.what, checked.next)
1037
+ const speaker = input?.[SPEAKER]
1038
+ if (typeof speaker !== "string" || !speaker.startsWith("view_")) {
1039
+ const named = own("NO_SPEAKER")
1040
+ return refusal(named.code, named.what, named.next)
1041
+ }
1042
+ try {
1043
+ // Every step of an act runs as the person who pressed: records' call,
1044
+ // and, for A12, the profile the plugin reads and writes. The engine
1045
+ // owner's credential is never used for any of it.
1046
+ return await asVerifiedView(speaker, async () => {
1047
+ // A12 changes something the memory core holds, which records cannot
1048
+ // reach, so the change is settled across two calls. Records reserves
1049
+ // the grant first — verified, bound to the person, spent once, with
1050
+ // its audit row — and a refused grant reaches no erase at all. Then
1051
+ // the erase, then the settle that makes the receipt terminal
1052
+ // (`erased`, or `refused` when the core fails). Only a settle that
1053
+ // cannot be delivered leaves the receipt `pending`, and the answer
1054
+ // says so rather than claim an outcome it has not recorded.
1055
+ if (action.name === "profile.erase") {
1056
+ const reserved = await runtime.recordsClient.call("acts.apply", { act: action.name, input, grant: call.grant }, { space: undefined })
1057
+ const spent = reserved?.spent ?? {}
1058
+ const hits = await erasePlan({ backend: runtime.backend, personalScopes, phrase: input.phrase })
1059
+ if (input.snapshot !== snapshotOf(hits)) {
1060
+ await settle({ act: action.name, spent, state: "refused", erased: 0 }, runtime, log)
1061
+ return refusal("VERSION_CONFLICT", "What Memory holds about you changed since that preview, so this erase is for words that are no longer there", "Read the preview again, then press again")
1062
+ }
1063
+ let erased
1064
+ try {
1065
+ erased = await eraseProfile({ backend: runtime.backend, personalScopes, phrase: input.phrase })
1066
+ } catch (error) {
1067
+ await settle({ act: action.name, spent, state: "refused", erased: 0 }, runtime, log)
1068
+ throw error
1069
+ }
1070
+ const settled = await settle({ act: action.name, spent, state: "erased", erased }, runtime, log)
1071
+ if (!settled) {
1072
+ // The erase ran; its receipt is still `pending` on the server,
1073
+ // and the next sweep marks it `unrecorded` (§4.7). Say that,
1074
+ // never claim a receipt the server has not got.
1075
+ return { ok: true, state: "unrecorded", erased, count: erased, note: ERASE_NOTE, message: UNRECORDED }
1076
+ }
1077
+ return { ok: true, ...(settled?.receipt ?? {}), erased, count: erased, note: ERASE_NOTE }
1078
+ }
1079
+ // #78: the press refuses the same words the preview cannot show whole,
1080
+ // by the same limit records enforces again, so the two cannot disagree.
1081
+ if (action.name === "held.decide") {
1082
+ const problem = heldEditsProblem(input?.edits)
1083
+ if (problem) {
1084
+ return refusal("INVALID", heldEditsRefusal(problem), `Shorten the words to ${HELD_EDITS_MAX} characters or fewer, then press again`)
1085
+ }
1086
+ }
1087
+ // A2–A9 and A11: reserve, run the operation as the person, settle.
1088
+ if (action.op !== undefined) {
1089
+ return await runSpaceAct({ action, input, grant: call.grant, runtime, operations, personalScopes, log })
1090
+ }
1091
+ const answer = await runtime.recordsClient.call("acts.apply", { act: action.name, input, grant: call.grant }, { space: typeof input.space === "string" ? input.space : undefined })
1092
+ const receipt = answer?.receipt ?? {}
1093
+ if (receipt.state !== "accepting" || !["review.decide", "inbox.decide", "held.decide"].includes(action.name)) return { ok: true, ...receipt }
1094
+ // A held team write's accept is two steps: records answers `accepting`,
1095
+ // and the shared write is made and completed the one way it is
1096
+ // (tools/held-write.js), with the author's editor right re-checked.
1097
+ return await finishHeldWrite({ runtime, receipt, input, speaker, personalScopes, log })
1098
+ })
1099
+ } catch (error) {
1100
+ log?.warn?.("action failed", { act: action.name, code: error?.code })
1101
+ return answerFor(error)
1102
+ }
1103
+ }
1104
+ }
1105
+ return { methods, handlers }
1106
+ }
1107
+
1108
+ /**
1109
+ * The `src/ops` function an action's input names: its own `op`, or the one a
1110
+ * map picks by the input's discriminator (`proposal.decide`).
1111
+ *
1112
+ * @param {{ op?: string | Record<string, string> }} action
1113
+ * @param {any} input
1114
+ * @returns {string | null}
1115
+ */
1116
+ function operationName(action, input) {
1117
+ if (typeof action.op === "string") return action.op
1118
+ if (!action.op || typeof action.op !== "object") return null
1119
+ const key = input?.[action.op.by]
1120
+ if (typeof key !== "string" || !Object.hasOwn(action.op, key) || key === "by") return null
1121
+ return typeof action.op[key] === "string" ? action.op[key] : null
1122
+ }
1123
+
1124
+ /**
1125
+ * The store a space act's grant is spent in, as `acts.apply` takes it: the
1126
+ * space the action's `store` path names (its own `space` when the path names
1127
+ * nothing), or `undefined` for an act that names none — a new space, a
1128
+ * handover's answer, a join — which is spent in the person's own store.
1129
+ *
1130
+ * @param {{ store?: string | null }} action
1131
+ * @param {any} input
1132
+ * @returns {string | undefined}
1133
+ */
1134
+ function actStore(action, input) {
1135
+ const body = input && typeof input === "object" && !Array.isArray(input) ? input : {}
1136
+ const own = typeof body.space === "string" && body.space ? body.space : undefined
1137
+ if (action.store === null) return undefined
1138
+ const path = action.store ?? "space"
1139
+ if (path === "space") return own
1140
+ let value = body
1141
+ for (const key of path.split(".")) {
1142
+ value = value && typeof value === "object" ? value[key] : undefined
1143
+ if (value === undefined) break
1144
+ }
1145
+ return typeof value === "string" && value ? value : own
1146
+ }
1147
+
1148
+ /**
1149
+ * The store a space act's grant is spent in, resolved: the one the action's
1150
+ * `store` path names, else the person's own. A preview's snapshot is kept in
1151
+ * this same store (0.11), so a preview and the press that follows always meet
1152
+ * in one.
1153
+ *
1154
+ * @param {{ store?: string | null }} action
1155
+ * @param {any} input
1156
+ * @param {() => Promise<Array<{ context: any }>>} personalScopes
1157
+ * @returns {Promise<string | undefined>}
1158
+ */
1159
+ async function pressStore(action, input, personalScopes) {
1160
+ const space = actStore(action, input)
1161
+ if (space !== undefined) return space
1162
+ const [first] = await personalScopes()
1163
+ return typeof first?.context?.space_id === "string" ? first.context.space_id : undefined
1164
+ }
1165
+
1166
+ /**
1167
+ * One space or sharing act: the reservation, the operation as the person, and
1168
+ * the settle that makes the receipt terminal (§4.7, the `profile.erase`
1169
+ * pattern). A refused operation settles `refused`; one whose settle cannot be
1170
+ * delivered answers `unrecorded` rather than claim a receipt the server has not
1171
+ * got. An operation's own refusal is answered in its own words: `src/ops`
1172
+ * already says `CODE: what happened. Next step: …`.
1173
+ */
1174
+ async function runSpaceAct({ action, input, grant, runtime, operations, personalScopes, log }) {
1175
+ const name = operationName(action, input)
1176
+ const operation = name ? operations?.[name] : null
1177
+ if (typeof operation !== "function") {
1178
+ const named = own("NO_OPERATION")
1179
+ return refusal(named.code, named.what, named.next)
1180
+ }
1181
+ // The store the grant is spent in: the one the act names, else the person's
1182
+ // own (asked for only when it is needed).
1183
+ const space = await pressStore(action, input, personalScopes)
1184
+ // Records gates the act: a grant it refuses reaches no operation at all.
1185
+ const reserved = await runtime.recordsClient.call("acts.apply", { act: action.name, input, grant }, { space })
1186
+ const spent = reserved?.spent ?? {}
1187
+ // What the person was shown, as records kept it from the preview (0.11). A
1188
+ // host's press carries the page's own input and never the preview's answer,
1189
+ // so the fields a press cannot name are put back here, exactly as if the page
1190
+ // had sent them back; the operation then holds them to the state now, as it
1191
+ // always has. A caller that named them itself keeps its own, checked.
1192
+ const bound = action.stateBound === true && reserved?.preview ? applyPreview(action.name, input, reserved.preview) : input
1193
+ // A G2-P act's change lands at the control plane, which does not hold the
1194
+ // host's grant: records answers a reservation naming the act, the input it
1195
+ // signed and this person, and the operation carries it to control, which
1196
+ // verifies and spends it once (docs/design/p2-control.md §2). Without one the
1197
+ // act still runs, and the control plane refuses it: nothing is ever sent in
1198
+ // the hope that a bare key will do.
1199
+ const p2 = typeof reserved?.reservation === "string" ? reservationFor(action.name, input, reserved.reservation) : null
1200
+ // A control-plane act cannot land without its reservation: records issued
1201
+ // none because its key is unset, or the gateway/control hold a different one
1202
+ // and will refuse it. Say what is missing here, once, instead of letting the
1203
+ // control plane answer a bare key `NEEDS_APPROVAL` about the person.
1204
+ if (action.needsControlP2 === true && !p2) {
1205
+ await settle({ act: action.name, spent, state: "refused", space }, runtime, log)
1206
+ const unavailable = own("P2_UNAVAILABLE")
1207
+ return refusal(unavailable.code, unavailable.what, unavailable.next)
1208
+ }
1209
+ let result
1210
+ try {
1211
+ // As the verified person, in the store the operation resolves for itself.
1212
+ result = await operation({ sessionID: undefined, p2 }, bound)
1213
+ } catch (error) {
1214
+ // An operation that half happened says so: a move that copied the page and
1215
+ // could not remove the original settles `partial` with the copy's id, so
1216
+ // the receipt never says `refused` about a change that is there.
1217
+ const partial = typeof error?.partial?.id === "string" && error.partial.id ? error.partial : null
1218
+ const settled = await settle({ act: action.name, spent, state: partial ? "partial" : "refused", ...(partial ? { id: partial.id } : {}), space }, runtime, log)
1219
+ if (error?.name === "OperationError" && typeof error.code === "string") {
1220
+ // The operation's refusal is already `CODE: what. Next step: …`.
1221
+ return { ok: false, code: error.code, message: error.message, ...(partial ? { state: "partial", id: partial.id, ...(settled ? {} : { receipt: "unrecorded" }) } : {}) }
1222
+ }
1223
+ throw error
1224
+ }
1225
+ const settled = await settle({ act: action.name, spent, state: "applied", space }, runtime, log)
1226
+ if (!settled) return { ok: true, ...result, receipt: "unrecorded", message: UNRECORDED_ACT }
1227
+ return { ok: true, ...result }
1228
+ }
1229
+
1230
+ /**
1231
+ * The reservation a G2-P act carries to the control plane: the proof records
1232
+ * answered, the act, and the act's canonical input as the host signed it (the
1233
+ * gateway and control hash those bytes and compare them with the proof).
1234
+ *
1235
+ * @param {string} act
1236
+ * @param {unknown} input
1237
+ * @param {string} token
1238
+ */
1239
+ function reservationFor(act, input, token) {
1240
+ return { token, act, input: Buffer.from(canonicalJson(input), "utf8").toString("base64url") }
1241
+ }
1242
+
1243
+ /**
1244
+ * The one call that makes a reservation terminal (§4.7, `acts.settle`). A
1245
+ * failure is logged and the answer says the outcome is unrecorded, rather than
1246
+ * claiming one the server has not got.
1247
+ */
1248
+ async function settle({ act, spent, state, erased, id, space = undefined }, runtime, log) {
1249
+ try {
1250
+ return await runtime.recordsClient.call("acts.settle", { act, host: spent.host, jti: spent.jti, state, ...(erased === undefined ? {} : { erased }), ...(id === undefined ? {} : { id }) }, { space })
1251
+ } catch (error) {
1252
+ log?.warn?.("the action's receipt could not be settled", { act, code: error?.code ?? null, state })
1253
+ return null
1254
+ }
1255
+ }
1256
+
1257
+ /** The proposal's store, read back, and the shared space the author may still write. */
1258
+ async function finishHeldWrite({ runtime, receipt, input, speaker, personalScopes, log }) {
1259
+ try {
1260
+ const record = await readProposal(runtime, receipt.id)
1261
+ if (!record) return refusal("NOT_FOUND", "The held write could not be read back after it was accepted", "Open it in Memory's console, or press again")
1262
+ const personal = await runtime.resolveContext({ space: input.space ?? undefined })
1263
+ const shared = await runtime.resolveContext({ space: record.fields?.space_id })
1264
+ // A second guard, before records sees it: the author must still write the
1265
+ // shared space. Records' held batch checks it again; this one says so in
1266
+ // the person's words, and never spends the send on a viewer.
1267
+ const writes = ["editor", "admin", "owner"].includes(String(shared?.role ?? "").toLowerCase())
1268
+ if (shared?.space_id !== record.fields?.space_id || shared?.space_kind !== "shared" || shared?.user_id !== personal?.user_id || !writes) {
1269
+ return refusal("NOT_OWNER", "You no longer have write access to the shared space this write was meant for", "Ask an admin of that space for the editor role, or keep the write in your own space instead")
1270
+ }
1271
+ const done = await asVerifiedView(speaker, () => completeHeldWrite({ runtime, space: input.space ?? personal?.space_id, id: receipt.id, held: record, shared }))
1272
+ const proposal = done?.proposal ?? {}
1273
+ return { ok: true, id: proposal.id ?? receipt.id, state: proposal.status ?? "applied", version: proposal.version ?? receipt.version }
1274
+ } catch (error) {
1275
+ if (error?.name === "OperationError" && typeof error.code === "string") return { ok: false, code: error.code, message: error.message }
1276
+ log?.warn?.("the held write was accepted but not completed", { code: error?.code ?? null })
1277
+ return refusal("NEEDS_APPROVAL", "The write was accepted but the shared space did not confirm it", "Press again: the proposal is `accepting`, and a second press completes it")
1278
+ }
1279
+ }
1280
+
1281
+ /** One proposal as records has it, for the completion. */
1282
+ async function readProposal(runtime, id) {
1283
+ const { records } = await runtime.recordsClient.call("records.get", { ids: [id] })
1284
+ return records?.[0] ?? null
1285
+ }
1286
+
1287
+ // ---------------------------------------------------------------------------
1288
+ // The previews: what an `always` confirmation shows, and A12's About-you flow
1289
+
1290
+ /** The most lines one erase preview shows; the rest are counted. */
1291
+ const ERASE_LINES_MAX = 20
1292
+ /** What the person is told when an erase ran but its receipt could not be recorded. */
1293
+ export const UNRECORDED =
1294
+ "UNRECORDED: the erase ran, but Memory could not record its receipt, so whether it happened is unrecorded until Memory's next pass marks it so. Next step: read About you again; the lines are gone if they are gone, and a new press erases nothing more."
1295
+
1296
+ /** What the person is told when a space act ran but its receipt could not be recorded. */
1297
+ export const UNRECORDED_ACT =
1298
+ "UNRECORDED: the change ran, but Memory could not record its receipt, so whether it happened is unrecorded until Memory's next pass marks it so. Next step: read it again in Memory; the change is there if it is there, and a second press signs a new grant."
1299
+
1300
+ /** The longest note a preview carries: one sentence, in Memory's words. */
1301
+ const ERASE_NOTE_CHARS = 300
1302
+ /** What an erase does not do, said in the preview and in its result. */
1303
+ export const ERASE_NOTE =
1304
+ "The turns and notes this was written from are not erased, so the phrase can come back the next time Memory consolidates them."
1305
+
1306
+ /** The digest a person's erase is signed for: the matched lines as the preview showed them. */
1307
+ function snapshotOf(lines) {
1308
+ return createHash("sha256").update(JSON.stringify(lines.map((line) => [line.id, line.text]))).digest("base64url")
1309
+ }
1310
+
1311
+ /**
1312
+ * The lines of the profile that hold the phrase, read afresh, with the digest the
1313
+ * erase action carries. A text operation, not a model call: the same lines the
1314
+ * write removes.
1315
+ */
1316
+ export async function erasePlan({ backend, personalScopes, phrase }) {
1317
+ const hits = []
1318
+ const scopes = await personalScopes()
1319
+ for (const { scope } of scopes) {
1320
+ const agent = String(scope?.agent_id ?? "")
1321
+ const core = await backend.readCore({ scope }).catch(() => null)
1322
+ const persona = String(core?.content ?? "")
1323
+ for (const line of matchingLines(persona, phrase)) {
1324
+ hits.push({ id: `persona:${agent}`, layer: "persona", agent, path: "persona", scope, text: line })
1325
+ }
1326
+ const list = await backend.listScenarios({ scope }).catch(() => null)
1327
+ for (const entry of list?.entries ?? []) {
1328
+ const path = String(entry?.path ?? "")
1329
+ if (!path || path.endsWith("/")) continue
1330
+ const data = await backend.readScenario({ path, scope }).catch(() => null)
1331
+ for (const line of matchingLines(String(data?.content ?? ""), phrase)) {
1332
+ hits.push({ id: `scenario:${agent}:${path}`, layer: "scenario", agent, path, scope, text: line })
1333
+ }
1334
+ }
1335
+ }
1336
+ return hits
1337
+ }
1338
+
1339
+ /** One commitment as the person sees it: its words, state and version. */
1340
+ async function commitmentPreview({ runtime, input = {} }) {
1341
+ const space = typeof input.space === "string" && input.space ? input.space : undefined
1342
+ const id = String(input.id ?? "")
1343
+ const answer = await runtime.recordsClient.call("records.get", { ids: [id] }, { space })
1344
+ const record = (Array.isArray(answer?.records) ? answer.records : []).find((entry) => entry?.kind === "commitment")
1345
+ if (!record) return { found: false, id, what: "", state: "", version: 0 }
1346
+ // The words the person is about to delete or move, read from the record,
1347
+ // never only its id — and the words the page showed must be these. A page
1348
+ // that names different words is showing something the record no longer says,
1349
+ // so the confirmation is refused rather than drawn for the wrong words.
1350
+ const what = String(record.fields?.what ?? record.title ?? "").slice(0, 300)
1351
+ const claimed = typeof input.what === "string" ? input.what.trim() : ""
1352
+ if (claimed && claimed !== what) {
1353
+ throw Object.assign(new Error("VERSION_CONFLICT: the commitment's words changed since they were shown, so this press is for words that are no longer there. Next step: read the commitment again, then choose it."), { code: "VERSION_CONFLICT" })
1354
+ }
1355
+ return {
1356
+ found: true,
1357
+ id: String(record.id),
1358
+ what,
1359
+ state: String(record.fields?.state ?? "open"),
1360
+ version: Number(record.version) || 0,
1361
+ ...(typeof input.to?.space === "string" ? { to: input.to.space } : {}),
1362
+ }
1363
+ }
1364
+
1365
+ /**
1366
+ * What a preview showed, for the press that cannot be told it (0.11).
1367
+ *
1368
+ * Jelly draws an `always` confirmation from the action's preview and then
1369
+ * presses with **the same value it previewed**: it never merges the preview's
1370
+ * answer into the press (`frontend/core/src/plugins/view-source.ts` `take`).
1371
+ * So a page never sends the page version a copy is signed for, the wiki file
1372
+ * the preview computed, or the digest a space change commits at. Each of those
1373
+ * is a fact about state the person saw, so the preview keeps it (records'
1374
+ * `acts.preview`, keyed by the act, the input's digest and the person, for a
1375
+ * few minutes), and the press that finds it spends it once, in the grant's own
1376
+ * transaction. The plugin then puts the fields back on the input, exactly as if
1377
+ * the page had sent them back.
1378
+ *
1379
+ * This map is what a preview keeps, per act; `applyPreview` puts it back on the
1380
+ * press's input. Both are the act's own, so a new state-bound act adds one
1381
+ * entry to each and nothing else learns it.
1382
+ */
1383
+ const PREVIEW_SNAPSHOTS = Object.freeze({
1384
+ /** A8: the page's version, and the path (or wiki file) the copy lands at. */
1385
+ "share.copy": (answer, input) => {
1386
+ if (String(answer?.op ?? input?.op ?? "") !== "page") return null
1387
+ const version = Number(answer?.from?.version)
1388
+ const toPath = typeof answer?.to?.path === "string" ? answer.to.path : ""
1389
+ if (!Number.isInteger(version) || version < 1 || !toPath) return null
1390
+ return { version, toPath }
1391
+ },
1392
+ /** A11: the state digest an archive or a leave commits at. */
1393
+ "space.manage": (answer) => {
1394
+ const expectedDigest = typeof answer?.expectedDigest === "string" ? answer.expectedDigest.trim() : ""
1395
+ return expectedDigest ? { expectedDigest } : null
1396
+ },
1397
+ /** #78: the version of the held write the person was shown. */
1398
+ "held.decide": (answer) => (answer?.found === true && Number.isInteger(answer.version) ? { revision: answer.version } : null),
1399
+ /** #77: the version of the suggestion the person was shown. */
1400
+ "suggestion.dismiss": (answer) => (answer?.found === true && Number.isInteger(answer.version) ? { revision: answer.version } : null),
1401
+ })
1402
+
1403
+ /**
1404
+ * The input a press runs on, with the fields its preview kept for it. A field
1405
+ * the caller named itself is kept, and checked by the operation as before: the
1406
+ * snapshot only fills what the press cannot know.
1407
+ */
1408
+ function applyPreview(act, input, preview) {
1409
+ const body = input && typeof input === "object" && !Array.isArray(input) ? input : {}
1410
+ if (act === "share.copy") {
1411
+ const toPath = typeof preview?.toPath === "string" ? preview.toPath : ""
1412
+ return {
1413
+ ...body,
1414
+ ...(body.version === undefined || body.version === null ? (Number.isInteger(preview?.version) ? { version: preview.version } : {}) : {}),
1415
+ ...(toPath && !String(body.to?.path ?? "").trim() ? { to: { ...(body.to ?? {}), path: toPath } } : {}),
1416
+ }
1417
+ }
1418
+ if (act === "space.manage") {
1419
+ const expectedDigest = typeof preview?.expectedDigest === "string" ? preview.expectedDigest.trim() : ""
1420
+ return String(body.expectedDigest ?? "").trim() || !expectedDigest ? body : { ...body, expectedDigest }
1421
+ }
1422
+ return body
1423
+ }
1424
+
1425
+ /**
1426
+ * Keep what one preview showed, in the store the act is spent in — the same
1427
+ * store `runSpaceAct` spends the press's grant in, so the press finds it — so
1428
+ * the press that follows finds it. A preview changes nothing the person owns:
1429
+ * this writes one expiring row that only their own press of this exact input
1430
+ * can spend.
1431
+ *
1432
+ * A snapshot that cannot be recorded does not fail the preview: a preview shows
1433
+ * what a press would do and must answer, and the press then asks for a fresh
1434
+ * preview rather than run on facts nobody kept.
1435
+ */
1436
+ async function notePreview({ action, input, answer }, runtime, space) {
1437
+ const binding = PREVIEW_SNAPSHOTS[action.name]?.(answer, input)
1438
+ if (!binding) return
1439
+ try {
1440
+ await runtime.recordsClient.call("acts.preview", { act: action.name, input, binding }, { space })
1441
+ } catch (error) {
1442
+ runtime.log?.warn?.("a preview's snapshot was not recorded", { act: action.name, code: error?.code ?? null })
1443
+ }
1444
+ }
1445
+
1446
+ /**
1447
+ * The read-only methods a Jelly confirmation shows first
1448
+ * (`action.preview`), plus A12's own preview read. Each is called with the
1449
+ * action's own input, as the person whose device asked, and none of them
1450
+ * changes anything the person owns. A state-bound act's preview also keeps what
1451
+ * it showed, so the press Jelly makes next can be exactly that press (0.11).
1452
+ *
1453
+ * An action whose preview reads the space and sharing services (`previewOp`)
1454
+ * answers through its `src/ops` function, with the action's own input
1455
+ * unchanged: the read and the action see exactly the same facts.
1456
+ *
1457
+ * @param {{ runtime: any, personalScopes: () => Promise<Array<{ context: any, scope: any }>>, operations?: Record<string, Function> | null }} input
1458
+ */
1459
+ export function createActionReads({ runtime, personalScopes, operations = null }) {
1460
+ const { backend } = runtime
1461
+
1462
+ /**
1463
+ * A record's title, as a person reads it: the title it carries, else the first
1464
+ * line of its words, on one line and within 120 characters. A confirm panel
1465
+ * says `Keep "<title>"?`, never a record id (jelly #75).
1466
+ */
1467
+ function titleOf(record, words) {
1468
+ const stored = record?.fields?.title ?? record?.title ?? ""
1469
+ const first = String(stored).trim() || String(words ?? "").split("\n").map((line) => line.trim()).find(Boolean) || ""
1470
+ return oneLine(first.replace(/^#+\s*/, ""), 120)
1471
+ }
1472
+
1473
+ /** One proposal as the person sees it: what it would save, and its version. */
1474
+ async function proposalPreview({ id: proposalId }) {
1475
+ const { records, missing } = await runtime.recordsClient.call("records.get", { ids: [proposalId] })
1476
+ const record = records?.[0]
1477
+ if (!record || missing?.length) {
1478
+ return { found: false, id: proposalId, version: 0, state: "", kind: "", space: "", title: "", text: "" }
1479
+ }
1480
+ let held = ""
1481
+ /** A held team write's own title, if the write carried one (jelly #75, S4). */
1482
+ let heldTitle = ""
1483
+ if (record.type === "team_write") {
1484
+ try {
1485
+ const first = JSON.parse(record.body)?.records?.[0]
1486
+ held = String(first?.body ?? "")
1487
+ heldTitle = String(first?.title ?? "")
1488
+ } catch {
1489
+ held = ""
1490
+ heldTitle = ""
1491
+ }
1492
+ }
1493
+ const words = held || String(record.fields?.payload?.body ?? record.body ?? "")
1494
+ return {
1495
+ found: true,
1496
+ id: record.id,
1497
+ version: record.version,
1498
+ state: String(record.status ?? ""),
1499
+ kind: String(record.type ?? ""),
1500
+ space: String(record.fields?.space_name ?? ""),
1501
+ // A held write is stored with a title of its own ("Team write awaiting
1502
+ // approval"), which is not what the person would keep: its body's first
1503
+ // line is. So for a held write the words win over the wrapper's title.
1504
+ // The store's wrapper is exactly this string; a write that carried its own
1505
+ // title keeps it, even one that happens to read "… awaiting approval".
1506
+ title: record.type === "team_write" ? titleOf({}, heldTitle && heldTitle !== HELD_WRITE_TITLE ? heldTitle : words) : titleOf(record, words),
1507
+ text: words,
1508
+ }
1509
+ }
1510
+
1511
+ /**
1512
+ * #78: the held write a press would accept, edit or drop — and, for an edit or
1513
+ * an accept with edits, the words that will land. The page supplies `edits`
1514
+ * with the press it previews, so the confirmation is drawn from the same
1515
+ * value, and the snapshot it keeps is keyed by that value's digest: another
1516
+ * edit can never land under this preview.
1517
+ */
1518
+ const heldDecidePreview = async (input = {}) => {
1519
+ const answer = await proposalPreview(input)
1520
+ if (!answer.found) return answer
1521
+ const edits = typeof input?.edits === "string" ? input.edits : ""
1522
+ const edit = edits.trim() && (input?.op === "edit" || input?.op === "accept")
1523
+ const lands = edit ? edits : answer.text
1524
+ // Nothing unseen lands: the preview refuses words it cannot show whole, and
1525
+ // the press is refused again by the same limit (records enforces it too).
1526
+ const problem = edit ? heldEditsProblem(edits) : null
1527
+ if (problem) throw Object.assign(new Error(`INVALID: ${heldEditsRefusal(problem)}. Next step: Shorten the words to ${HELD_EDITS_MAX} characters or fewer, then read the preview again.`), { code: "INVALID" })
1528
+ const shown = { ...answer, text: lands }
1529
+ if (edit && !shownWhole(shown)) throw Object.assign(new Error(`INVALID: ${heldEditsRefusal({ length: (JSON.stringify(shown, null, 2) ?? "").length, limit: JELLY_PREVIEW_MAX_CHARS })}. Next step: Shorten the words, then read the preview again.`), { code: "INVALID" })
1530
+ await notePreview({ action: { name: "held.decide" }, input, answer: shown }, runtime, await pressStore({}, input, personalScopes))
1531
+ return shown
1532
+ }
1533
+
1534
+ /**
1535
+ * A preview that also keeps the version it showed, for the two acts a press
1536
+ * may take only from a live preview (`held.decide`, `suggestion.dismiss`):
1537
+ * records refuses the press with no snapshot, so the read leaves one in the
1538
+ * store the press's grant is spent in.
1539
+ */
1540
+ const pressPreview = (name) => async (input = {}) => {
1541
+ const answer = await proposalPreview(input)
1542
+ if (answer.found) await notePreview({ action: { name }, input, answer }, runtime, await pressStore({}, input, personalScopes))
1543
+ return answer
1544
+ }
1545
+
1546
+ /**
1547
+ * The previews the space and sharing services answer (`previewOp`): each runs
1548
+ * its operation's own read, with the action's input, and never its write.
1549
+ */
1550
+ const spaceReads = {}
1551
+ for (const action of ACTIONS) {
1552
+ if (!action.preview || !action.previewOp) continue
1553
+ spaceReads[action.preview] = async (input = {}) => {
1554
+ const read = operations?.[action.previewOp]
1555
+ if (typeof read !== "function") {
1556
+ const named = own("NO_OPERATION")
1557
+ throw Object.assign(new Error(named.what), { code: named.code })
1558
+ }
1559
+ const answer = await read({ sessionID: undefined }, input)
1560
+ // What this showed, for the press Jelly makes next: the same input, and
1561
+ // the fields a press cannot name (0.11). Kept in the store `runSpaceAct`
1562
+ // will spend the press's grant in, so the press finds it.
1563
+ if (action.stateBound === true) await notePreview({ action, input, answer }, runtime, await pressStore(action, input, personalScopes))
1564
+ return answer
1565
+ }
1566
+ }
1567
+
1568
+ return {
1569
+ ...spaceReads,
1570
+ /** A1: the page at the version the person saw, and whether this space needs approval. */
1571
+ "page.write.preview": async ({ space, path: pagePath, body, expectVersion } = {}) => {
1572
+ const { records } = await runtime.recordsClient.call("records.get", { paths: [pagePath] }, { space })
1573
+ const current = records?.[0] ?? null
1574
+ let kind = "personal"
1575
+ try {
1576
+ kind = String((await runtime.resolveContext({ space }))?.space_kind ?? "personal")
1577
+ } catch {
1578
+ // An unknown space is not a personal one: say so rather than guess.
1579
+ kind = "unknown"
1580
+ }
1581
+ const before = String(current?.body ?? "").split("\n").filter(Boolean)
1582
+ const after = String(body ?? "").split("\n").filter(Boolean)
1583
+ const kept = new Set(after)
1584
+ const was = new Set(before)
1585
+ return {
1586
+ space: String(space ?? ""),
1587
+ path: String(pagePath ?? ""),
1588
+ exists: Boolean(current),
1589
+ version: Number(current?.version ?? 0),
1590
+ expectVersion: Number.isSafeInteger(expectVersion) ? expectVersion : null,
1591
+ approvalRequired: kind !== "personal",
1592
+ added: after.filter((line) => !was.has(line)).length,
1593
+ removed: before.filter((line) => !kept.has(line)).length,
1594
+ }
1595
+ },
1596
+ /** A10: the record a keep, edit or forget would save. */
1597
+ "review.decide.preview": proposalPreview,
1598
+ /** A15: the held write an edit or a private keep acts on. */
1599
+ "write.decide.preview": proposalPreview,
1600
+ /**
1601
+ * #78: the held write the press accepts, edits or drops, and the version it
1602
+ * is bound to. For an `edit`, or an `accept` carrying edits, the answer's
1603
+ * `text` is the **final** text that will land, so the confirmation shows
1604
+ * the words the person is approving, never the words now. The preview keeps
1605
+ * the version: a press sends only the page's own input, and records refuses
1606
+ * one with no live preview.
1607
+ */
1608
+ "held.decide.preview": heldDecidePreview,
1609
+ /** #77: the suggestion a press hides, and the version it is bound to. */
1610
+ "suggestion.dismiss.preview": pressPreview("suggestion.dismiss"),
1611
+ /**
1612
+ * A13's two commitment controls that change a record (`delete`, `move`):
1613
+ * the words the press acts on, its state and version, and where a move
1614
+ * would take it. Read under the person's own credential, so a commitment
1615
+ * they cannot see is not found.
1616
+ */
1617
+ "commitment.delete.preview": (input = {}) => commitmentPreview({ runtime, input }),
1618
+ "commitment.move.preview": (input = {}) => commitmentPreview({ runtime, input }),
1619
+ /**
1620
+ * Jelly's answer 5: the memory a confirm or correct acts on, at the version
1621
+ * the person saw. Read under the person's own credential, so a record they
1622
+ * cannot see is not found.
1623
+ */
1624
+ "memory.revise.preview": async ({ space, id: memoryId } = {}) => {
1625
+ const { records, missing } = await runtime.recordsClient.call("records.get", { ids: [memoryId] }, { space })
1626
+ const record = records?.[0]
1627
+ if (!record || missing?.length || record.kind !== "memory") return { found: false, id: String(memoryId ?? ""), version: 0, body: "", status: "" }
1628
+ return {
1629
+ found: true,
1630
+ id: record.id,
1631
+ version: Number(record.version) || 0,
1632
+ body: String(record.body ?? "").slice(0, 4000),
1633
+ status: String(record.status ?? ""),
1634
+ }
1635
+ },
1636
+ /**
1637
+ * The Inbox's own preview (Jelly's answers 2 and 6): the item behind
1638
+ * Memory's key (`proposal:rec_…`), as the review preview shows it.
1639
+ */
1640
+ "inbox.decide.preview": async ({ itemId } = {}) => {
1641
+ const key = String(itemId ?? "")
1642
+ const proposalId = key.startsWith("proposal:") ? key.slice("proposal:".length) : key
1643
+ if (!proposalId) return { found: false, id: key, version: 0, state: "", kind: "", space: "", text: "" }
1644
+ return proposalPreview({ id: proposalId })
1645
+ },
1646
+ /** A12: the lines an erase would remove, and the digest it is signed for. */
1647
+ "profile.erase.preview": async ({ phrase } = {}) => {
1648
+ const word = String(phrase ?? "").trim()
1649
+ if (word.length < MIN_ERASE_CHARS) {
1650
+ return { lines: [], count: 0, snapshot: "", tooShort: true, note: ERASE_NOTE.slice(0, ERASE_NOTE_CHARS) }
1651
+ }
1652
+ const hits = await erasePlan({ backend, personalScopes, phrase: word })
1653
+ const lines = hits.slice(0, ERASE_LINES_MAX).map((line) => ({ id: line.id, text: line.text.slice(0, 300), space: "" }))
1654
+ return { lines, count: hits.length, snapshot: snapshotOf(hits), tooShort: false, note: ERASE_NOTE.slice(0, ERASE_NOTE_CHARS) }
1655
+ },
1656
+ }
1657
+ }
1658
+
1659
+ /**
1660
+ * A12's erase through the memory core, after records spent the grant: the same
1661
+ * lines the preview showed, removed from the persona and from each scenario.
1662
+ * The core is the only place it can happen, so the action's answer counts what
1663
+ * went and the receipt says it was decided.
1664
+ */
1665
+ export async function eraseProfile({ backend, personalScopes, phrase }) {
1666
+ const word = String(phrase ?? "").trim()
1667
+ if (word.length < MIN_ERASE_CHARS) return 0
1668
+ let removed = 0
1669
+ for (const { scope } of await personalScopes()) {
1670
+ const core = await backend.readCore({ scope }).catch(() => null)
1671
+ const persona = String(core?.content ?? "")
1672
+ if (matchingLines(persona, word).length > 0) {
1673
+ const { content, removed: gone } = eraseLines(persona, word)
1674
+ await backend.writeCore({ content, scope })
1675
+ removed += gone
1676
+ }
1677
+ const list = await backend.listScenarios({ scope }).catch(() => null)
1678
+ for (const entry of list?.entries ?? []) {
1679
+ const path = String(entry?.path ?? "")
1680
+ if (!path || path.endsWith("/")) continue
1681
+ const data = await backend.readScenario({ path, scope }).catch(() => null)
1682
+ const content = String(data?.content ?? "")
1683
+ if (matchingLines(content, word).length === 0) continue
1684
+ const { content: next, removed: gone } = eraseLines(content, word)
1685
+ await backend.writeScenario({ path, content: next, scope })
1686
+ removed += gone
1687
+ }
1688
+ }
1689
+ return removed
1690
+ }