@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
@@ -13,6 +13,17 @@ import { BROWSE_MAX, isSelection, runSelection, selectionRequest } from "./recal
13
13
  const MAX_LIMIT = 25
14
14
  /** Raw turns rendered per recall. Records and atoms carry the distilled answer. */
15
15
  const MAX_TURNS = 4
16
+ /** Unsearched spaces a miss names before it counts the rest. */
17
+ const UNSEARCHED_MAX = 5
18
+
19
+ /** `Alpha, Beta, and 3 more`: the spaces a miss names, bounded. */
20
+ function namedSpaces(names) {
21
+ if (!Array.isArray(names) || names.length === 0) return ""
22
+ const shown = names.slice(0, UNSEARCHED_MAX)
23
+ const rest = names.length - shown.length
24
+ return `${shown.join(", ")}${rest > 0 ? `, and ${rest} more` : ""}`
25
+ }
26
+
16
27
  /** Where recall looks (contract §4.1). */
17
28
  export const RECALL_IN = Object.freeze(["all", "memories", "pages", "transcripts", "documents"])
18
29
  /** Record types `types` filters on: the kinds remember writes, page types, and commitments. */
@@ -120,6 +131,30 @@ export function registerRecall(editor, toolkit) {
120
131
  return rest
121
132
  }
122
133
 
