@joe-broadhead/opencode-mem 0.9.14 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +1856 -0
  2. package/README.md +15 -7
  3. package/SECURITY.md +3 -1
  4. package/docs/agent-instructions.md +1 -1
  5. package/docs/agent-protocol.md +7 -7
  6. package/docs/permissions.md +16 -0
  7. package/package.json +8921 -1070
  8. package/shared/page-paths.js +44 -0
  9. package/skills/mem.pages/SKILL.md +3 -1
  10. package/skills/mem.usage/SKILL.md +15 -15
  11. package/src/action-grant-keys.js +159 -0
  12. package/src/action-grant.js +439 -0
  13. package/src/actions.js +1690 -0
  14. package/src/backend/records.js +25 -2
  15. package/src/backend/v3.js +76 -22
  16. package/src/call-shapes.js +17 -16
  17. package/src/collector-lock.js +533 -62
  18. package/src/collector-service.js +153 -26
  19. package/src/collector.js +623 -30
  20. package/src/config.js +88 -7
  21. package/src/connect.js +106 -8
  22. package/src/credentials.js +123 -25
  23. package/src/events.js +174 -3
  24. package/src/forget-turn.js +141 -0
  25. package/src/host-refusal.js +78 -0
  26. package/src/index.js +209 -22
  27. package/src/jobs/host.js +557 -0
  28. package/src/ops/codes.js +110 -0
  29. package/src/ops/copy-lineage.js +42 -0
  30. package/src/ops/index.js +28 -0
  31. package/src/ops/space-ops.js +1936 -0
  32. package/src/outlinks.js +103 -0
  33. package/src/p2-reservation.js +151 -0
  34. package/src/permissions.js +30 -0
  35. package/src/plugins/descriptor.js +62 -0
  36. package/src/plugins/discovery.js +318 -0
  37. package/src/plugins/grants.js +178 -0
  38. package/src/plugins/locate.js +319 -0
  39. package/src/plugins/manifest.js +1162 -0
  40. package/src/plugins/source-contract/index.js +34 -0
  41. package/src/plugins/source-contract/policy.js +102 -0
  42. package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
  43. package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
  44. package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
  45. package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
  46. package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
  47. package/src/plugins/source-contract/vendor/broker-client.js +93 -0
  48. package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
  49. package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
  50. package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
  51. package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
  52. package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
  53. package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
  54. package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
  55. package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
  56. package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
  57. package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
  58. package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
  59. package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
  60. package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
  61. package/src/plugins/source-contract/vendor/cursor.js +26 -0
  62. package/src/plugins/source-contract/vendor/descriptor.js +34 -0
  63. package/src/plugins/source-contract/vendor/events.js +257 -0
  64. package/src/plugins/source-contract/vendor/index.js +10 -0
  65. package/src/plugins/source-contract/vendor/params.js +22 -0
  66. package/src/plugins/source-contract/vendor/permission.js +28 -0
  67. package/src/plugins/source-contract/vendor/pick.js +22 -0
  68. package/src/plugins/source-contract/vendor/read.js +29 -0
  69. package/src/plugins/source-contract/vendor/registry.js +23 -0
  70. package/src/plugins/source-contract/vendor/schema.js +17 -0
  71. package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
  72. package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
  73. package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
  74. package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
  75. package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
  76. package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
  77. package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
  78. package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
  79. package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
  80. package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
  81. package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
  82. package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
  83. package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
  84. package/src/plugins/source-contract/vendor/schemas.js +19 -0
  85. package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
  86. package/src/plugins/verify.js +56 -0
  87. package/src/protocol.js +11 -6
  88. package/src/recall.js +92 -5
  89. package/src/records.js +61 -2
  90. package/src/requests.js +216 -0
  91. package/src/runtime.js +89 -7
  92. package/src/setup-time.js +68 -0
  93. package/src/skills.js +230 -8
  94. package/src/source-ids.js +25 -0
  95. package/src/sources/declaration.js +365 -0
  96. package/src/sources/reads.js +772 -0
  97. package/src/sources/rpc.js +151 -0
  98. package/src/sources.js +389 -92
  99. package/src/spaces.js +283 -11
  100. package/src/spool.js +61 -4
  101. package/src/stated.js +10 -5
  102. package/src/storable.js +139 -0
  103. package/src/tools/commitments.js +74 -23
  104. package/src/tools/held-write.js +46 -19
  105. package/src/tools/index.js +28 -0
  106. package/src/tools/ingest.js +38 -2
  107. package/src/tools/memory.js +56 -25
  108. package/src/tools/page.js +212 -95
  109. package/src/tools/recall.js +218 -4
  110. package/src/tools/share.js +42 -3
  111. package/src/tools/shared.js +84 -6
  112. package/src/tools/space-lifecycle.js +278 -0
  113. package/src/tools/spaces.js +381 -30
  114. package/src/tools/status.js +9 -2
  115. package/src/tools/wiki.js +231 -116
  116. package/src/util.js +110 -6
  117. package/src/vendor/source-contract/README.md +24 -0
  118. package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
  119. package/src/vendor/source-contract/VENDOR.json +81 -0
  120. package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
  121. package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
  122. package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
  123. package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
  124. package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
  125. package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
  126. package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
  127. package/src/vendor/source-contract/cursor.js +26 -0
  128. package/src/vendor/source-contract/events.js +257 -0
  129. package/src/vendor/source-contract/registry.js +23 -0
  130. package/src/vendor/source-contract/tools-rpc.js +42 -0
  131. package/src/views/access-reads.js +256 -0
  132. package/src/views/communities.js +77 -0
  133. package/src/views/contracts.js +1082 -23
  134. package/src/views/inbox-bytes.js +103 -0
  135. package/src/views/profile.js +31 -0
  136. package/src/views/receipt.js +26 -1
  137. package/src/views/records-reads.js +520 -41
  138. package/src/views/rpc.js +153 -25
  139. package/src/views/shape.js +8 -5
  140. package/src/views/write-state.js +89 -0
  141. package/src/wiki-ingest.js +215 -0
  142. package/src/wiki-state.js +228 -0
  143. package/views/pages.html +2 -2
