@joe-broadhead/opencode-mem 0.9.0 → 0.9.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.
@@ -3,6 +3,7 @@ import { REMEMBER_WRAPPER } from "../copies.js"
3
3
  import { errorMessage, isPlainObject, oneLine, redactSecrets } from "../util.js"
4
4
  import { isCoded } from "../errors.js"
5
5
  import { canWriteShared } from "./shared.js"
6
+ import { holdTeamWrite } from "./held-write.js"
6
7
 
7
8
  /**
8
9
  * `mem_share` (docs/design/memory-v1-contracts.md §4.1; memory-tools-v1.md §10):
@@ -82,7 +83,6 @@ const LEGACY_ID = /^(m_|msg[-_])/
82
83
  const MAX_COPY_IDS = 20
83
84
  const MAX_COPY_CHARS = 8_000
84
85
  /** Records whose owner a folder transfer changes at most. */
85
- const MAX_TRANSFER_RECORDS = 1_000
86
86
  /** The legacy copy scan: newest rows per layer and agent (as mem_forget). */
87
87
  const SCAN_PAGE = 100
88
88
  const SCAN_PAGES = 3
@@ -331,18 +331,28 @@ export function createShareActions(toolkit) {
331
331
  return { records: answer?.records ?? [], cursor: answer?.cursor }
332
332
  }
333
333
 
334
- /** Register the page or folder as a `wiki_page` resource (idempotent) and return its id. */
335
- async function registerTarget(target, spaceContext, title) {
336
- const resource = await control.createResource({
337
- userId: userOf(spaceContext),
338
- spaceId: spaceContext.space_id,
339
- resource: {
340
- kind: "wiki_page",
341
- upstream_id: upstreamIdFor(target),
342
- name: oneLine(target.kind === "page" ? `${title || target.path} (${target.path})` : `Folder ${target.path}`, 200),
343
- },
344
- })
345
- return String(resource?.id ?? "").trim()
334
+ /** Look up or register the page/folder; control rejects duplicate registrations. */
335
+ async function registerTarget(target, spaceContext, title, { returnResource = false } = {}) {
336
+ const lookup = async () => (await sharedResources(spaceContext)).find((entry) => entry.upstream_id === upstreamIdFor(target))
337
+ let resource = await lookup()
338
+ if (!resource) {
339
+ try {
340
+ resource = await control.createResource({
341
+ userId: userOf(spaceContext),
342
+ spaceId: spaceContext.space_id,
343
+ resource: {
344
+ kind: "wiki_page",
345
+ upstream_id: upstreamIdFor(target),
346
+ name: oneLine(target.kind === "page" ? `${title || target.path} (${target.path})` : `Folder ${target.path}`, 200),
347
+ },
348
+ })
349
+ } catch (error) {
350
+ if (Number(error?.status) !== 409) throw error
351
+ resource = await lookup()
352
+ if (!resource) throw error
353
+ }
354
+ }
355
+ return returnResource ? resource : String(resource?.id ?? "").trim()
346
356
  }
347
357
 
348
358
  /** The space's shared pages and folders (`wiki_page` resources with a `records:` id). */
@@ -474,9 +484,10 @@ export function createShareActions(toolkit) {
474
484
  })
475
485
  } catch (error) {
476
486
  log.warn("share grant failed", error)
477
- return fail(`${target.path} is registered (resource ${resourceId}), but the grant failed (${errorMessage(error)}). Nothing was shared.`)
487
+ return fail(`${target.path} is registered (resource ${resourceId}), but the grant outcome is unknown (${errorMessage(error)}). Check current grants before retrying.`)
478
488
  }
479
- const grantId = row?.grant_id || "(no id returned)"
489
+ const grantId = row?.grant_id
490
+ if (!grantId) return fail(`${target.path} is registered (resource ${resourceId}), but the grant outcome is unknown: no grant id was returned. Check current grants before retrying.`)
480
491
  log.info("share grant", { space: spaceContext.space_id, kind: target.kind, role })
481
492
  const folderNote = target.kind === "folder" ? ` It covers every page under ${target.path} (${found.records.length}${found.cursor ? "+" : ""} now), including pages added later.` : ""