134
+ /**
135
+ * The spaces this recall did not read: the person's own space aside, the
136
+ * names a miss note lists. `[]` when there is no other space (local direct
137
+ * mode has one fixed scope), `null` when the list cannot be read — the note
138
+ * then scopes the claim without naming anything.
139
+ *
140
+ * A name is set by another member of the organisation, so it is untrusted
141
+ * text: neutralised like the scope label beside it, so it cannot close the
142
+ * fence the answer is wrapped in (review S1).
143
+ */
144
+ async function unsearchedNames(spaceContext) {
145
+ if (!control) return []
146
+ try {
147
+ const spaces = await control.listSpaces({ userId: config.user })
148
+ return (spaces ?? [])
149
+ .filter((space) => space.space_id && space.kind !== "personal" && space.space_id !== spaceContext?.space_id && space.space_id !== spaceContext?.personal_space_id)
150
+ .map((space) => neutralizeFenceClosers(oneLine(space.name || space.space_id, 60)))
151
+ .filter(Boolean)
152
+ } catch (error) {
153
+ log.debug("unsearched spaces unread", { error: errorMessage(error) })
154
+ return null
155
+ }
156
+ }
157
+
123
158
  /**
124
159
  * Label record hits by the task they were written under: `task` on the hit
125
160
  * when the service sends it, else read once with `records.get`. A failed
@@ -350,6 +385,13 @@ export function registerRecall(editor, toolkit) {
350
385
  }
351
386
  }
352
387
 
388
+ // The person's own space, and the count of their private matches for
389
+ // this query (0.11.1 gate H2): run before the shared search, so the
390
+ // count is a fact when the note is written and the space's own search
391
+ // stays the last one this call made.
392
+ const ownSpace = !spaceContext || spaceContext.space_kind === "personal"
393
+ const privateCount = !ownSpace && !resolved.granted ? await privateMatchCount() : null
394
+
353
395
  let result = { atoms: [], conversations: [], withheld: addWithheld(), failures: [] }
354
396
  let taskHit = false
355
397
  if (layers.atoms || layers.turns) {
@@ -422,6 +464,7 @@ export function registerRecall(editor, toolkit) {
422
464
  const BROWSE_RECORDS = 6
423
465
  let census
424
466
  let browse
467
+ let stats = null
425
468
  let unmatchedRecords = []
426
469
  const memoryLayers = layers.records || layers.atoms || layers.turns
427
470
  // A lexical records miss can coexist with a core hit on a nearby
@@ -444,6 +487,9 @@ export function registerRecall(editor, toolkit) {
444
487
  log.debug("records fallback unavailable", { error: errorMessage(error) })
445
488
  }
446
489
  }
490
+ // The same `space.stats` answer carries the collected events a space
491
+ // holds (`events.total`, `events.by_source`), kept for the miss line
492
+ // below (0.10.4 gate A16).
447
493
  if (memoryLayers && records.length === 0 && atoms.length === 0 && conversations.length === 0) {
448
494
  const [atomsCount, conversationsCount, recordsCount] = await Promise.all([
449
495
  layers.atoms ? backend.countAtoms({ scope }).then((data) => Number(data?.total) || 0).catch(() => null) : Promise.resolve(0),
@@ -453,7 +499,10 @@ export function registerRecall(editor, toolkit) {
453
499
  // count would tell the caller how much they cannot see.
454
500
  layers.records && !found.unavailable && !found.missingEndpoint && !resolved.granted
455
501
  ? callRecords(toolkit, "space.stats", {}, spaceContext, scope).then(
456
- (data) => recordCount(data, recordKinds),
502
+ (data) => {
503
+ stats = data
504
+ return recordCount(data, recordKinds)
505
+ },
457
506
  () => null,
458
507
  )
459
508
  : Promise.resolve(0),
@@ -501,6 +550,19 @@ export function registerRecall(editor, toolkit) {
501
550
  }
502
551
  }
503
552
 
553
+ // Collected events sit in a layer no recall reads (0.10.4 gate A16: the
554
+ // answer said the collected email was not in Memory). The counts and
555
+ // the collection times are read scoped to the searched space, and no
556
+ // event text is read.
557
+ let collected = null
558
+ if (stats && !census?.failed && Number(stats.events?.total) > 0) {
559
+ const listed = await callRecords(toolkit, "sources.list", {}, spaceContext, scope).catch((error) => {
560
+ log.debug("sources list unavailable", { error: errorMessage(error) })
561
+ return null
562
+ })
563
+ collected = collectedEvents(stats, listed?.sources)
564
+ }
565
+
504
566
  const renderMemory = (maxChars) => memoryLayers
505
567
  ? renderRecallBlock({
506
568
  records,
@@ -520,6 +582,7 @@ export function registerRecall(editor, toolkit) {
520
582
  failures,
521
583
  failureDetail,
522
584
  unmatchedRecords,
585
+ collected,
523
586
  })
524
587
  : ""
525
588
 
@@ -558,12 +621,137 @@ export function registerRecall(editor, toolkit) {
558
621
 
559
622
  const label = neutralizeFenceClosers(oneLine(spaceContext ? displayScope(spaceContext, scoped) : `${scoped.team_id}/${scoped.agent_id}`, 200))
560
623
  const coverage = `Searched in ${label}: ${searched.length ? searched.join(", ") : "no memory layers"}. ${documentCoverage}`.trim()
624
+ // A space that is not the person's own is not their memory: a recall
625
+ // there never reads their personal space, so neither a hit nor a miss
626
+ // supports "memory says nothing about this" (gate 0.10.1 H2,
627
+ // hand-note-no-private#4). A result with a hit only limits the claim;
628
+ // one without a hit also says how to search private memory, so a recall
629
+ // that already answers invites no extra call (protocol rule 3).
630
+ // "Answered" means a memory hit (records, atoms, turns): document text
631
+ // carries no hit count — a space with one index always renders a
632
+ // <knowledge> fence, even with no hit, and a failure block when the
633
+ // search fails — so it cannot say whether the asked fact was found.
634
+ const answered = records.length + atoms.length + conversations.length > 0
635
+ // 0.10.3 (0.10.2 gate H2, suite-lifecycle life-archive-asked#3): the
636
+ // claim names the scope it holds for, and the spaces this result did
637
+ // not read. 0.10.2 scoped a recall in a shared space only, so a miss in
638
+ // the person's own space still supported "nothing in memory records a
639
+ // rule" while the shared space, where a team rule lives, was never
640
+ // searched. A hit only bounds the claim — 0.10.1's H2 was a hit on
641
+ // another topic — and never invites a second search (0.10.2's review;
642
+ // rule 3). Since protocol rule 1 allows another space only when the
643
+ // person named it, the miss says so rather than sending the agent to
644
+ // search one (review S2): the scoped claim is the fix.
645
+ // A note that claims the scope "was searched" needs a search that
646
+ // answered: a failed layer makes the result incomplete, not empty.
647
+ const searchAnswered = failures.length === 0
648
+ const scopedTo = `: say so, or search a space the person named.`
649
+ /**
650
+ * The person's own private memory, counted only (0.11.1 gate H2,
651
+ * hand-note-no-private#5): a recall in a shared space warned that
652
+ * private memory was not searched, and the agent told the person
653
+ * nothing recorded their next week while a private note did. The same
654
+ * query is run against the caller's own personal space, and only the
655
+ * count reaches the answer: no title, text or id, and never another
656
+ * member's space. `null` when there is no personal space or the probe
657
+ * fails, so the note keeps its previous wording.
658
+ */
659
+ async function privateMatchCount() {
660
+ try {
661
+ const privateSpace = await toolkit.resolvePrivateSpace({}, context)
662
+ if (privateSpace?.invalid || privateSpace?.error || !privateSpace?.context?.space_id) return null
663
+ const personal = privateSpace.context
664
+ if (spaceContext && personal.space_id === spaceContext.space_id) return null
665
+ const privateScope = readScope(toolkit.scopeFor(personal, { agent: context?.agent }))
666
+ let count = 0
667
+ if (layers.records) {
668
+ const data = await callRecords(
669
+ toolkit,
670
+ "records.search",
671
+ { query, kinds: recordKinds, ...(types.length > 0 ? { types } : {}), status, limit: 25 },
672
+ personal,
673
+ privateScope,
674
+ )
675
+ count += Array.isArray(data?.hits) ? data.hits.length : 0
676
+ }
677
+ if (layers.atoms) {
678
+ const page = await backend.searchAtoms({ query, limit: 25, scope: privateScope })
679
+ count += Array.isArray(page?.items) ? page.items.length : 0
680
+ }
681
+ if (layers.turns) {
682
+ const page = await backend.searchConversations({ query, limit: 25, scope: privateScope })
683
+ count += Array.isArray(page?.messages) ? page.messages.length : 0
684
+ }
685
+ return count
686
+ } catch (error) {
687
+ log.debug("private count probe failed", { error: errorMessage(error) })
688
+ return null
689
+ }
690
+ }
691
+ let privateNote = ""
692
+ if (resolved.granted && !answered && memoryLayers && searchAnswered) {
693
+ const others = await unsearchedNames(spaceContext)
694
+ privateNote = `Page grant: only the pages granted to the person here were searched, not the person's own memory${others && others.length > 0 ? ` or the spaces they can reach (${namedSpaces(others)})` : ""}, so "not recorded" holds for this grant only${scopedTo}`
695
+ } else if (!ownSpace) {
696
+ // A fact, not a warning (0.11.1 gate H2): the count of the person's
697
+ // own matches. An absence claim that contradicts it is unlikely, and
698
+ // a complete one is true.
699
+ privateNote =
700
+ privateCount === null
701
+ ? answered
702
+ ? `Shared space: only this space was searched, not the person's private memory, so "not recorded" holds for this space only.`
703
+ : `Shared space: the person's private memory was not searched. Search it with visibility: "private" before saying it is not recorded.`
704
+ : privateCount > 0
705
+ ? `The person's private memory has ${privateCount} matching record(s), not shown. Read them with visibility: "private" when the request is about the person's own things, and put on a shared page only what the person asked for.`
706
+ : `The person's private memory has no match either.`
707
+ } else if (control && answered) {
708
+ // A personal-space hit on another topic gets no scope at all today,
709
+ // the mirror of 0.10.1's H2 (review S4). For a person who can reach
710
+ // another space, bound the claim as a shared space's hit does; no
711
+ // names and no invitation, so it costs no call.
712
+ privateNote = `The person's own memory only: "not recorded" holds for it alone.`
713
+ } else if (!answered && memoryLayers && searchAnswered) {
714
+ // Read once, on a miss, so the note can name what it did not search.
715
+ const others = await unsearchedNames(spaceContext)
716
+ if (collected) {
717
+ // 0.10.4 gate A16: the space holds collected events recall cannot
718
+ // read, so a miss is not evidence of absence. The block names them;
719
+ // this note must not license "not recorded" beside it.
720
+ privateNote = `The person's own memory was searched${others && others.length > 0 ? `, not the shared spaces they can reach (${namedSpaces(others)})` : ""}; the collected events it holds are not readable by recall yet${scopedTo}`
721
+ } else if (others === null) {
722
+ privateNote = `The person's own memory was searched, so "not recorded" holds for their own memory only${scopedTo}`
723
+ } else if (others.length > 0) {
724
+ privateNote = `The person's own memory was searched, not the shared spaces they can reach (${namedSpaces(others)}), so "not recorded" holds for their own memory only${scopedTo}`
725
+ }
726
+ }
561
727
  const empty = where === "all" && types.length === 0 && !resolved.granted && census && !census.failed && !withheld.status && !withheld.instruction && !withheld.task && !withheld.redacted && !withheld.forgotten && !withheld.unchecked && census.records + census.atoms + census.conversations === 0 && documentsEmpty