package/src/spaces.js CHANGED
@@ -72,7 +72,8 @@ export function createControlClient(input) {
72
72
  async function bearer(operation) {
73
73
  if (!credentials) return token
74
74
  try {
75
- return await credentials.bearer()
75
+ // The control plane's own origin: the identity token is never for another.
76
+ return await credentials.bearer(controlURLOf())
76
77
  } catch (error) {
77
78
  throw new ControlError(operation, Number(error?.status) || 0, oneLine(errorMessage(error)), { cause: error })
78
79
  }
@@ -81,15 +82,32 @@ export function createControlClient(input) {
81
82
  async function renewed(rejected) {
82
83
  if (!credentials) return ""
83
84
  try {
84
- return await credentials.refresh(rejected)
85
+ return await credentials.refresh(rejected, controlURLOf())
85
86
  } catch {
86
87
  return ""
87
88
  }
88
89
  }
89
90
 
91
+ /**
92
+ * The reservation a G2-P act carries (docs/design/p2-control.md): records
93
+ * spent the host's grant and answered this proof, and the gateway and control
94
+ * verify and spend it. Three body fields, never a header: the gateway's
95
+ * allow-list takes them where the act's own change goes.
96
+ *
97
+ * @param {{ token: string, act: string, input: string } | null | undefined} p2
98
+ * @returns {Record<string, string>} the fields to merge into the body
99
+ */
100
+ function p2Body(p2) {
101
+ if (!p2) return {}
102
+ if (typeof p2.token !== "string" || !p2.token || typeof p2.act !== "string" || !p2.act || typeof p2.input !== "string" || !p2.input) {
103
+ throw new ControlError("host action", 0, "the reservation is not {token, act, input}", { errorCode: "SPACES_GRANT_MISSING", next: "press the action again in the host, which reserves it" })
104
+ }
105
+ return { p2: p2.token, p2_act: p2.act, p2_input: p2.input }
106
+ }
107
+
90
108
  /**
91
109
  * @param {string} operation
92
- * @param {"GET" | "POST" | "DELETE"} method
110
+ * @param {"GET" | "POST" | "PATCH" | "DELETE"} method
93
111
  * @param {string} route
94
112
  * @param {{ query?: Record<string, string | undefined>, body?: unknown }} [options]
95
113
  */
@@ -150,7 +168,9 @@ export function createControlClient(input) {
150
168
  const rawCode = json?.code ?? json?.error?.code
151
169
  const code = typeof rawCode === "string" && /^[a-z][a-z0-9_]{1,63}$/.test(rawCode) ? rawCode : ""
152
170
  const text = typeof message?.message === "string" ? message.message : String(message)
153
- throw new ControlError(operation, response.status, oneLine(code && !text.includes(code) ? `${text} (${code})` : text))
171
+ // The gateway's words are shown, and a failure can quote the URL it
172
+ // failed on: the same redaction every failure text gets (0.10.4's gate).
173
+ throw new ControlError(operation, response.status, oneLine(errorMessage((code && !text.includes(code) ? `${text} (${code})` : text) || "request failed"), 400))
154
174
  }
155
175
  return unwrap(json)
156
176
  } catch (error) {
@@ -176,6 +196,35 @@ export function createControlClient(input) {
176
196
  return extractSpaceList(payload).map(normalizeSpace).filter((space) => space.space_id)
177
197
  }
178
198
 
199
+ /**
200
+ * The shared spaces the person may join (#58 A11): control's own answer, not
201
+ * a filter of `listSpaces`, because only control knows an open space's
202
+ * visibility, an archived one, and a request that still stands. Only a space
203
+ * its owner opened is named; a grant never lists one. Each row is
204
+ * `{ space, name, kind, about, members, join, yourRequest? }`; `name` is empty
205
+ * when control will not name the space to this person, and the request's id
206
+ * and every upstream field are dropped here. `more` says control cut the list.
207
+ */
208
+ async function joinableSpaces({ userId } = {}) {
209
+ if (!userId) throw missing("spaces", "user_id")
210
+ const payload = await request("spaces", "GET", "/v1/spaces/joinable", { query: { user_id: String(userId) } })
211
+ const rows = Array.isArray(payload?.spaces) ? payload.spaces : []
212
+ return {
213
+ spaces: rows
214
+ .filter((row) => isPlainObject(row) && text(row.space))
215
+ .map((row) => ({
216
+ space: text(row.space),
217
+ name: oneLine(text(row.name), 200),
218
+ kind: text(row.kind) === "topic" ? "topic" : "team",
219
+ ...(text(row.about) ? { about: oneLine(text(row.about), 300) } : {}),
220
+ ...(Number.isInteger(row.members) && row.members >= 0 ? { members: row.members } : {}),
221
+ join: text(row.join) === "open" ? "open" : "request",
222
+ ...(text(row.yourRequest) === "pending" ? { yourRequest: "pending" } : {}),
223
+ })),
224
+ more: payload?.more === true,
225
+ }
226
+ }
227
+
179
228
  /**
180
229
  * Resolve the active context, or the context for one requested space.
181
230
  *
@@ -252,22 +301,34 @@ export function createControlClient(input) {
252
301
  }
253
302
 
254
303
  /**
255
- * List the grants that name the caller in one space.
304
+ * List the grants the caller may see in one space.
256
305
  *
257
306
  * The public route is intentionally read-only: the control plane decides
258
307
  * which grants the caller may see, and the plugin only renders the answer.
308
+ * One registered page, folder or wiki is asked for by `resource_id`, the
309
+ * parameter the gateway's share route reads (`deploy/auth/space-admin-api.mjs`:
310
+ * "with resource_id: every grant on that resource, for its owner or an
311
+ * admin"), and an older `targetType: "resource"` with `targetId` means the
312
+ * same one target. Without a target the route answers the grants that name
313
+ * the caller: it never names every grant in a space to a key.
314
+ *
259
315
  * Only display fields are retained so an upstream control response cannot
260
316
  * leak a container, cell, or service id.
261
317
  *
262
- * @param {{ userId: string, spaceId: string }} input
318
+ * @param {{ userId: string, spaceId: string, scope?: "mine" | "space", resourceId?: string, targetType?: "resource", targetId?: string }} input
263
319
  */
264
- async function listGrants({ userId, spaceId, resourceId } = {}) {
320
+ async function listGrants({ userId, spaceId, scope, resourceId, targetType, targetId } = {}) {
265
321
  if (!userId) throw missing("grants", "user_id")
266
322
  if (!spaceId) throw missing("grants", "space_id")
267
- // With resource_id: who a shared page or folder is shared with (its owner
268
- // or a space admin may ask). Without: the grants that name the caller.
323
+ const target = text(resourceId) || (targetType === "resource" ? text(targetId) : "")
269
324
  const payload = await request("grants", "GET", "/v1/grants", {
270
- query: { space_id: String(spaceId), resource_id: resourceId ? String(resourceId) : undefined },
325
+ query: {
326
+ space_id: String(spaceId),
327
+ // `mine` is the grants naming the caller; `space` is every grant in it,
328
+ // which control answers only to an owner or admin of the space.
329
+ ...(scope === "mine" || scope === "space" ? { scope } : {}),
330
+ ...(target ? { resource_id: target } : {}),
331
+ },
271
332
  })
272
333
  return extractGrantList(payload).map(normalizeGrant).filter((grant) => grant.grant_id)
273
334
  }
@@ -422,13 +483,196 @@ export function createControlClient(input) {
422
483
  }
423
484
  }
424
485
 
486
+ /**
487
+ * A person's own space lifecycle (DESIGN-CRUD S1; the gateway's
488
+ * space-lifecycle-api.mjs): create a shared space (placed at once), rename
489
+ * it, archive or unarchive it, and the G2 preview, leave and handover. The
490
+ * answers keep display fields only; the preview token is opaque.
491
+ */
492
+ const spaceOf = (value) => (isPlainObject(value) && text(value.id) ? { space_id: text(value.id), name: text(value.name), kind: text(value.kind), status: text(value.status), role: text(value.role) } : null)
493
+ const spacePath = (spaceId, rest = "") => `/v1/spaces/${encodeURIComponent(String(spaceId))}${rest}`
494
+
495
+ async function createSpace({ userId, name, kind, visibility, members } = {}) {
496
+ if (!userId) throw missing("space create", "user_id")
497
+ const body = { name: String(name ?? "") }
498
+ // #58 A5: what kind of space it is and who may join it. Control keeps its
499
+ // own kind (`shared`) and validates both values.
500
+ if (kind !== undefined) body.kind = String(kind)
501
+ if (visibility !== undefined) body.visibility = String(visibility)
502
+ if (Array.isArray(members) && members.length > 0) body.members = members
503
+ const payload = await request("space create", "POST", "/v1/spaces", { body })
504
+ return {
505
+ space: spaceOf(payload?.space),
506
+ flavor: payload?.flavor === undefined ? null : String(payload.flavor ?? ""),
507
+ visibility: payload?.visibility === undefined ? null : String(payload.visibility ?? ""),
508
+ members: Array.isArray(payload?.members) ? payload.members : [],
509
+ owned: Number(payload?.owned) || null,
510
+ cap: Number(payload?.cap) || null,
511
+ }
512
+ }
513
+
514
+ /** #58 A11: join an open space. */
515
+ async function joinSpace({ userId, spaceId } = {}) {
516
+ if (!userId) throw missing("space join", "user_id")
517
+ if (!spaceId) throw missing("space join", "space_id")
518
+ const payload = await request("space join", "POST", `${spacePath(spaceId, "/join")}`, { body: {} })
519
+ return { state: text(payload?.state) || "joined", space: spaceOf(payload?.space) }
520
+ }
521
+
522
+ /** #58 A11: ask to join an invite-only space. */
523
+ async function requestJoinSpace({ userId, spaceId, note } = {}) {
524
+ if (!userId) throw missing("space join request", "user_id")
525
+ if (!spaceId) throw missing("space join request", "space_id")
526
+ const payload = await request("space join request", "POST", spacePath(spaceId, "/join-request"), { body: { ...(note ? { note: String(note) } : {}) } })
527
+ return { requestId: text(payload?.request_id), state: text(payload?.state) || "pending" }
528
+ }
529
+
530
+ /**
531
+ * #58 A3/A8: who reads one path in a space — members, and the grants that
532
+ * cover it (space, folder prefix, page). A group is reported as the group.
533
+ */
534
+ async function readers({ userId, spaceId, path } = {}) {
535
+ if (!userId) throw missing("readers", "user_id")
536
+ if (!spaceId) throw missing("readers", "space_id")
537
+ // Without a path: the space's own readers, members and space-wide grants.
538
+ const payload = await request("readers", "GET", spacePath(spaceId, "/readers"), { query: path ? { path: String(path) } : {} })
539
+ return {
540
+ path: payload?.path ?? (path ? String(path) : null),
541
+ space: spaceOf(payload?.space),
542
+ readers: Array.isArray(payload?.readers) ? payload.readers : [],
543
+ // A caller who reaches the space only through a page grant gets counts,
544
+ // never a name: the member list is a member's to read.
545
+ counts: payload?.counts && typeof payload.counts === "object" ? payload.counts : null,
546
+ }
547
+ }
548
+
549
+ /** #58 A11: a space's owner or admins decide a join request. */
550
+ async function decideJoinRequest({ userId, requestId, decision, note } = {}) {
551
+ if (!userId) throw missing("join decision", "user_id")
552
+ if (!requestId) throw missing("join decision", "request_id")
553
+ if (!["approve", "decline"].includes(String(decision))) throw new ControlError("join decision", 0, 'decision is "approve" or "decline"', { errorCode: "SPACES_INPUT_MISSING", next: "send approve or decline" })
554
+ const payload = await request("join decision", "POST", `/v1/join-requests/${encodeURIComponent(String(requestId))}/${decision}`, { body: { ...(note ? { note: String(note) } : {}) } })
555
+ return { requestId: text(payload?.request_id) || String(requestId), state: text(payload?.state), space: spaceOf(payload?.space) }
556
+ }
557
+
558
+ /** #58 A11: who may join a shared space; the owner's own act, in the console. */
559
+ async function updateVisibility({ userId, spaceId, visibility, p2 } = {}) {
560
+ if (!userId) throw missing("space visibility", "user_id")
561
+ if (!spaceId) throw missing("space visibility", "space_id")
562
+ if (!["invite", "open"].includes(String(visibility))) throw new ControlError("space visibility", 0, 'visibility is "invite" or "open"', { errorCode: "SPACES_INPUT_MISSING", next: "send visibility: invite or open" })
563
+ const payload = await request("space visibility", "PATCH", spacePath(spaceId), { body: { visibility: String(visibility), ...p2Body(p2) } })
564
+ return { visibility: text(payload?.visibility), space: spaceOf(payload?.space) }
565
+ }
566
+
567
+ async function listJoinRequests({ userId } = {}) {
568
+ if (!userId) throw missing("join requests", "user_id")
569
+ const payload = await request("join requests", "GET", "/v1/spaces/join-requests")
570
+ return { requests: Array.isArray(payload?.requests) ? payload.requests : [] }
571
+ }
572
+
573
+ /** #58 A6: the preview of a grant, as control plans it (a read). */
574
+ async function previewGrant({ userId, grant } = {}) {
575
+ if (!userId) throw missing("share preview", "user_id")
576
+ return await request("share preview", "POST", "/v1/grants/preview", { body: grant ?? {} })
577
+ }
578
+
579
+ async function previewRevoke({ userId, grantId } = {}) {
580
+ if (!userId) throw missing("share preview", "user_id")
581
+ if (!grantId) throw missing("share preview", "grant_id")
582
+ return await request("share preview", "POST", `/v1/grants/${encodeURIComponent(String(grantId))}/preview`, { body: {} })
583
+ }
584
+
585
+ /** #58 A7: a handover, as a request the person it names decides. */
586
+ async function requestTransfer({ userId, target, to, p2 } = {}) {
587
+ if (!userId) throw missing("transfer", "user_id")
588
+ const payload = await request("transfer", "POST", "/v1/transfers", { body: { target: target ?? {}, to: String(to ?? ""), ...p2Body(p2) } })
589
+ return { requestId: text(payload?.request_id), state: text(payload?.state) || "pending" }
590
+ }
591
+
592
+ async function listTransfers({ userId } = {}) {
593
+ if (!userId) throw missing("transfers", "user_id")
594
+ const payload = await request("transfers", "GET", "/v1/transfers")
595
+ return { requests: Array.isArray(payload?.requests) ? payload.requests : [] }
596
+ }
597
+
598
+ async function decideTransfer({ userId, requestId, decision, note, p2 } = {}) {
599
+ if (!userId) throw missing("transfer decision", "user_id")
600
+ if (!requestId) throw missing("transfer decision", "request_id")
601
+ if (!["accept", "decline"].includes(String(decision))) throw new ControlError("transfer decision", 0, 'decision is "accept" or "decline"', { errorCode: "SPACES_INPUT_MISSING", next: "send accept or decline" })
602
+ const payload = await request("transfer decision", "POST", `/v1/transfers/${encodeURIComponent(String(requestId))}/${decision}`, { body: { ...(note ? { note: String(note) } : {}), ...p2Body(p2) } })
603
+ return { state: text(payload?.state), target: payload?.target ?? null }
604
+ }
605
+
606
+ async function updateSpace({ userId, spaceId, name, status, expectedDigest, p2 } = {}) {
607
+ if (!userId) throw missing("space update", "user_id")
608
+ if (!spaceId) throw missing("space update", "space_id")
609
+ const body = {}
610
+ if (name !== undefined) body.name = String(name)
611
+ if (status !== undefined) body.status = String(status)
612
+ if (expectedDigest) body.expected_digest = String(expectedDigest)
613
+ Object.assign(body, p2Body(p2))
614
+ const payload = await request("space update", "PATCH", spacePath(spaceId), { body })
615
+ return { space: spaceOf(payload?.space), from: text(payload?.from), unchanged: payload?.unchanged === true }
616
+ }
617
+
618
+ async function previewSpace({ userId, spaceId, action, user } = {}) {
619
+ if (!userId) throw missing("space preview", "user_id")
620
+ if (!spaceId) throw missing("space preview", "space_id")
621
+ const payload = await request("space preview", "POST", spacePath(spaceId, "/preview"), { body: { action: String(action), ...(user ? { user_id: String(user) } : {}) } })
622
+ const effect = isPlainObject(payload?.effect) ? payload.effect : {}
623
+ const digest = text(payload?.expected_digest)
624
+ if (!digest) throw new ControlError("space preview", 502, "the gateway returned no expected_digest")
625
+ return {
626
+ action: text(payload?.action),
627
+ space: { space_id: text(payload?.space?.id), name: text(payload?.space?.name) },
628
+ summary: text(effect.summary),
629
+ reversible: effect.reversible === true,
630
+ newOwner: isPlainObject(effect.new_owner) ? { user_id: text(effect.new_owner.user_id), name: text(effect.new_owner.name) } : null,
631
+ digest,
632
+ }
633
+ }
634
+
635
+ async function leaveSpace({ userId, spaceId, expectedDigest, p2 } = {}) {
636
+ if (!userId) throw missing("space leave", "user_id")
637
+ const payload = await request("space leave", "POST", spacePath(spaceId, "/leave"), { body: { expected_digest: String(expectedDigest ?? ""), ...p2Body(p2) } })
638
+ return { left: payload?.left === true }
639
+ }
640
+
641
+ /**
642
+ * A handover from a tool is a bearer's call, so it files the request; the
643
+ * owner performs it in the console (ownership cannot be taken back, and
644
+ * performing it needs P1). `requested` says which happened.
645
+ */
646
+ async function handoverSpace({ userId, spaceId, user, expectedDigest } = {}) {
647
+ if (!userId) throw missing("space handover", "user_id")
648
+ const payload = await request("space handover", "POST", spacePath(spaceId, "/handover"), { body: { user_id: String(user ?? ""), expected_digest: String(expectedDigest ?? "") } })
649
+ return { requested: payload?.requested === true, handedOver: payload?.handed_over === true, owner: text(payload?.owner_user_id), next: text(payload?.next) }
650
+ }
651
+
425
652
  return {
426
653
  get controlURL() {
427
654
  return controlURLOf()
428
655
  },
656
+ createSpace,
657
+ joinSpace,
658
+ requestJoinSpace,
659
+ listJoinRequests,
660
+ decideJoinRequest,
661
+ updateVisibility,
662
+ readers,
663
+ previewGrant,
664
+ previewRevoke,
665
+ requestTransfer,
666
+ listTransfers,
667
+ decideTransfer,
668
+ updateSpace,
669
+ previewSpace,
670
+ leaveSpace,
671
+ handoverSpace,
429
672
  lookupUser,
430
673
  sharedWithMe,
431
674
  listSpaces,
675
+ joinableSpaces,
432
676
  resolveContext,
433
677
  effectiveAccess,
434
678
  listGrants,
@@ -494,16 +738,27 @@ function withKind(items, kind) {
494
738
  })
495
739
  }
496
740
 
497
- function normalizeSpace(item) {
741
+ export function normalizeSpace(item) {
498
742
  const space = isPlainObject(item?.space) ? item.space : isPlainObject(item) ? item : {}
499
743
  const id = space.space_id ?? space.id ?? space.spaceId ?? item?.space_id
500
744
  const kind = String(space.kind ?? space.space_kind ?? item?.kind ?? "").toLowerCase()
501
745
  const role = space.role ?? space.my_role ?? item?.role
746
+ const count = (value) => {
747
+ const number = Number(value)
748
+ return Number.isInteger(number) && number >= 0 ? number : undefined
749
+ }
750
+ const members = count(space.member_count ?? item?.member_count)
751
+ const wikis = count(space.wiki_count ?? item?.wiki_count)
502
752
  return {
503
753
  space_id: id === undefined || id === null ? "" : String(id),
504
754
  name: text(space.name ?? space.title ?? item?.name),
505
755
  kind: kind === "personal" || kind === "shared" ? kind : "unknown",
506
756
  role: role === undefined || role === null ? "" : String(role),
757
+ // Counts, never the rows behind them (jelly #55): how many people the space
758
+ // is shared with and how many wikis it holds, when control answers them.
759
+ // A count is not a grant list, so a grant still never lists a space.
760
+ ...(members === undefined ? {} : { members }),
761
+ ...(wikis === undefined ? {} : { wikis }),
507
762
  }
508
763
  }
509
764
 
@@ -567,9 +822,18 @@ function normalizeContext(payload, requested) {
567
822
  const collectionID = first(collection.id, collection.collection_id, root.collection_id, root.collectionId)
568
823
  const agent = isPlainObject(root.agent) ? root.agent.name ?? root.agent.id : root.agent_name ?? root.agent_id ?? root.agent
569
824
  const kind = String(space.kind ?? space.space_kind ?? root.space_kind ?? "").toLowerCase()
825
+ // The person the server itself names (0.10.3 page-owner-name; review F1):
826
+ // behind the gateway the request's `user_id` is the plugin's own and control
827
+ // renames the caller to its `usr_…` id, so a roster read that compares only
828
+ // `user_id` matches nobody. `id` is control's own user id, `upstream_user_id`
829
+ // the memory id a records answer keeps as a page's owner.
830
+ const user = isPlainObject(root.user) ? root.user : {}
570
831
 
571
832
  return {
572
833
  user_id: text(root.user_id ?? requested.userId),
834
+ auth_user_id: text(first(user.auth_user_id, user.authUserId, user.id, root.auth_user_id)),
835
+ upstream_user_id: text(first(user.upstream_user_id, user.upstreamUserId, user.upstream_id, root.upstream_user_id)),
836
+ routing,
573
837
  space_id: text(first(space.id, space.space_id, root.space_id, requested.spaceId)),
574
838
  space_name: text(space.name ?? root.space_name),
575
839
  space_kind: kind === "personal" || kind === "shared" ? kind : "unknown",
@@ -601,12 +865,20 @@ function normalizeGrant(grant) {
601
865
  inherit: grant?.inherit === true || grant?.inherit === 1 || grant?.inherit === "1",
602
866
  expires_at: text(grant?.expires_at),
603
867
  created_at: text(grant?.created_at),
868
+ // Who a user grant names, for its owner or an admin listing it: control's
869
+ // own display fields (`deploy/auth/space-admin-api.mjs`, `projectGrant`).
870
+ ...(text(grant?.principal_name) ? { principal_name: text(grant.principal_name) } : {}),
871
+ ...(text(grant?.principal_email) ? { principal_email: text(grant.principal_email) } : {}),
604
872
  }
605
873
  }
606
874
 
607
875
  function normalizeMember(member) {
608
876
  return {
609
877
  user_id: text(member?.user_id ?? member?.userId ?? member?.id),
878
+ // The person's memory (upstream) user id: what the records service keeps as
879
+ // a page's `owner`, so a roster read can name that owner. It is not shown
880
+ // anywhere: `user_id` is the person's id, as the members read reports it.
881
+ upstream_user_id: text(member?.upstream_user_id ?? member?.upstreamUserId),
610
882
  name: text(member?.name),
611
883
  email: text(member?.email),
612
884
  role: text(member?.role),
package/src/spool.js CHANGED
@@ -29,6 +29,25 @@ const CLAIM_SUFFIX = /\.(\d+)-(\d+)\.inflight$/
29
29
  /** The retry fields a 0.9.7 or older entry kept inside its payload. */
30
30
  const LEGACY_STATE_FIELDS = ["attempts", "lastError", "lastStatus", "lastAttemptAt", "nextAttemptAt", "quarantine"]
31
31
 
32
+ /**
33
+ * The leading part of a turn's idempotency key, unique to its session and
34
+ * message. A spooled entry of one turn is found by it whatever its payload
35
+ * (src/forget-turn.js), so a turn can be deleted without its text. Only
36
+ * characters the gateway accepts are kept.
37
+ *
38
+ * @param {string} sessionID
39
+ * @param {string | null | undefined} messageID
40
+ */
41
+ export function turnKeyPrefix(sessionID, messageID) {
42
+ const session = safeKeyPart(sessionID) || "session"
43
+ return `${/^[A-Za-z0-9]/.test(session) ? "" : "s"}${session}:${safeKeyPart(messageID) || "-"}:`
44
+ }
45
+
46
+ /** One part of an idempotency key, in the gateway's alphabet. */
47
+ function safeKeyPart(value) {
48
+ return String(value ?? "").replace(/[^A-Za-z0-9._:-]/g, "_").slice(0, 190)
49
+ }
50
+
32
51
  /**
33
52
  * A captured turn's idempotency key: its session, its message, and a hash of
34
53
  * the payload. The live send and every replay of one spooled turn send the
@@ -40,9 +59,16 @@ const LEGACY_STATE_FIELDS = ["attempts", "lastError", "lastStatus", "lastAttempt
40
59
  * @param {unknown} payload
41
60
  */
42
61
  export function turnKey(sessionID, messageID, payload) {
43
- const safe = (value) => String(value ?? "").replace(/[^A-Za-z0-9._:-]/g, "_").slice(0, 190)
44
- const session = safe(sessionID) || "session"
45
- return `${/^[A-Za-z0-9]/.test(session) ? "" : "s"}${session}:${safe(messageID) || "-"}:${shortHash(JSON.stringify(payload ?? null), 16)}`
62
+ return `${turnKeyPrefix(sessionID, messageID)}${shortHash(JSON.stringify(payload ?? null), 16)}`
63
+ }
64
+
65
+ /**
66
+ * Whether the gateway refused this capture because the person erased the turn
67
+ * (`409 capture_tombstoned`). Its entry is deleted, never quarantined: text the
68
+ * person asked to forget must not sit in a quarantine file for 14 days.
69
+ */
70
+ export function isTombstoned(error) {
71
+ return error?.code === "capture_tombstoned" || error?.errorCode === "capture_tombstoned"
46
72
  }
47
73
 
48
74
  /**
@@ -493,9 +519,32 @@ export function createSpool(input) {
493
519
  })
494
520
  }
495
521
 
522
+ /**
523
+ * Delete an entry the gateway refused because its turn was erased. The log
524
+ * names the file and kind, never the content: an id-only record of the
525
+ * refusal.
526
+ */
527
+ function dropTombstoned(claimed) {
528
+ let kind = null
529
+ try {
530
+ kind = JSON.parse(fs.readFileSync(claimed, "utf8"))?.kind ?? null
531
+ } catch {
532
+ /* the kind is only for the log */
533
+ }
534
+ removeSpool(claimed)
535
+ log.info("spooled capture of a turn the person erased was dropped, not kept", {
536
+ file: path.basename(pendingOf(claimed)),
537
+ kind,
538
+ })
539
+ }
540
+
496
541
  /** Return a staged capture after a failed live send. */
497
542
  function releaseSpool(claimed, error) {
498
543
  if (!claimed) return null
544
+ if (isTombstoned(error)) {
545
+ dropTombstoned(claimed)
546
+ return "dropped"
547
+ }
499
548
  if (isUnlinked(error)) {
500
549
  let entry = null
501
550
  try {
@@ -895,6 +944,11 @@ export function createSpool(input) {
895
944
  continue
896
945
  }
897
946
 
947
+ if (isTombstoned(failure)) {
948
+ dropTombstoned(claimed)
949
+ result.dropped = (result.dropped ?? 0) + 1
950
+ continue
951
+ }
898
952
  if (isUnlinked(failure)) {
899
953
  dropUnlinked(claimed, entry)
900
954
  result.dropped = (result.dropped ?? 0) + 1
@@ -957,7 +1011,10 @@ export function createSpool(input) {
957
1011
  }
958
1012
  quarantined.push({
959
1013
  at: new Date(at).toISOString(),
960
- reason: oneLine(typeof reason === "string" ? reason : "reason not recorded (the process stopped while quarantining it)", 160),
1014
+ // The reason was redacted where it was written; a state file from an
1015
+ // older version may still hold raw text, so it is redacted on the way
1016
+ // out as well (a broker's failure text, shown in health).
1017
+ reason: oneLine(errorMessage(typeof reason === "string" && reason ? reason : "reason not recorded (the process stopped while quarantining it)"), 160),
961
1018
  expires: new Date(at + QUARANTINE_TTL_MS).toISOString(),
962
1019
  })
963
1020
  }
package/src/stated.js CHANGED
@@ -318,9 +318,15 @@ function triggerWords(text) {
318
318
  }
319
319
 
320
320
  /**
321
- * Whether the person's messages name the event of `trigger`: at least half of
322
- * its content words (and one at the least) appear in them. A trigger of only
323
- * "when" words names nothing to check and passes.
321
+ * Whether the person's messages name the event of `trigger`: **every** content
322
+ * word of the trigger appears in them. A trigger of only "when" words names
323
+ * nothing to check and passes.
324
+ *
325
+ * 0.11 gate H2: half the words was enough for the agent's own trigger, "Before
326
+ * the Shared Workspace handover to Ama can be previewed", because the person had
327
+ * said "Hand the Shared Workspace memory space over to Ama" — the condition was
328
+ * the agent's, the words were hers. A condition the person stated is made of
329
+ * words they wrote.
324
330
  *
325
331
  * @param {string} trigger
326
332
  * @param {Array<{ text: string }>} messages
@@ -329,6 +335,5 @@ export function triggerStated(trigger, messages) {
329
335
  const wanted = triggerWords(trigger)
330
336
  if (wanted.length === 0) return true
331
337
  const said = new Set(messages.flatMap((message) => triggerWords(message.text)))
332
- const hits = wanted.filter((word) => said.has(word)).length
333
- return hits >= Math.max(1, Math.ceil(wanted.length / 2))
338
+ return wanted.every((word) => said.has(word))
334
339
  }