@joe-broadhead/opencode-mem 0.8.5 → 0.9.1

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 (58) hide show
  1. package/CHANGELOG.md +512 -0
  2. package/README.md +127 -61
  3. package/docs/agent-protocol.md +67 -177
  4. package/package.json +1453 -100
  5. package/skills/mem.pages/SKILL.md +146 -0
  6. package/skills/mem.sharing/SKILL.md +91 -0
  7. package/skills/mem.sources/SKILL.md +94 -0
  8. package/skills/mem.usage/SKILL.md +129 -492
  9. package/src/backend/records.js +285 -0
  10. package/src/backend/v3.js +3 -0
  11. package/src/bootstrap.js +49 -45
  12. package/src/call-shapes.js +41 -10
  13. package/src/collector-lock.js +162 -0
  14. package/src/collector-service.js +441 -0
  15. package/src/collector.js +381 -0
  16. package/src/commands.js +3 -3
  17. package/src/config.js +15 -1
  18. package/src/credentials.js +26 -1
  19. package/src/curation.js +1 -1
  20. package/src/permissions.js +87 -10
  21. package/src/protocol.js +29 -20
  22. package/src/recall.js +104 -27
  23. package/src/records-store.js +267 -121
  24. package/src/records.js +63 -11
  25. package/src/runtime.js +23 -14
  26. package/src/skills.js +44 -18
  27. package/src/sources.js +58 -0
  28. package/src/spaces.js +93 -10
  29. package/src/tools/aliases.js +164 -0
  30. package/src/tools/commitments.js +12 -9
  31. package/src/tools/held-write.js +82 -0
  32. package/src/tools/index.js +100 -23
  33. package/src/tools/ingest.js +277 -0
  34. package/src/tools/knowledge.js +6 -1
  35. package/src/tools/memory.js +722 -229
  36. package/src/tools/page.js +423 -0
  37. package/src/tools/recall.js +371 -113
  38. package/src/tools/records-kit.js +142 -0
  39. package/src/tools/share.js +1042 -0
  40. package/src/tools/shared.js +16 -2
  41. package/src/tools/spaces.js +431 -143
  42. package/src/tools/status.js +87 -58
  43. package/src/tools/wiki.js +8 -4
  44. package/src/views/contracts.js +293 -3
  45. package/src/views/inbox-decision.js +59 -0
  46. package/src/views/recall-result.js +12 -0
  47. package/src/views/records-reads.js +675 -0
  48. package/src/views/rpc.js +58 -99
  49. package/src/views/shape.js +61 -0
  50. package/views/commitments.html +4 -0
  51. package/views/graph.html +753 -0
  52. package/views/home.html +11 -5
  53. package/views/journal.html +621 -0
  54. package/views/memory.html +7 -1
  55. package/views/pages.html +636 -0
  56. package/views/recall.html +123 -0
  57. package/views/review.html +406 -0
  58. package/views/today.html +309 -0
@@ -1,65 +1,94 @@
1
- import { describeBootstrap, describeSpool, errorMessage, oneLine } from "../util.js"
1
+ import { describeBootstrap, describeSpool, errorMessage, isPlainObject, oneLine } from "../util.js"
2
+ import { recordsFailure, recordsOf } from "./share.js"
2
3
 
3
4
  /**
4
- * `mem_status`: backend health, active scope, layer counts, skills, and spool.
5
+ * The health report `mem_spaces` (`"action": "health"`) gives, and the
6
+ * deprecated `mem_status` alias with it: backend health, active scope,
7
+ * per-layer counts (L0-L3), skills, knowledge assets, queued captures, then the
8
+ * records service's counts for the space (`space.stats`) and the collector.
5
9
  *
6
- * @param {any} editor
7
10
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
11
+ * @returns {Promise<{ text: string } | { failure: string }>}
8
12
  */