562
728
  const memoryEmpty = where === "all" && types.length === 0 && !resolved.granted && census && !census.failed && !withheld.status && !withheld.instruction && !withheld.task && !withheld.redacted && !withheld.forgotten && !withheld.unchecked && census.records + census.atoms + census.conversations === 0
563
- const next = empty ? "Nothing is recorded in this space. Answer that it is not recorded, or continue the requested work. Do not search again in pages, wiki, spaces, commitments or other tools; a named document can be read directly when requested." : memoryEmpty ? "Nothing is recorded in the searched memory layers of this space. Report any document search limitation above; do not claim unsearched documents are empty. Do not repeat the search in pages, wiki, spaces or commitments." : ""
564
- const memoryBudget = Math.max(100, config.recallChars - coverage.length - 1 - (documents ? documents.length + 2 : 0) - (next ? next.length + 1 : 0))
729
+ // 0.10.2 delta L4: the miss line offers another scope (a private
730
+ // recall, or the space named above), so "do not search again" is scoped
731
+ // to the space that was searched when that line is present; the offered
732
+ // search is not one of the layers it bans. 0.10.3 gives the person's own
733
+ // space the same line, on the same condition.
734
+ const noRescan = privateNote
735
+ ? "Do not search this space again in pages, wiki, spaces, commitments or other tools; a named document can be read directly when requested."
736
+ : "Do not search again in pages, wiki, spaces, commitments or other tools; a named document can be read directly when requested."
737
+ const next = empty
738
+ ? collected
739
+ ? noRescan
740
+ : `Nothing is recorded in this space. Answer that it is not recorded in this space, or continue the requested work. ${noRescan}`
741
+ : memoryEmpty ? "Nothing is recorded in the searched memory layers of this space. Report any document search limitation above; do not claim unsearched documents are empty. Do not repeat the search in pages, wiki, spaces or commitments." : ""
742
+ // 0.11.3: a miss opens with one short, quotable sentence naming what was
743
+ // searched, because agents echo the tool's own words as an absence claim
744
+ // (fast0112's three H2s). It goes first, before the private count. Only a
745
+ // real miss carries it: no hits, nothing listed to check, and no failed
746
+ // layer (an incomplete search is not an absence).
747
+ const listedContext = unmatchedRecords.length > 0
748
+ const missLine =
749
+ records.length + atoms.length + conversations.length === 0 && failures.length === 0 && !listedContext
750
+ ? `Not recorded in ${label}: ${searched.length ? searched.join(", ") : "no memory layers"}.`
751
+ : ""
752
+ const memoryBudget = Math.max(100, config.recallChars - coverage.length - 1 - (missLine ? missLine.length + 1 : 0) - (privateNote ? privateNote.length + 1 : 0) - (documents ? documents.length + 2 : 0) - (next ? next.length + 1 : 0))
565
753
  const memory = renderMemory(memoryBudget)