482
493
  return text(
@@ -625,7 +636,8 @@ export function createShareActions(toolkit) {
625
636
  await callRecords("records.delete", { ids }, where)
626
637
  } catch (error) {
627
638
  log.warn("copy revoke failed", error)
628
- return fail(`the copies were not deleted: ${recordsFailure(error)}`)
639
+ if (error?.outcomeUnknown) return fail(recordsFailure(error))
640
+ return fail(`the delete was not confirmed: ${recordsFailure(error)}`)
629
641
  }
630
642
  let back
631
643
  try {
@@ -657,6 +669,7 @@ export function createShareActions(toolkit) {
657
669
  let found
658
670
  try {
659
671
  found = await readTarget(target, where)
672
+ if (target.kind === "folder") found.records = await allUnder(target, where, found)
660
673
  } catch (error) {
661
674
  if (recordsServiceMissing(error)) return text(sharingNeedsRecords("transfer"))
662
675
  return fail(recordsFailure(error))
@@ -676,32 +689,34 @@ export function createShareActions(toolkit) {
676
689
 
677
690
  let resourceId
678
691
  try {
679
- resourceId = await registerTarget(target, spaceContext, found.title)
692
+ const resource = await registerTarget(target, spaceContext, found.title, { returnResource: true })
693
+ resourceId = String(resource?.id ?? "").trim()
680
694
  if (!resourceId) throw new Error("registration returned no resource id")
681
- const moved = await control.transferResource({ userId: userOf(spaceContext), spaceId: spaceContext.space_id, resourceId, toUserId: principal.id })
682
- if (moved?.transferred === false) throw new Error("control did not transfer it")
695
+ if (resource.owner_user_id !== principal.id) {
696
+ const moved = await control.transferResource({ userId: userOf(spaceContext), spaceId: spaceContext.space_id, resourceId, toUserId: principal.id })
697
+ if (moved?.transferred === false && moved?.owner_user_id !== principal.id) throw new Error("control did not confirm the requested owner")
698
+ }
683
699
  } catch (error) {
684
700
  log.warn("share transfer failed", error)
685
- return fail(`${target.path} was not transferred: ${errorMessage(error)}. Nothing changed.`)
701
+ return fail(`${target.path}: control transfer did not complete or could not be confirmed (${errorMessage(error)}). Registration or ownership may have changed; check control before retrying. No page owners were changed by this call.`)
686
702
  }
687
703
 
688
704
  // Control now names the new owner; the records under the path follow
689
705
  // (contract §3: records.put with the new owner).
690
- const pages = target.kind === "page" ? found.records : await allUnder(target, where, found)
706
+ const pages = found.records
691
707
  const failed = []
692
- for (const record of pages.slice(0, MAX_TRANSFER_RECORDS)) {
708
+ for (const record of pages) {
693
709
  try {
694
710
  await putOwner(record, principal.id, where)
695
711
  } catch (error) {
696
712
  failed.push(`${record.path || record.id} (${recordsFailure(error)})`)
697
713
  }
698
714
  }
699
- const over = pages.length > MAX_TRANSFER_RECORDS ? pages.length - MAX_TRANSFER_RECORDS : 0
700
715
  log.info("share transfer", { space: spaceContext.space_id, kind: target.kind, pages: pages.length, failed: failed.length })
701
716
  const done = `transferred ${target.kind} ${target.path} in ${toolkit.describeSpace(spaceContext)} to ${principal.label}: control's resource ${resourceId} names them as owner`
702
- if (failed.length > 0 || over > 0) {
717
+ if (failed.length > 0) {
703
718
  return fail(
704
- `${done}, but ${failed.length + over} of ${pages.length} page(s) still name the old owner${failed.length ? `: ${failed.slice(0, 5).join("; ")}` : ""}${over ? `; ${over} past the ${MAX_TRANSFER_RECORDS}-page limit` : ""}. Repeat the same call to finish.`,
719
+ `${done}, but ${failed.length} of ${pages.length} page owner update(s) failed or could not be confirmed: ${failed.slice(0, 5).join("; ")}. Check the current page owners before retrying; an owner or space admin with access to the remaining pages may need to finish it.`,
705
720
  )
706
721
  }
707
722
  return text(`${done}, and ${pages.length} page(s) now name them as owner. You keep the access your space role gives you.`)
@@ -710,7 +725,10 @@ export function createShareActions(toolkit) {
710
725
  async function allUnder(target, where, first) {
711
726
  const out = [...first.records]
712
727
  let cursor = first.cursor
713
- while (cursor && out.length < MAX_TRANSFER_RECORDS + 1) {
728
+ const seen = new Set()
729
+ while (cursor) {
730
+ if (seen.has(cursor)) throw new Error("records.list repeated a cursor; folder enumeration is incomplete")
731
+ seen.add(cursor)
714
732
  const answer = await callRecords("records.list", { kind: "page", path_prefix: target.path, limit: 200, cursor }, where)
715
733
  out.push(...(answer?.records ?? []))
716
734
  cursor = answer?.cursor
@@ -721,7 +739,7 @@ export function createShareActions(toolkit) {
721
739
  /** Set a record's owner; on a version conflict, read it again once and retry. */
722
740
  async function putOwner(record, owner, where) {
723
741
  if (record.owner === owner) return
724
- const put = (current) => callRecords("records.put", { record: { ...current, owner, base_version: current.version } }, where)
742
+ const put = (current) => callRecords("records.put", { record: { id: current.id, owner, base_version: current.version } }, where)
725
743
  try {
726
744
  await put(record)
727
745
  } catch (error) {
@@ -848,12 +866,27 @@ export function createShareActions(toolkit) {
848
866
  }
849
867
 
850
868
  const { spaceContext, where } = target
869
+ if (config.heldTeamWrites) {
870
+ const by = userOf(personal) || userOf(spaceContext) || "unknown"
871
+ const proposed = sources.map((source) => ({
872
+ kind: "memory", type: source.type, title: oneLine(source.title || source.text, 300), body: source.text,
873
+ stated_by: source.stated_by || "person",
874
+ fields: { copied_from: { space: personal.space_id, id: source.id, by, rationale: oneLine(rationale, 500) } },
875
+ source: context?.sessionID ? { session: String(context.sessionID) } : {},
876
+ }))
877
+ try {
878
+ return text(await holdTeamWrite(toolkit, context, spaceContext, proposed))
879
+ } catch (error) {
880
+ if (error?.outcomeUnknown) return fail(errorMessage(error))
881
+ return fail(`held write failed: ${errorMessage(error)}. No memories were copied.`)
882
+ }
883
+ }
851
884
  const denied = await approve(
852
885
  context,
853
886
  {
854
887
  action: "memory.promote",
855
888
  resources: ids,
856
- metadata: { space: spaceContext.space_id, rationale, copies: sources.map((source) => `${source.id} (${source.type}): ${oneLine(source.text, 160)}`) },
889
+ metadata: { space: spaceContext.space_id, space_id: spaceContext.space_id, ...(spaceContext.space_name ? { space_name: oneLine(spaceContext.space_name, 200) } : {}), rationale, copies: sources.map((source) => `${source.id} (${source.type}): ${oneLine(source.text, 160)}`) },
857
890
  },
858
891
  "not copied (approval)",
859
892
  )
@@ -884,19 +917,21 @@ export function createShareActions(toolkit) {
884
917
  made.push({ from: source.id, id })
885
918
  } catch (error) {
886
919
  log.warn("copy write failed", error)
920
+ if (error?.outcomeUnknown) return fail(`${errorMessage(error)} ${made.length ? `Already confirmed copies: ${made.map((entry) => entry.id).join(", ")}.` : "No earlier copies were confirmed."}`)
887
921
  // The records service is missing on this server (legacy m_/msg- ids
888
922
  // are read from the core, so the first write is where it shows).
889
923
  if (recordsServiceMissing(error) && made.length === 0) return text(sharingNeedsRecords("copy"))
890
- let cleanup = "nothing was left behind"
924
+ let cleanup = "no earlier copies were confirmed"
891
925
  if (made.length > 0) {
892
926
  try {
893
- await callRecords("records.delete", { ids: made.map((entry) => entry.id) }, where)
894
- cleanup = `the ${made.length} cop${made.length === 1 ? "y" : "ies"} already written ${made.length === 1 ? "was" : "were"} deleted`
927
+ const deleted = await callRecords("records.delete", { ids: made.map((entry) => entry.id) }, where)
928
+ const unconfirmed = made.filter((entry) => !(deleted?.deleted ?? []).includes(entry.id)).map((entry) => entry.id)
929
+ cleanup = unconfirmed.length ? `deletion of ${unconfirmed.join(", ")} was not confirmed; check the shared space before retrying` : `the ${made.length} cop${made.length === 1 ? "y" : "ies"} already written ${made.length === 1 ? "was" : "were"} deleted`
895
930
  } catch (cleanupError) {
896
- cleanup = `${made.map((entry) => entry.id).join(", ")} remain (${recordsFailure(cleanupError)}); revoke them with mem_share ("action": "revoke", "ids")`
931
+ cleanup = `deletion of ${made.map((entry) => entry.id).join(", ")} was not confirmed (${recordsFailure(cleanupError)}); check the shared space before retrying`
897
932
  }
898
933
  }
899
- return fail(`copying ${source.id} failed (${recordsFailure(error)}); ${cleanup}. Nothing was shared.`)
934
+ return fail(`copying ${source.id} failed (${recordsFailure(error)}); ${cleanup}.`)
900
935
  }
901
936
  }
902
937
  log.info("copy", { space: spaceContext.space_id, count: made.length })
@@ -1,6 +1,7 @@
1
1
  import { contextScopeLabel, scopeLabel, taskKey } from "../scope.js"
2
2
  import { errorMessage, oneLine } from "../util.js"
3
3
  import { isCoded } from "../errors.js"
4
+ import { hasSharedWritePolicy } from "../permissions.js"
4
5
 
5
6
  /**
6
7
  * Roles that may write to a shared space. The plugin reads this from the
@@ -219,7 +220,7 @@ export function createToolkit(ctx, runtime) {
219
220
  return { key, declared: true }
220
221
  }
221
222
 
222
- /** Team-visible writes and deletes pass through the host approval gate. */
223
+ /** An assertion enforces host policy, but does not prove a prompt appeared. */
223
224
  async function assertTeamWrite(context, action, resources, metadata) {
224
225
  await ctx.permission.assert({
225
226
  sessionID: context?.sessionID,
@@ -230,6 +231,12 @@ export function createToolkit(ctx, runtime) {
230
231
  save: [],
231
232
  metadata,
232
233
  })
234
+ // On older hosts a default * allow may pass with no action policy. Require
235
+ // a visible action-specific rule there; never infer that a prompt appeared.
236
+ if (["memory.remember", "memory.revise", "page.write", "wiki.write"].includes(action) &&
237
+ !(await hasSharedWritePolicy(ctx, context, action, resources))) {
238
+ throw new Error(`no explicit permission rule for ${action} is visible on this host; no write was made. Add an allow or ask rule for ${action} (or memory.* for memory actions), or update OpenCode`)
239
+ }
233
240
  }
234
241
 
235
242
  /**
@@ -324,7 +324,7 @@ export function createSpacesActions(toolkit) {
324
324
  await records().call("sources.bind", { source: binding.source, account: binding.account, owner, enabled: true }, space.where)
325
325
  } catch (error) {
326
326
  log.warn("sources bind failed", error)
327
- return fail(`not bound: ${recordsFailure(error)}`)
327
+ return fail(`${error?.outcomeUnknown ? "bind outcome unknown" : "not bound"}: ${recordsFailure(error)}`)
328
328
  }
329
329
  let after = rows
330
330
  try {
@@ -354,7 +354,7 @@ export function createSpacesActions(toolkit) {
354
354
  answer = await records().call("sources.unbind", { source: binding.source, account: binding.account }, space.where)
355
355
  } catch (error) {
356
356
  log.warn("sources unbind failed", error)
357
- return fail(`not unbound: ${recordsFailure(error)}`)
357
+ return fail(`${error?.outcomeUnknown ? "unbind outcome unknown" : "not unbound"}: ${recordsFailure(error)}`)
358
358
  }
359
359
  let after = rows.filter((entry) => entry !== row)
360
360
  try {
@@ -422,7 +422,7 @@ export function createSpacesActions(toolkit) {
422
422
  answer = await records().call("review.decide", { id, decision, ...(payload ? { payload } : {}), ...(reason ? { reason } : {}) }, space.where)
423
423
  } catch (error) {
424
424
  log.warn("review decide failed", error)
425
- return fail(`not decided: ${recordsFailure(error)}`)
425
+ return fail(`${error?.outcomeUnknown ? "decision outcome unknown" : "not decided"}: ${recordsFailure(error)}`)
426
426
  }
427
427
  const applied = answer?.applied
428
428
  const appliedText = isPlainObject(applied) && applied.id ? ` Applied as ${oneLine(applied.id, 40)}${applied.path ? ` (${oneLine(applied.path, 120)})` : ""}.` : ""
package/src/tools/wiki.js CHANGED
@@ -141,7 +141,7 @@ export function registerWiki(editor, toolkit) {
141
141
  filename,
142
142
  ...(action === "create" ? { name: oneLine(input?.name, 200) } : {}),
143
143
  bytes: Buffer.byteLength(content),
144
- excerpt: redactSecrets(content.slice(0, APPROVAL_EXCERPT_CHARS)),
144
+ excerpt: redactSecrets(content).slice(0, APPROVAL_EXCERPT_CHARS),
145
145
  }
146
146
  }
147
147
 
@@ -166,7 +166,11 @@ export function registerWiki(editor, toolkit) {
166
166
  async function approveWrite(context, visibility, spaceContext, approval) {
167
167
  if (visibility !== "team") return ""
168
168
  try {
169
- await assertTeamWrite(context, "wiki.write", [spaceContext?.space_id ?? "team"], approval)
169
+ await assertTeamWrite(context, "wiki.write", [spaceContext?.space_id ?? "team"], {
170
+ ...approval,
171
+ ...(spaceContext?.space_id ? { space_id: spaceContext.space_id } : {}),
172
+ ...(spaceContext?.space_name ? { space_name: oneLine(spaceContext.space_name, 200) } : {}),
173
+ })
170
174
  return ""
171
175
  } catch (error) {
172
176
  return errorMessage(error)
@@ -597,7 +601,7 @@ export function registerWiki(editor, toolkit) {
597
601
  editor.add({
598
602
  name: "wiki",
599
603
  description:
600
- "Call list, search and read for documentation, architecture, ownership and call-graph questions about what was uploaded or indexed. Write only documents the person gave you, as flat source files (\"notes.md\"; a name with a folder is refused). A space has a knowledge wiki only once action create makes one (name it \"My knowledge\" in the personal space); list shows which wikis exist. A write starts an ingest that locks the wiki for a few minutes: to write several files, pass ingest: false on each and ingest: true on the last. Like mem_recall it uses the session's space by default: your personal space, or a shared space bound to the session. A write to a shared space asks the person and shows the file and an excerpt; a write to your personal space does not. delete removes one source file (filename), one generated page (ref), or a whole wiki (wiki_id alone): without confirm it only previews; with confirm: true it always asks the person, then deletes and reads it back. Never put things to do (mem_commitments), where a project stands, or person and project pages (mem_page) here.",
604
+ "When asked to read a named document or wiki file, use mem_wiki read (or search to find it), even if mem_recall might answer. Call list, search and read for documentation, architecture, ownership and call-graph questions about what was uploaded or indexed. Write only documents the person gave you, as flat source files (\"notes.md\"; a name with a folder is refused). A space has a knowledge wiki only once action create makes one (name it \"My knowledge\" in the personal space); list shows which wikis exist. A write starts an ingest that locks the wiki for a few minutes: to write several files, pass ingest: false on each and ingest: true on the last. Like mem_recall it uses the session's space by default: your personal space, or a shared space bound to the session. A write to a shared space asks the person and shows the file and an excerpt; a write to your personal space does not. delete removes one source file (filename), one generated page (ref), or a whole wiki (wiki_id alone): without confirm it only previews; with confirm: true it always asks the person, then deletes and reads it back. Never put things to do (mem_commitments), where a project stands, or person and project pages (mem_page) here.",
601
605
  input: {
602
606
  type: "object",
603
607
  properties: {
@@ -134,6 +134,8 @@ const overviewOutput = {
134
134
  /** Capture as this engine runs it now: the declared setting, read at start. */
135
135
  capture: { type: "boolean" },
136
136
  health: { type: "string", enum: ["ok", "unreachable", "unknown"] },
137
+ extraction: { type: "string", enum: ["healthy", "failing", "unknown"] },
138
+ failing_since: line(40),
137
139
  /** Whether the records service answers (memories are records from 0.9); "unavailable" says the page shows `RECORDS_OFF`. */
138
140
  records: { type: "string", enum: ["ok", "unavailable"] },
139
141
  space,
@@ -387,6 +389,17 @@ const reviewListOutput = object({
387
389
  more: flag,
388
390
  })
389
391
 
392
+ const inboxOutput = object({
393
+ items: list(object({
394
+ key: line(200),
395
+ category: { type: "string", enum: ["request"] },
396
+ label: line(40),
397
+ name: line(120),
398
+ line: line(120),
399
+ at: line(40),
400
+ }), REVIEW_MAX),
401
+ })
402
+
390
403
  const pagesListOutput = object({
391
404
  space,
392
405
  /** The folder listed, "" for the top. */
@@ -526,6 +539,13 @@ export const VIEW_METHODS = Object.freeze([
526
539
  input: viewInput(spaceInput),
527
540
  output: reviewListOutput,
528
541
  },
542
+ {
543
+ name: "inbox.list",
544
+ label: "list proposals waiting for your review",
545
+ permission: "mem_spaces",
546
+ input: empty,
547
+ output: inboxOutput,
548
+ },
529
549
  {
530
550
  name: "pages.list",
531
551
  label: "list your pages by folder",
@@ -0,0 +1,59 @@
1
+ import { asVerifiedView } from "../credentials.js"
2
+ import { decideProposal as decideHeldProposal } from "../tools/held-write.js"
3
+
4
+ /** Actions for a proposal read from the records service, not from the caller. */
5
+ export function proposalActions(proposal) {
6
+ return proposal?.type === "team_write" ? ["accept", "private", "decline"] : ["accept", "decline"]
7
+ }
8
+
9
+ /**
10
+ * Integration seam, deliberately not registered as RPC. A future Jelly action
11
+ * handler must verify the action grant, bind `caller` to its signed member and
12
+ * input, and supply a proposal reader using that person's credentials. Never
13
+ * pass a caller or proposal supplied by a page as authority.
14
+ */
15
+ export function createInboxDecision({ loadProposal, decideProposal } = {}) {
16
+ return async ({ key, decision, caller } = {}) => {
17
+ if (typeof key !== "string" || !/^proposal:rec_[0-9A-Za-z]{1,64}$/.test(key) || !["accept", "private", "decline"].includes(decision)) {
18
+ return { ok: false, code: "invalid_input" }
19
+ }
20
+ if (!caller || typeof loadProposal !== "function" || typeof decideProposal !== "function") return { ok: false, code: "unavailable" }
21
+ let proposal
22
+ try {
23
+ proposal = await loadProposal({ key, caller })
24
+ } catch {
25
+ return { ok: false, code: "unavailable" }
26
+ }
27
+ if (!proposal || (proposal.status !== "proposed" && !(proposal.status === "accepting" && decision === "accept"))) return { ok: false, code: "not_pending" }
28
+ if (!proposalActions(proposal).includes(decision)) return { ok: false, code: "invalid_decision" }
29
+ // J-HELD JOIN: the sole mutation call. J-HELD owns authorization, the
30
+ // shared-space ask, atomicity, replay and the returned decision result.
31
+ return decideProposal({ key, decision, caller })
32
+ }
33
+ }
34
+
35
+ /** Join the public Inbox key to the authenticated author's personal store. */
36
+ export function createHeldInboxDecision(runtime) {
37
+ async function personal(caller) {
38
+ if (!runtime?.control || caller?.runtime !== runtime || !/^view_[A-Za-z0-9_-]{1,123}$/.test(caller?.speaker ?? "")) throw new Error("authenticated caller required")
39
+ if (typeof runtime.availability === "function" && await runtime.availability()) throw new Error("unavailable")
40
+ const active = await runtime.resolveContext({})
41
+ const space = active?.personal_space_id
42
+ if (!space) throw new Error("personal space unavailable")
43
+ const own = await runtime.resolveContext({ space })
44
+ if (own?.space_id !== space || own.space_kind !== "personal" || own.personal_space_id !== space || own.role !== "owner" || !own.user_id) throw new Error("personal space unverified")
45
+ return own
46
+ }
47
+ return createInboxDecision({
48
+ loadProposal: ({ key, caller }) => asVerifiedView(caller.speaker, async () => {
49
+ const own = await personal(caller)
50
+ const answer = await runtime.recordsClient.call("records.get", { ids: [key.slice("proposal:".length)] }, { space: own.space_id })
51
+ const proposal = answer?.records?.[0]
52
+ return proposal?.kind === "proposal" && proposal?.type === "team_write" && proposal?.author?.user === own.user_id ? proposal : null
53
+ }),
54
+ decideProposal: ({ key, decision, caller }) => asVerifiedView(caller.speaker, async () => {
55
+ const own = await personal(caller)
56
+ return decideHeldProposal({ key: `${own.space_id}:${key.slice("proposal:".length)}`, decision, caller })
57
+ }),
58
+ })
59
+ }
@@ -0,0 +1,12 @@
1
+ /** Build the bounded metadata for a recall result; input is the curated search result. */
2
+ export function recallResultView({ coverage, scopeNote, records, atoms, conversations, failures, documentIncomplete } = {}) {
3
+ const text = (value) => typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 600) : ""
4
+ const count = (value) => Array.isArray(value) ? Math.min(value.length, 1000) : 0
5
+ return {
6
+ v: 1,
7
+ coverage: text(coverage),
8
+ scopeNote: text(scopeNote),
9
+ counts: { records: count(records), atoms: count(atoms), conversations: count(conversations) },
10
+ incomplete: Boolean(documentIncomplete || (Array.isArray(failures) && failures.length)),
11
+ }
12
+ }
package/src/views/rpc.js CHANGED
@@ -11,6 +11,11 @@ import {
11
11
  } from "./contracts.js"
12
12
  import { createRecordsReads, recordsFailureWords } from "./records-reads.js"
13
13
  import { SPACE_KINDS, ViewRefusal, clip, clipText, idOf, refuse, spaceOf } from "./shape.js"
14
+ import { createHeldInboxDecision } from "./inbox-decision.js"
15
+
16
+ // Jelly has no Inbox action route, signed-grant verifier, or ask bridge yet (#33).
17
+ // Never enable in production until all three are available and independently verified.
18
+ export const INBOX_ACTION_RPC_ENABLED = false
14
19
 
15
20
  /**
16
21
  * The RPC behind Memory's views in Jelly (`views/*.html`).
@@ -53,6 +58,14 @@ const AGENT_TTL_MS = 60_000
53
58
  /** A page's text is held well under Jelly's 64 KB answer cap. */
54
59
  const PAGE_TEXT_BYTES = 56_000
55
60
 
61
+ function inboxTime(value) {
62
+ const match = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:Z|([+-])(\d\d):(\d\d))$/.exec(value)
63
+ if (!match) return false
64
+ const [, year, month, day, hour, minute, second, , offsetHour, offsetMinute] = match
65
+ const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)))
66
+ return date.getUTCFullYear() === Number(year) && date.getUTCMonth() + 1 === Number(month) && date.getUTCDate() === Number(day) && Number(hour) < 24 && Number(minute) < 60 && Number(second) < 60 && Number(offsetHour ?? 0) < 24 && Number(offsetMinute ?? 0) < 60
67
+ }
68
+
56
69
  const CREDENTIALS = Object.freeze({
57
70
  [SOURCES.identity]: "jelly",
58
71
  [SOURCES.secret]: "key",
@@ -145,6 +158,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
145
158
  const base = {
146
159
  capture: config.capture !== false,
147
160
  health: "unknown",
161
+ extraction: "unknown",
148
162
  ...(address ? { address: clip(address, 300) } : {}),
149
163
  }
150
164
  const reason = await unavailableNow()
@@ -165,7 +179,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
165
179
  // Memories are records from 0.9 (the space's count); conversations,
166
180
  // summaries and the profile are still the core's, per agent.
167
181
  const count = (read) => read.then((data) => Number(data?.total) || 0).catch(() => 0)
168
- const [health, kept, perAgent] = await Promise.all([
182
+ const [health, kept, perAgent, extraction] = await Promise.all([
169
183
  backend.probe().catch(() => ({ ok: false })),
170
184
  recordsReads.memoryCount(scopes[0]).catch((error) => {
171
185
  runtime.log?.warn?.("view overview: records count failed", error)
@@ -183,6 +197,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
183
197
  ]),
184
198
  ),
185
199
  ),
200
+ runtime.control && typeof backend.extractionHealth === "function" ? backend.extractionHealth().catch(() => null) : null,
186
201
  ])
187
202
  const counts = { memories: kept.memories, conversations: 0, summaries: 0, profile: false }
188
203
  for (const [conversations, summaries, profile] of perAgent) {
@@ -195,6 +210,8 @@ export function createViewReads({ runtime, agents = async () => [] }) {
195
210
  ...credentialState(),
196
211
  ...base,
197
212
  health: health?.ok ? "ok" : "unreachable",
213
+ extraction: ["healthy", "failing", "unknown"].includes(extraction?.state) ? extraction.state : "unknown",
214
+ ...(extraction?.state === "failing" && typeof extraction.failing_since === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(extraction.failing_since) ? { failing_since: extraction.failing_since } : {}),
198
215
  ...(kept.records ? { records: kept.records } : {}),
199
216
  space: spaceOf(scopes[0]?.context),
200
217
  counts,
@@ -318,8 +335,19 @@ export function createViewReads({ runtime, agents = async () => [] }) {
318
335
  }
319
336
  }
320
337
 
338
+ async function inboxList() {
339
+ const review = await recordsReads.methods["review.list"]({})
340
+ return { items: review.items.flatMap((item) => {
341
+ if (!/^rec_[0-9A-Za-z]{1,64}$/.test(item.id)) return []
342
+ if (!inboxTime(item.created)) return []
343
+ const title = String(item.title).replace(/[\p{Cc}\p{Cf}<>]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 120)
344
+ return [{ key: `proposal:${item.id}`, category: "request", label: "Proposal", name: "Memory", line: title || "A proposal is waiting for review", at: item.created }]
345
+ }) }
346
+ }
347
+
321
348
  return {
322
349
  "commitments.list": commitmentsList,
350
+ "inbox.list": inboxList,
323
351
  "memory.overview": overview,
324
352
  "spaces.list": spacesList,
325
353
  "wiki.list": wikiList,
@@ -411,7 +439,7 @@ export function splitSpeaker(input) {
411
439
  * @param {any} ctx
412
440
  * @param {any} runtime
413
441
  */
414
- export async function registerViewRpc(ctx, runtime) {
442
+ export async function registerViewRpc(ctx, runtime, { enableInboxActions = INBOX_ACTION_RPC_ENABLED, verifyInboxAction } = {}) {
415
443
  if (typeof ctx?.rpc?.register !== "function") return null
416
444
  const reads = createViewReads({ runtime, agents: engineAgents(ctx) })
417
445
  const methods = {}
@@ -432,5 +460,19 @@ export async function registerViewRpc(ctx, runtime) {
432
460
  return typeof speaker === "string" ? asView(speaker, read) : read()
433
461
  }
434
462
  }
463
+ if (enableInboxActions) {
464
+ if (typeof verifyInboxAction !== "function") throw new Error("Inbox actions require a grant verifier and ask bridge")
465
+ const decide = createHeldInboxDecision(runtime)
466
+ methods["act.inbox.decide"] = {
467
+ input: { type: "object", additionalProperties: false, required: ["key", "decision"], properties: { key: { type: "string" }, decision: { type: "string", enum: ["accept", "private", "decline"] } } },
468
+ output: { type: "object" },
469
+ }
470
+ handlers["act.inbox.decide"] = async (input, call) => {
471
+ // The verifier must validate the signed, input-bound grant and enforce the
472
+ // separate memory.revise ask; page-provided identity is never accepted.
473
+ const speaker = await verifyInboxAction({ input, call })
474
+ return decide({ key: input?.key, decision: input?.decision, caller: { runtime, speaker } })
475
+ }
476
+ }
435
477
  return ctx.rpc.register({ id: PACKAGE_NAME, events: {}, methods }, handlers)
436
478
  }
@@ -0,0 +1,123 @@
1
+ <!doctype html>
2
+ <html lang="en-GB">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-5dtPKkjegOPG8bawdSzGBjixnIaSCLYcZOUAwbRWFAc=' 'sha256-LWSrwYvpjwYQwZdOGG46gdsMvGXpb6MbK0p4FgHUWDU='; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
6
+ <title>Recalled memory</title>
7
+ <style>
8
+ :root { color: var(--jelly-text, CanvasText); background: var(--jelly-surface, Canvas); font: 14px/1.5 var(--jelly-font, system-ui, sans-serif); }
9
+ body { margin: 0; padding: 16px; }
10
+ h1 { font-size: 18px; margin: 0 0 12px; }
11
+ p { margin: 8px 0; }
12
+ .muted { color: var(--jelly-muted, GrayText); }
13
+ </style>
14
+ </head>
15
+ <body>
16
+ <main aria-live="polite"><h1>Recalled memory</h1><div id="coverage" class="muted">Loading…</div><div id="scope"></div><div id="counts"></div><div id="incomplete"></div></main>
17
+ <script>
18
+ // jelly-view.js: a client of Jelly's view bridge. Paste it into the page's own <script>:
19
+ // a sealed page loads no script by URL and is given no global. Call jellyView() as the
20
+ // script starts; it resolves with the client when the app says hello.
21
+ function jellyView() {
22
+ return new Promise((resolve) => {
23
+ addEventListener("message", function hello(event) {
24
+ const said = event.data;
25
+ if (event.source !== parent || said?.v !== 1 || said.kind !== "hello" || !event.ports[0])
26
+ return;
27
+ removeEventListener("message", hello);
28
+ const port = event.ports[0];
29
+ const listeners = new Set();
30
+ const latest = new Map();
31
+ const queue = [];
32
+ let sequence = 0;
33
+ let current;
34
+ const theme = (tokens) => {
35
+ const style = document.documentElement.style;
36
+ for (const [name, value] of Object.entries(tokens))
37
+ if (name === "scheme") style.colorScheme = value;
38
+ else style.setProperty(`--jelly-${name}`, value);
39
+ };
40
+ // The app answers one request at a time, so requests go in turn.
41
+ const next = () => {
42
+ if (current !== undefined || queue.length === 0) return;
43
+ current = queue.shift();
44
+ current.timer = setTimeout(
45
+ () => settle({ ok: false, error: "No answer from the app" }),
46
+ 15000,
47
+ );
48
+ port.postMessage(current.message);
49
+ };
50
+ const settle = (answer) => {
51
+ const done = current;
52
+ current = undefined;
53
+ clearTimeout(done.timer);
54
+ if (answer.ok) done.resolve(answer.value);
55
+ else done.reject(new Error(answer.error));
56
+ next();
57
+ };
58
+ port.onmessage = ({ data }) => {
59
+ if (data?.v !== 1) return;
60
+ if (typeof data.kind !== "string") {
61
+ if (current !== undefined && data.re === current.message.id) settle(data);
62
+ return;
63
+ }
64
+ // A call waiting for the person is answered by `until`, not in 15 s.
65
+ if (data.kind === "rpc.waiting" && data.re === current?.message.id) {
66
+ clearTimeout(current.timer);
67
+ current.timer = setTimeout(
68
+ () => settle({ ok: false, error: "No answer from the app" }),
69
+ Math.max(0, Date.parse(data.until) - Date.now()) + 15000,
70
+ );
71
+ }
72
+ if (data.kind === "theme.changed") theme(data.theme);
73
+ // A wait is news only while it lasts, so a later listener is not told of it.
74
+ if (data.kind !== "rpc.waiting") latest.set(data.kind, data);
75
+ for (const listener of listeners) listener(data);
76
+ };
77
+ port.start();
78
+ theme(said.theme);
79
+ const request = (op, fields = {}) =>
80
+ new Promise((resolve, reject) => {
81
+ queue.push({ resolve, reject, message: { ...fields, v: 1, id: String(++sequence), op } });
82
+ next();
83
+ });
84
+ resolve({
85
+ hello: said,
86
+ // A listener first hears the latest push of each kind that came before it.
87
+ on(listener) {
88
+ for (const push of latest.values()) listener(push);
89
+ listeners.add(listener);
90
+ return () => listeners.delete(listener);
91
+ },
92
+ request,
93
+ data: () => request("data.get"),
94
+ state: () => request("state.get"),
95
+ setState: (revision, data) => request("state.set", { revision, data }),
96
+ call: (method, input = {}) => request("rpc.call", { method, input }),
97
+ openAgent: (prefill) => request("open-agent", prefill === undefined ? {} : { prefill }),
98
+ resize: (height) =>
99
+ request("resize", { height: Math.min(1200, Math.max(1, Math.ceil(height))) }),
100
+ decline: () => request("decline"),
101
+ });
102
+ });
103
+ });
104
+ }
105
+ </script>
106
+ <script>
107
+ jellyView().then(async (view) => {
108
+ const result = await view.data();
109
+ const data = result?.metadata?.memoryRecall;
110
+ const coverage = document.getElementById("coverage");
111
+ if (!data || data.v !== 1 || !data.counts || typeof data.incomplete !== "boolean") {
112
+ coverage.textContent = "Recall details are not available for this result.";
113
+ return;
114
+ }
115
+ coverage.textContent = typeof data.coverage === "string" ? data.coverage : "";
116
+ document.getElementById("scope").textContent = typeof data.scopeNote === "string" ? data.scopeNote : "";
117
+ const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : 0;
118
+ document.getElementById("counts").textContent = `${count(data.counts.records)} records · ${count(data.counts.atoms)} atoms · ${count(data.counts.conversations)} conversations matched`;
119
+ document.getElementById("incomplete").textContent = data.incomplete ? "Search incomplete; do not infer absence." : "";
120
+ }).catch(() => { document.getElementById("coverage").textContent = "Recall details are not available for this result."; });
121
+ </script>
122
+ </body>
123
+ </html>