9
- export function registerStatus(editor, toolkit) {
10
- const { text, fail, resolveSpace } = toolkit
13
+ export async function renderHealth(toolkit, input, context) {
14
+ const resolved = await toolkit.resolveSpace(input, context)
15
+ if (resolved.error) return { failure: resolved.error }
16
+ const spaceContext = resolved.context
17
+ let status
18
+ try {
19
+ status = await toolkit.runtime.status({
20
+ sessionID: input?.space ? undefined : context?.sessionID,
21
+ agent: context?.agent,
22
+ context: spaceContext,
23
+ })
24
+ } catch (error) {
25
+ return { failure: errorMessage(error) }
26
+ }
27
+ const lines = [
28
+ `backend: ${status.health}`,
29
+ `scope: ${status.scope}`,
30
+ `capture: ${status.capture}`,
31
+ `credential: ${status.credential}`,
32
+ ]
33
+ if (status.space) {
34
+ const kind = status.spaceKind && status.spaceKind !== "unknown" ? ` [${status.spaceKind}]` : ""
35
+ const name = status.spaceName ? ` ${oneLine(status.spaceName, 120)}` : ""
36
+ lines.splice(2, 0, `space: ${oneLine(status.space, 80)}${kind}${name}`)
37
+ if (status.collection) lines.splice(3, 0, `collection: ${oneLine(status.collection, 120)}`)
38
+ }
39
+ lines.push(
40
+ `L0 conversations: ${status.layers.l0 ?? "?"}`,
41
+ `L1 atoms: ${status.layers.l1 ?? "?"}`,
42
+ `L2 scenarios: ${status.layers.l2 ?? "?"}`,
43
+ `L3 persona: ${status.layers.l3 ? "present" : "empty"}`,
44
+ `skills: ${status.layers.skills ?? "?"}`,
45
+ `source spaces: ${status.sourceSpaces}`,
46
+ `mirrored skills: ${status.mirroredSkills}`,
47
+ `knowledge assets: ${status.layers.knowledge ?? "?"}`,
48
+ `pinned sessions: ${status.pinned}`,
49
+ `bootstrap: ${describeBootstrap(status.bootstrap)}`,
50
+ `spooled captures: ${describeSpool(status.spool)}`,
51
+ )
52
+ lines.push(...(await recordsLines(toolkit, input, context, spaceContext)))
53
+ if (toolkit.collector) lines.push(toolkit.collector.describe())
54
+ return { text: lines.join("\n") }
55
+ }
11
56
 
12
- editor.add({
13
- name: "status",
14
- description:
15
- "Report memory backend health, active scope, per-layer counts (L0-L3), mirrored skills, knowledge assets, and queued captures. Use it when recall returns nothing and you need to know whether the store is empty, extraction has not run yet, or the backend is unreachable.",
16
- input: {
17
- type: "object",
18
- properties: {
19
- space: { type: "string", description: "Optional; no argument is needed. Space id to report on (control plane); defaults to the active space" },
20
- },
21
- additionalProperties: false,
22
- },
23
- options: { namespace: "mem" },
24
- execute: async (input, context) => {
25
- const resolved = await resolveSpace(input, context)
26
- if (resolved.error) return fail(resolved.error)
27
- const spaceContext = resolved.context
28
- try {
29
- const status = await toolkit.runtime.status({
30
- sessionID: input?.space ? undefined : context?.sessionID,
31
- agent: context?.agent,
32
- context: spaceContext,
33
- })
34
- const lines = [
35
- `backend: ${status.health}`,
36
- `scope: ${status.scope}`,
37
- `capture: ${status.capture}`,
38
- `credential: ${status.credential}`,
39
- ]
40
- if (status.space) {
41
- const kind = status.spaceKind && status.spaceKind !== "unknown" ? ` [${status.spaceKind}]` : ""
42
- const name = status.spaceName ? ` ${oneLine(status.spaceName, 120)}` : ""
43
- lines.splice(2, 0, `space: ${oneLine(status.space, 80)}${kind}${name}`)
44
- if (status.collection) lines.splice(3, 0, `collection: ${oneLine(status.collection, 120)}`)
45
- }
46
- lines.push(
47
- `L0 conversations: ${status.layers.l0 ?? "?"}`,
48
- `L1 atoms: ${status.layers.l1 ?? "?"}`,
49
- `L2 scenarios: ${status.layers.l2 ?? "?"}`,
50
- `L3 persona: ${status.layers.l3 ? "present" : "empty"}`,
51
- `skills: ${status.layers.skills ?? "?"}`,
52
- `source spaces: ${status.sourceSpaces}`,
53
- `mirrored skills: ${status.mirroredSkills}`,
54
- `knowledge assets: ${status.layers.knowledge ?? "?"}`,
55
- `pinned sessions: ${status.pinned}`,
56
- `bootstrap: ${describeBootstrap(status.bootstrap)}`,
57
- `spooled captures: ${describeSpool(status.spool)}`,
58
- )
59
- return text(lines.join("\n"))
60
- } catch (error) {
61
- return fail(errorMessage(error))
62
- }
63
- },
64
- })
57
+ /** The records service's counts for the space, or why they are missing. */
58
+ async function recordsLines(toolkit, input, context, spaceContext) {
59
+ const records = recordsOf(toolkit)
60
+ if (!records) return ["records: not available in this plugin build"]
61
+ const where = spaceContext?.space_id ? (input?.space ? { space: spaceContext.space_id } : { sessionID: context?.sessionID, space: spaceContext.space_id }) : { sessionID: context?.sessionID }
62
+ let stats
63
+ try {
64
+ stats = await records.call("space.stats", {}, where)
65
+ } catch (error) {
66
+ return [`records: unavailable (${oneLine(recordsFailure(error), 240)})`]
67
+ }
68
+ // `space.stats` (contract §2.4): `records: {total, by_kind: {kind: {status: n}}}`,
69
+ // `events: {total, by_source}`, `sources: {total, confirmed, pending, enabled}`, `last_runs`.
70
+ const lines = []
71
+ const byKind = isPlainObject(stats?.records?.by_kind) ? stats.records.by_kind : {}
72
+ const kinds = new Map()
73
+ const statuses = new Map()
74
+ for (const [kind, byStatus] of Object.entries(byKind)) {
75
+ for (const [status, count] of Object.entries(isPlainObject(byStatus) ? byStatus : {})) {
76
+ const n = Number(count) || 0
77
+ kinds.set(kind, (kinds.get(kind) ?? 0) + n)
78
+ statuses.set(status, (statuses.get(status) ?? 0) + n)
79
+ }
80
+ }
81
+ const counts = (map) => [...map].map(([key, count]) => `${oneLine(key, 40)} ${count}`).join(", ")
82
+ lines.push(`records: ${counts(kinds) || "none"}`)
83
+ if (statuses.size > 0) lines.push(`records by status: ${counts(statuses)}`)
84
+ if (isPlainObject(stats?.events)) lines.push(`events: ${Number(stats.events.total) || 0}`)
85
+ if (isPlainObject(stats?.sources)) {
86
+ const sources = stats.sources
87
+ lines.push(`sources: ${Number(sources.total) || 0} (${Number(sources.confirmed) || 0} confirmed, ${Number(sources.pending) || 0} pending)`)
88
+ }
89
+ const runs = Array.isArray(stats?.last_runs) ? stats.last_runs : []
90
+ for (const run of runs.slice(0, 5)) {
91
+ lines.push(`routine ${oneLine(run?.routine ?? "?", 20)}: ${oneLine(run?.status ?? "?", 20)} ${oneLine(run?.date ?? run?.ended ?? run?.started ?? "", 40)}${run?.error ? ` (${oneLine(run.error, 120)})` : ""}`)
92
+ }
93
+ return lines
65
94
  }
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
- "Read, search, or write knowledge pages. 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. Keep one knowledge wiki per space, holding flat source files: index.md, log.md, project-<slug>.md, person-<slug>.md (private only), team-<slug>.md, decision-<date>-<slug>.md, runbook-<slug>.md, and glossary.md (no folders: a name with a folder is refused). Use list/search/read for documentation, architecture, ownership, runbooks, a project's status, and call-graph questions; read index.md before creating a page and extend an existing one. Use write to replace a page (one write per page per session) and append for log.md. 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. Where a project stands goes in its page's dated Status section, replaced on update; things to do go in mem_commitments, never as a checklist on a page. 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.",
604
+ "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: {
@@ -625,7 +629,7 @@ export function registerWiki(editor, toolkit) {
625
629
  content: {
626
630
  type: "string",
627
631
  description:
628
- "Markdown for create, write (replaces the file), or append. A project page (project-<slug>.md) is: # Name; Updated YYYY-MM-DD · Owner · Tracker; ## Purpose; ## Status (as of YYYY-MM-DD), replaced on every update; ## Decisions (- YYYY-MM-DD: decision, because why); ## Open questions; ## People; ## Links; ## Log (one line appended per change). No checkboxes: things to do are mem_commitments",
632
+ "Markdown for create, write (replaces the file), or append: a document the person gave you. Person, project, decision and runbook pages go in mem_page; things to do go in mem_commitments",
629
633
  },
630
634
  ingest: {
631
635
  type: "boolean",
@@ -10,8 +10,14 @@
10
10
  * before the plugin sees it, so every method reads under the permission of the
11
11
  * tool that makes the same read: the overview under `mem_status`, the space
12
12
  * list under `mem_spaces`, recent memories under `mem_recall`, the wiki under
13
- * `mem_wiki`, commitments under `mem_commitments`. None of them writes: a write starts as a message the person sends
14
- * (`open-agent`), and the agent's tool runs under the person's rules.
13
+ * `mem_wiki`, commitments under `mem_commitments`, and (0.9) journals, pages,
14
+ * history and the graph under `mem_page`, proposals awaiting review under
15
+ * `mem_spaces` (its `review` action). None of them writes: a write starts as a
16
+ * message the person sends (`open-agent`), and the agent's tool runs under the
17
+ * person's rules. That includes a review decision: Jelly lets a view call only
18
+ * read-only methods (its `viewIssues`, and its host route), and a view call
19
+ * carries no session the plugin could ask `memory.revise` in, so the Review
20
+ * view starts the message and `mem_spaces` (`review`, `decide`) asks.
15
21
  *
16
22
  * The schemas are JSON Schema documents Jelly reads as data, checked on every
17
23
  * call both ways (input and answer), each at most 16 KB. They use no
@@ -38,7 +44,7 @@ export const ID_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$"
38
44
  */
39
45
  export const RECENT_PAGE = 50
40
46
  export const RECENT_MAX_OFFSET = 50
41
- /** Characters of one memory a view is given; the tool reads the rest. */
47
+ /** Characters of one memory (a record of kind `memory`) a view is given; the tool reads the rest. */
42
48
  export const MEMORY_TEXT_CHARS = 600
43
49
  /** Characters of one wiki page a view is given. */
44
50
  export const PAGE_TEXT_CHARS = 48_000
@@ -47,6 +53,39 @@ export const LIST_MAX = 100
47
53
  /** The most commitments one answer lists (the Home card shows fewer). */
48
54
  export const COMMITMENTS_MAX = 100
49
55
 
56
+ /** Journal pages one answer lists, newest first. */
57
+ export const JOURNAL_MAX = 100
58
+ /** Characters of a journal's summary line. */
59
+ export const SUMMARY_CHARS = 300
60
+ /** Characters of a record's body a view is given (journal, page). */
61
+ export const RECORD_BODY_CHARS = 40_000
62
+ /** A journal's sources one answer carries, for its citation chips. */
63
+ export const JOURNAL_SOURCES_MAX = 200
64
+ /** Proposals one Review answer lists. */
65
+ export const REVIEW_MAX = 20
66
+ /** Evidence quotes shown per proposal. */
67
+ export const EVIDENCE_MAX = 3
68
+ /** Pages one Pages answer lists, and the folders it names. */
69
+ export const PAGES_MAX = 150
70
+ export const FOLDERS_MAX = 50
71
+ /** A page's fields, outlinks and backlinks one answer carries. */
72
+ export const FIELDS_MAX = 24
73
+ export const LINKS_MAX = 50
74
+ /** Versions and lineage one history answer lists. */
75
+ export const HISTORY_MAX = 50
76
+ export const LINEAGE_MAX = 20
77
+ /** The graph's caps: nodes (the records service's own cap) and edges. */
78
+ export const GRAPH_NODES_MAX = 200
79
+ export const GRAPH_EDGES_MAX = 600
80
+
81
+ /**
82
+ * What every view says, as one plain line, when the server has no records
83
+ * service (503 `records_unavailable`): memories, commitments, journals, pages
84
+ * and review all live there from 0.9. The pages show it as it is.
85
+ */
86
+ export const RECORDS_OFF =
87
+ "This Memory server has no records service yet, so memories, journals, pages and review can't be shown. Ask whoever runs it to turn it on."
88
+
50
89
  /** The input property a Jelly host of contract v1.5 or later fills with the caller's speaker id. */
51
90
  export const SPEAKER_FIELD = "jellySpeaker"
52
91
 
@@ -95,6 +134,10 @@ const overviewOutput = {
95
134
  /** Capture as this engine runs it now: the declared setting, read at start. */
96
135
  capture: { type: "boolean" },
97
136
  health: { type: "string", enum: ["ok", "unreachable", "unknown"] },
137
+ extraction: { type: "string", enum: ["healthy", "failing", "unknown"] },
138
+ failing_since: line(40),
139
+ /** Whether the records service answers (memories are records from 0.9); "unavailable" says the page shows `RECORDS_OFF`. */
140
+ records: { type: "string", enum: ["ok", "unavailable"] },
98
141
  space,
99
142
  counts: {
100
143
  type: "object",
@@ -242,6 +285,197 @@ const commitmentsOutput = {
242
285
  },
243
286
  }
244
287
 
288
+ /* ---------------------------------------------------------------- records (0.9) */
289
+
290
+ const integer = { type: "integer", minimum: 0 }
291
+ const flag = { type: "boolean" }
292
+ const list = (items, max) => ({ type: "array", maxItems: max, items })
293
+ const object = (properties, required = Object.keys(properties)) => ({
294
+ type: "object",
295
+ additionalProperties: false,
296
+ required,
297
+ properties,
298
+ })
299
+ /** A space the person chose from `spaces.list`; omitted, their personal space. */
300
+ const spaceInput = { space: id }
301
+ const period = { type: "string", enum: ["day", "week", "month"] }
302
+
303
+ const journalListInput = viewInput({ ...spaceInput, period })
304
+
305
+ const journalListOutput = object({
306
+ space,
307
+ items: list(
308
+ object({
309
+ path: id,
310
+ title: line(200),
311
+ period,
312
+ /** The day the page covers, YYYY-MM-DD (a week's Monday, a month's first). */
313
+ date: line(40),
314
+ /** Whether a person edited it: the routine leaves it alone then. */
315
+ edited: flag,
316
+ summary: line(SUMMARY_CHARS),
317
+ updated: line(40),
318
+ }),
319
+ JOURNAL_MAX,
320
+ ),
321
+ more: flag,
322
+ })
323
+
324
+ const journalReadOutput = object(
325
+ {
326
+ space,
327
+ path: id,
328
+ title: line(200),
329
+ period,
330
+ date: line(40),
331
+ edited: flag,
332
+ updated: line(40),
333
+ /** Markdown without its Sources section and footer, which come apart. */
334
+ body: line(RECORD_BODY_CHARS),
335
+ clipped: flag,
336
+ /** The journal's cited sources, for the chips: an event's title and address, a turn's source. */
337
+ sources: list(
338
+ object({
339
+ ref: id,
340
+ kind: { type: "string", enum: ["event", "turn"] },
341
+ source: line(40),
342
+ title: line(160),
343
+ url: line(300),
344
+ }),
345
+ JOURNAL_SOURCES_MAX,
346
+ ),
347
+ footer: object(
348
+ {
349
+ routine: line(40),
350
+ counts: list(object({ source: line(40), count: integer }), 20),
351
+ tokens: integer,
352
+ budget: integer,
353
+ line: line(600),
354
+ },
355
+ ["routine", "counts", "line"],
356
+ ),
357
+ },
358
+ ["space", "path", "title", "period", "date", "edited", "updated", "body", "clipped", "sources", "footer"],
359
+ )
360
+
361
+ const reviewListOutput = object({
362
+ space,
363
+ items: list(
364
+ object(
365
+ {
366
+ id,
367
+ /** create, append, supersede, merge, close_commitment, open_commitment, share. */
368
+ action: line(40),
369
+ title: line(200),
370
+ /** The record or page it changes, when it changes one. */
371
+ target: line(200),
372
+ reason: line(300),
373
+ stated_by: { type: "string", enum: ["person", "agent", "inferred", "external", "unknown"] },
374
+ /** Whether the words came from someone other than the person: the page labels it. */
375
+ external: flag,
376
+ evidence: list(
377
+ object({ kind: { type: "string", enum: ["event", "turn", "record"] }, ref: id, quote: line(300) }),
378
+ EVIDENCE_MAX,
379
+ ),
380
+ /** The text accepting it would apply; the Edit box starts from it. */
381
+ proposed: line(600),
382
+ expires: line(40),
383
+ created: line(40),
384
+ },
385
+ ["id", "action", "title", "target", "reason", "stated_by", "external", "evidence", "proposed", "expires", "created"],
386
+ ),
387
+ REVIEW_MAX,
388
+ ),
389
+ more: flag,
390
+ })
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
+
403
+ const pagesListOutput = object({
404
+ space,
405
+ /** The folder listed, "" for the top. */
406
+ folder: line(64),
407
+ folders: list(object({ name: line(64), count: integer }), FOLDERS_MAX),
408
+ pages: list(object({ path: id, title: line(200), type: line(40), updated: line(40) }), PAGES_MAX),
409
+ more: flag,
410
+ })
411
+
412
+ const pageRef = { ...spaceInput, path: id, id }
413
+
414
+ const pagesReadOutput = object({
415
+ space,
416
+ id,
417
+ path: line(200),
418
+ kind: line(20),
419
+ type: line(40),
420
+ title: line(200),
421
+ status: line(20),
422
+ stated_by: line(20),
423
+ updated: line(40),
424
+ version: integer,
425
+ fields: list(object({ name: line(40), value: line(300) }), FIELDS_MAX),
426
+ body: line(RECORD_BODY_CHARS),
427
+ clipped: flag,
428
+ /** Each `[[link]]` of the body: its target, and the record it names when there is one. */
429
+ outlinks: list(object({ target: line(200), title: line(200), exists: flag }), LINKS_MAX),
430
+ backlinks: list(object({ id, path: line(200), title: line(200), type: line(40) }), LINKS_MAX),
431
+ backlinksMore: flag,
432
+ })
433
+
434
+ const lineageItem = object({ id, title: line(200), status: line(20) })
435
+
436
+ const pagesHistoryOutput = object({
437
+ id,
438
+ versions: list(
439
+ object({ version: integer, updated: line(40), title: line(200), status: line(20), change: line(200) }),
440
+ HISTORY_MAX,
441
+ ),
442
+ supersedes: list(lineageItem, LINEAGE_MAX),
443
+ supersededBy: list(lineageItem, LINEAGE_MAX),
444
+ })
445
+
446
+ const graphInput = viewInput({
447
+ ...pageRef,
448
+ depth: { type: "integer", minimum: 1, maximum: 2 },
449
+ max: { type: "integer", minimum: 10, maximum: GRAPH_NODES_MAX },
450
+ /** Record types to keep (person, project, decision, …); empty keeps every type. */
451
+ types: list(line(40), 20),
452
+ })
453
+
454
+ const graphOutput = object({
455
+ space,
456
+ /** The index in `nodes` of the record the neighbourhood is around. */
457
+ start: integer,
458
+ nodes: list(
459
+ object({
460
+ /** The record id; "" for a dangling link or a cited source. */
461
+ id: line(200),
462
+ path: line(200),
463
+ title: line(80),
464
+ /** memory, page, commitment, proposal; event or turn for a cited source; "" when dangling. */
465
+ kind: line(20),
466
+ type: line(40),
467
+ dangling: flag,
468
+ }),
469
+ GRAPH_NODES_MAX,
470
+ ),
471
+ /** Edges by node index. */
472
+ edges: list(
473
+ object({ from: integer, to: integer, type: { type: "string", enum: ["link", "supersedes", "source"] } }),
474
+ GRAPH_EDGES_MAX,
475
+ ),
476
+ truncated: flag,
477
+ })
478
+
245
479
  /**
246
480
  * The methods, in the order `package.json` declares them.
247
481
  * @type {ReadonlyArray<{ name: string, label: string, permission: string, input: object, output: object }>}
@@ -284,6 +518,62 @@ export const VIEW_METHODS = Object.freeze([
284
518
  input: commitmentsInput,
285
519
  output: commitmentsOutput,
286
520
  },
521
+ {
522
+ name: "journal.list",
523
+ label: "list your journal pages",
524
+ permission: "mem_page",
525
+ input: journalListInput,
526
+ output: journalListOutput,
527
+ },
528
+ {
529
+ name: "journal.read",
530
+ label: "read a journal page",
531
+ permission: "mem_page",
532
+ input: viewInput({ ...spaceInput, path: id }, ["path"]),
533
+ output: journalReadOutput,
534
+ },
535
+ {
536
+ name: "review.list",
537
+ label: "list what waits for your review",
538
+ permission: "mem_spaces",
539
+ input: viewInput(spaceInput),
540
+ output: reviewListOutput,
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
+ },
549
+ {
550
+ name: "pages.list",
551
+ label: "list your pages by folder",
552
+ permission: "mem_page",
553
+ input: viewInput({ ...spaceInput, folder: line(64) }),
554
+ output: pagesListOutput,
555
+ },
556
+ {
557
+ name: "pages.read",
558
+ label: "read a page or memory, with its links",
559
+ permission: "mem_page",
560
+ input: viewInput(pageRef),
561
+ output: pagesReadOutput,
562
+ },
563
+ {
564
+ name: "pages.history",
565
+ label: "read a page's history",
566
+ permission: "mem_page",
567
+ input: viewInput({ ...spaceInput, id }, ["id"]),
568
+ output: pagesHistoryOutput,
569
+ },
570
+ {
571
+ name: "graph.links",
572
+ label: "map the links around a page",
573
+ permission: "mem_page",
574
+ input: graphInput,
575
+ output: graphOutput,
576
+ },
287
577
  ])
288
578
 
289
579
  /** The refusal a page can show in the plugin's own words (`call.error`). */
@@ -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
+ }