566
- const block = [coverage, next, memory, documents].filter(Boolean).join("\n")
754
+ const block = [missLine, coverage, privateNote, next, memory, documents].filter(Boolean).join("\n")
567
755
 
568
756
  log.debug("recall", {
569
757
  scope: displayScope(spaceContext, scoped),
@@ -593,3 +781,29 @@ function recordCount(stats, kinds) {
593
781
  if (!byKind || typeof byKind !== "object") return 0
594
782
  return kinds.reduce((sum, kind) => sum + Object.values(byKind[kind] ?? {}).reduce((total, count) => total + (Number(count) || 0), 0), 0)
595
783
  }
784
+
785
+ /**
786
+ * The collected events a space holds that recall cannot read, in the shape the
787
+ * miss line uses: source, account, how many, and when the binding was last
788
+ * collected (`sources.list` `cursor_at`, or a report the collector marked ok).
789
+ * Both answers are counts only: no event text is read.
790
+ *
791
+ * REVIEW F3: the records service writes `collection.at` on every report, a
792
+ * failed one included, so it is a collection time only when `collection.ok`.
793
+ */
794
+ function collectedEvents(stats, sources) {
795
+ const rows = (Array.isArray(stats?.events?.by_source) ? stats.events.by_source : []).filter((row) => row && Number(row.count) > 0)
796
+ if (rows.length === 0) return null
797
+ const collectedAt = new Map()
798
+ for (const row of Array.isArray(sources) ? sources : []) {
799
+ if (!row || !row.source) continue
800
+ const at = row.cursor_at ?? (row.collection?.ok ? row.collection.at : null) ?? null
801
+ if (at) collectedAt.set(`${row.source}\u0000${row.account ?? "default"}`, String(at))
802
+ }
803
+ return {
804
+ sources: rows.map((row) => {
805
+ const account = String(row.account ?? "default")
806
+ return { source: String(row.source), account, count: Number(row.count) || 0, lastCollected: collectedAt.get(`${row.source}\u0000${account}`) ?? null }
807
+ }),
808
+ }
809
+ }
@@ -1,3 +1,4 @@
1
+ import { forwardCopies } from "../ops/copy-lineage.js"
1
2
  import { writeRefusal } from "../curation.js"
2
3
  import { REMEMBER_WRAPPER } from "../copies.js"
3
4
  import { FENCE_TAGS, errorMessage, isPlainObject, neutralizeFenceClosers, oneLine, redactSecrets } from "../util.js"
@@ -961,7 +962,7 @@ export function createShareActions(toolkit) {
961
962
  problems.push(`${id} is ${record.status}; copy the current memory instead`)
962
963
  continue
963
964
  }
964
- found.set(id, { id, type: record.type || "fact", title: record.title, text: String(record.body ?? record.title ?? "").trim(), stated_by: record.stated_by })
965
+ found.set(id, { id, type: record.type || "fact", title: record.title, text: String(record.body ?? record.title ?? "").trim(), stated_by: record.stated_by, event: typeof record.source?.event === "string" ? record.source.event : null })
965
966
  }
966
967
  }
967
968
  if (legacyIds.length > 0) {
@@ -1121,9 +1122,25 @@ export function createShareActions(toolkit) {
1121
1122
  }
1122
1123
  }
1123
1124
  log.info("copy", { space: spaceContext.space_id, count: made.length })
1125
+ // The origin space is told which copies exist (records.copied): a source
1126
+ // removal runs there, and a space cannot read another space's file, so
1127
+ // without this note it could neither retract nor report a copy. A failed
1128
+ // note never fails the copy, which has already happened.
1129
+ let noted = true
1130
+ try {
1131
+ const notedCopies = await callRecords(
1132
+ "records.copied",
1133
+ { to_space: spaceContext.space_id, copies: made.map((entry) => ({ record: entry.from, copy_id: entry.id, origin_event: sources.find((source) => source.id === entry.from)?.event ?? null })) },
1134
+ { space: personal.space_id },
1135
+ )
1136
+ await forwardCopies((body, space) => callRecords("records.copied", body, { space }), notedCopies)
1137
+ } catch (error) {
1138
+ noted = false
1139
+ log.warn("copy registration failed", error)
1140
+ }
1124
1141
  const list = made.map((entry) => `${entry.from} → ${entry.id}`).join(", ")
1125
1142
  return text(
1126
- `copied ${made.length} memor${made.length === 1 ? "y" : "ies"} to ${toolkit.describeSpace(spaceContext)}: ${list}. Each copy names its source (copied_from). They are copies: your private originals are unchanged, and later edits to them do not reach the copies. Members find them with mem_recall in that space. To revoke: mem_share({"action": "revoke", "ids": [${made.map((entry) => `"${entry.id}"`).join(", ")}], "space": "${oneLine(spaceContext.space_id, 80)}"}).`,
1143
+ `copied ${made.length} memor${made.length === 1 ? "y" : "ies"} to ${toolkit.describeSpace(spaceContext)}: ${list}. Each copy names its source (copied_from). They are copies: your private originals are unchanged, and later edits to them do not reach the copies. Members find them with mem_recall in that space. To revoke: mem_share({"action": "revoke", "ids": [${made.map((entry) => `"${entry.id}"`).join(", ")}], "space": "${oneLine(spaceContext.space_id, 80)}"}).${noted ? "" : " The copies are not registered in your private space, so removing what they came from will not report them."}`,
1127
1144
  )
1128
1145
  }
1129
1146
 
@@ -1302,6 +1319,27 @@ export function createShareActions(toolkit) {
1302
1319
  else results.push({ key: label(item), outcome: "not moved", reason: recordsFailure(error) })
1303
1320
  }
1304
1321
  }
1322
+ // The origin space is told every copy exists (records.copied), a move too:
1323
+ // its original is deleted, and a source removal can only report a copy it
1324
+ // can see the note of — never the other space's file (0.11 review, B2). A
1325
+ // failed note never fails the copy, which has already happened.
1326
+ let noted = true
1327
+ if (written.length > 0) {
1328
+ try {
1329
+ const notedMove = await callRecords(
1330
+ "records.copied",
1331
+ {
1332
+ to_space: target.space_id,
1333
+ copies: written.map((entry) => ({ record: entry.item.record.id, copy_id: entry.id, origin_event: entry.item.record.source?.event ?? null })),
1334
+ },
1335
+ fromWhere,
1336
+ )
1337
+ await forwardCopies((body, space) => callRecords("records.copied", body, { space }), notedMove)
1338
+ } catch (error) {
1339
+ noted = false
1340
+ log.warn("move registration failed", error)
1341
+ }
1342
+ }
1305
1343
  if (keep) {
1306
1344
  for (const entry of written) results.push({ key: label(entry.item), outcome: "copied", id: entry.id })
1307
1345
  } else if (written.length > 0) {
@@ -1370,7 +1408,8 @@ export function createShareActions(toolkit) {
1370
1408
  const tail = keep
1371
1409
  ? "Each copy names its source (copied_from); the originals stay."
1372
1410
  : "Each copy names its source (moved_from) and was read back before its original was deleted. Nothing was fingerprinted as forgotten, so recall in the target finds them; recall in the source no longer does."
1373
- return text([head, ...rows, tail].join("\n"))
1411
+ const unregistered = noted ? null : " The copies are not registered in the space they came from, so removing what they came from will not report them."
1412
+ return text([head, ...rows, tail].join("\n") + (unregistered ?? ""))
1374
1413
  }
1375
1414
 
1376
1415
  async function run(input, context) {
@@ -2,8 +2,9 @@ import { contextScopeLabel, scopeLabel, taskKey } from "../scope.js"
2
2
  import { errorMessage, oneLine } from "../util.js"
3
3
  import { isCoded } from "../errors.js"
4
4
  import { assertUnlessSkipped, hasSharedWritePolicy, skipsAsk } from "../permissions.js"
5
- import { asVerifiedSession } from "../credentials.js"
5
+ import { asVerifiedSession, memoryResourceAvailable } from "../credentials.js"
6
6
  import { holdTeamWrite } from "./held-write.js"
7
+ import { readSession } from "../sessions.js"
7
8
 
8
9
  /**
9
10
  * Roles that may write to a shared space. The plugin reads this from the
@@ -56,6 +57,39 @@ export function canWriteShared(role) {
56
57
  return SHARED_WRITE_ROLES.includes(String(role ?? "").trim().toLowerCase())
57
58
  }
58
59
 
60
+ /**
61
+ * 0.11.3: a space the caller names but cannot reach answers with one short,
62
+ * quotable sentence that scopes the claim to what they can reach, because
63
+ * agents restate the tool's own words as an absence claim (fast0112's
64
+ * hand-nonmember-switch #3: "there's no Platform Team space").
65
+ */
66
+ export function unreachableSpace(name) {
67
+ return `No space named "${oneLine(name, 80)}" among the spaces you can reach. {"action": "list"} shows them.`
68
+ }
69
+
70
+ /**
71
+ * The codes control uses for a space the caller cannot reach
72
+ * (control/src/service/context.js: `space_access_denied` and
73
+ * `space_role_required`; control/src/service/cells.js: `space_not_found`).
74
+ */
75
+ const SPACE_UNREACHABLE_CODES = Object.freeze(["space_access_denied", "space_role_required", "space_not_found"])
76
+
77
+ /**
78
+ * True only for control's own refusal of a space this caller cannot reach.
79
+ * A 5xx, a timeout or a network error is never a space refusal: answering the
80
+ * scoped sentence for one would be the false absence claim this rule exists
81
+ * to prevent.
82
+ */
83
+ export function spaceUnreachable(error) {
84
+ const status = Number(error?.status ?? 0)
85
+ const code = String(error?.code ?? "")
86
+ if (SPACE_UNREACHABLE_CODES.includes(code)) return true
87
+ // Control answers a named space the caller cannot reach with 403 (with or
88
+ // without a code, the eval's control answers a bare 403), and an id it does
89
+ // not know with 404.
90
+ return status === 403 || status === 404
91
+ }
92
+
59
93
  /**
60
94
  * Helpers shared by the memory tool modules. The control plane is the only
61
95
  * source of a space, its placement, and the caller's role.
@@ -97,6 +131,10 @@ export function createToolkit(ctx, runtime) {
97
131
  if (!resolved) return { error: "the control plane returned no space context" }
98
132
  return { context: resolved }
99
133
  } catch (error) {
134
+ // 0.11.3: a named space this caller cannot reach answers with a scoped
135
+ // sentence an agent can quote without over-claiming (fast0112's three
136
+ // H2s), not the control plane's terse refusal.
137
+ if (requested && spaceUnreachable(error)) return { error: unreachableSpace(requested) }
100
138
  return { error: errorMessage(error) }
101
139
  }
102
140
  }
@@ -293,16 +331,33 @@ export function createToolkit(ctx, runtime) {
293
331
  *
294
332
  * @param {any} context the tool call's context
295
333
  * @param {{ action: string, spaceContext?: any, shared?: boolean, pinned?: boolean, resources?: string[], metadata?: object, records?: object[] }} write
296
- * @returns {Promise<{ asked: boolean, held?: string, denied?: string }>}
334
+ * @returns {Promise<{ asked: boolean, held?: string, heldID?: string, heldState?: string, denied?: string }>}
297
335
  */
298
- async function gateWrite(context, { action, spaceContext, shared = false, pinned = false, resources = [], metadata = {}, records } = {}) {
299
- if (!shared && !pinned) return { asked: false }
336
+ async function gateWrite(context, { action, spaceContext, shared = false, pinned = false, ask = null, resources = [], metadata = {}, records } = {}) {
337
+ // `ask` is the tier's own gate (DESIGN-MEMORY-JOBS §12): "unless-skipped"
338
+ // is G1, which the person's skipAsks may lift; "always" is G2, which no
339
+ // setting lifts. Both ask in a personal space too, where `shared` is false.
340
+ if (!shared && !pinned && !ask) return { asked: false }
300
341
  if (shared && config.heldTeamWrites && Array.isArray(records) && records.length > 0) {
301
342
  const held = await asVerifiedSession(context?.sessionID, () => holdTeamWrite(toolkit, context, spaceContext, records))
302
- return { asked: false, held }
343
+ // The held write's sentence, and what its answer's first line says (0.11.3).
344
+ return { asked: false, held: held?.text, heldID: held?.id, heldState: held?.state }
303
345
  }
346
+ const askResources = [spaceContext?.space_id ?? (shared ? "team" : "local"), ...resources]
304
347
  try {
305
- await assertTeamWrite(context, action, [spaceContext?.space_id ?? (shared ? "team" : "local"), ...resources], {
348
+ if (ask === "always") {
349
+ await ctx.permission.assert({
350
+ sessionID: context?.sessionID,
351
+ agent: context?.agent,
352
+ source: { type: "tool", messageID: context?.messageID, id: context?.id },
353
+ action,
354
+ resources: askResources,
355
+ save: [],
356
+ metadata: { ...metadata, visibility: shared ? "team" : "private", ...(spaceContext?.space_id ? { space_id: spaceContext.space_id } : {}) },
357
+ })
358
+ return { asked: true }
359
+ }
360
+ await assertTeamWrite(context, action, askResources, {
306
361
  ...metadata,
307
362
  visibility: shared ? "team" : "private",
308
363
  ...(pinned ? { pinned: "This page is placed in the system prompt of every later session." } : {}),
@@ -403,6 +458,29 @@ export function createToolkit(ctx, runtime) {
403
458
  log,
404
459
  control,
405
460
  runtime,
461
+ /**
462
+ * Whether the host offers this engine the `memory` resource: the
463
+ * resource-token fact (`memoryResourceAvailable()`, resource-token contract
464
+ * §1/§6), which plain OpenCode cannot satisfy. The read-only twins are
465
+ * registered only here (jelly #74); a declared `capabilities` entry
466
+ * replaces this interim in audit step 4.
467
+ */
468
+ readOnlyTwins: memoryResourceAvailable(),
469
+ /**
470
+ * Learn this session's parent once (0.10.7 review R2-6): a session the host
471
+ * has not been asked about yet looks like an unknown child, and an unknown
472
+ * child's prompt is treated as an agent's brief. Asking the host turns an
473
+ * unknown root into a known root; a failure leaves it unknown, which fails
474
+ * closed.
475
+ */
476
+ ensureSession: async (sessionID) => {
477
+ if (!sessionID || runtime.parentOf?.(sessionID) !== undefined) return
478
+ try {
479
+ await readSession(ctx, runtime, sessionID)
480
+ } catch {
481
+ /* an unknown session stays unknown */
482
+ }
483
+ },
406
484
  /** The project's directory: where mem_page export writes `.opencode-mem/exports/`. */
407
485
  directory: typeof ctx?.location?.directory === "string" ? ctx.location.directory : "",
408
486
  scope: runtime.scope,