@joe-broadhead/opencode-mem 0.9.1 → 0.9.5

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.
@@ -0,0 +1,125 @@
1
+ import { dayIn, dueDay, formatDay } from "../records.js"
2
+ import { OVERDUE_CATEGORY, OVERDUE_KEY_PREFIX, OVERDUE_LABEL, OVERDUE_MAX } from "./contracts.js"
3
+ import { clip, idOf } from "./shape.js"
4
+
5
+ /**
6
+ * Overdue commitments, as Inbox items.
7
+ *
8
+ * Memory computes what is overdue from the person's commitments and nothing
9
+ * else: no ledger, no timer, no push. The host's Inbox asks (`inbox.list`),
10
+ * and the answer is a pure function of the records and of today. So the same
11
+ * commitment is one item, whichever process or restart answers and however
12
+ * many days pass:
13
+ *
14
+ * - **Key** `commitment:<id>`: stable while the commitment lives, so the host
15
+ * keeps one item and never stacks them.
16
+ * - **Updated in place each day:** the line carries who owes it, since when and
17
+ * the day count, and `at` is the start of today in the person's zone, so the
18
+ * host shows the same item unread again each day.
19
+ * - **It clears by itself:** a commitment that is closed (done or cancelled),
20
+ * or whose due day has moved to today or later, is not overdue, so the next
21
+ * read leaves it out and the host drops it. A snooze is only a new due date.
22
+ *
23
+ * The rule is the one `commitments.list` shows (`overdue`): open, with a due
24
+ * day before today in the person's zone. A date-time due earlier today is not
25
+ * overdue until tomorrow. A commitment with only a trigger, or no due date, is
26
+ * never overdue.
27
+ *
28
+ * Only the commitment's own title is carried (`what`, one plain line), never
29
+ * its project, link or trigger.
30
+ */
31
+
32
+ /** Whole days from one YYYY-MM-DD to a later one. */
33
+ export function daysBetween(from, to) {
34
+ const at = (day) => {
35
+ const [year, month, date] = day.split("-").map(Number)
36
+ return Date.UTC(year, month - 1, date)
37
+ }
38
+ return Math.round((at(to) - at(from)) / 86_400_000)
39
+ }
40
+
41
+ /** Offset of `zone` from UTC at an instant, in minutes. */
42
+ function offsetMinutes(ms, zone) {
43
+ const parts = Object.fromEntries(
44
+ new Intl.DateTimeFormat("en-CA", {
45
+ timeZone: zone,
46
+ hourCycle: "h23",
47
+ year: "numeric",
48
+ month: "2-digit",
49
+ day: "2-digit",
50
+ hour: "2-digit",
51
+ minute: "2-digit",
52
+ second: "2-digit",
53
+ })
54
+ .formatToParts(new Date(ms))
55
+ .map((part) => [part.type, part.value]),
56
+ )
57
+ const wall = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour), Number(parts.minute), Number(parts.second))
58
+ return Math.round((wall - Math.floor(ms / 1000) * 1000) / 60_000)
59
+ }
60
+
61
+ /**
62
+ * The instant a local day begins in `zone`, as an ISO time in UTC. The same
63
+ * for every read of that day, whichever process makes it.
64
+ */
65
+ export function dayStartIso(day, zone) {
66
+ const [year, month, date] = day.split("-").map(Number)
67
+ const wall = Date.UTC(year, month - 1, date)
68
+ // The offset at midnight depends on the instant, so settle it in two steps.
69
+ let instant = wall - offsetMinutes(wall, zone) * 60_000
70
+ instant = wall - offsetMinutes(instant, zone) * 60_000
71
+ return new Date(instant).toISOString().replace(".000Z", "Z")
72
+ }
73
+
74
+ /** One plain line: no control or format characters, no angle brackets (an Inbox line is read as text). */
75
+ export function oneLinePlain(value, max) {
76
+ return clip(String(value ?? "").replace(/[\p{Cc}\p{Cf}<>]/gu, " ").replace(/\s+/g, " ").trim(), max)
77
+ }
78
+
79
+ /** Who owes it, in words: never the stored "user". */
80
+ export function ownerWords(owner) {
81
+ const name = String(owner ?? "").trim()
82
+ if (!name || name === "user") return "You"
83
+ if (name === "agent") return "An agent"
84
+ return oneLinePlain(name, 30)
85
+ }
86
+
87
+ /**
88
+ * The open commitments whose due day is before today, the most overdue first.
89
+ *
90
+ * @param {Array<{ id?: string, what?: string, owner?: string, state?: string, due?: string }>} items
91
+ * @param {{ today: string, zone: string }} when
92
+ */
93
+ export function overdueCommitments(items, { today, zone }) {
94
+ const found = []
95
+ for (const item of items ?? []) {
96
+ if (item?.state !== "open") continue
97
+ const id = idOf(item.id)
98
+ const day = dueDay(item.due, zone)
99
+ if (!id || !day || day >= today) continue
100
+ found.push({ id, what: item.what, owner: item.owner, day, days: daysBetween(day, today) })
101
+ }
102
+ return found.sort((a, b) => a.day.localeCompare(b.day) || a.id.localeCompare(b.id))
103
+ }
104
+
105
+ /**
106
+ * One Inbox item per overdue commitment.
107
+ *
108
+ * @param {Array<object>} items the person's commitments
109
+ * @param {{ now: number | Date, zone: string, max?: number }} when
110
+ * @returns {Array<{ key: string, category: string, label: string, name: string, line: string, at: string }>}
111
+ */
112
+ export function overdueInboxItems(items, { now, zone, max = OVERDUE_MAX }) {
113
+ const today = dayIn(now, zone)
114
+ const at = dayStartIso(today, zone)
115
+ const out = []
116
+ for (const found of overdueCommitments(items, { today, zone })) {
117
+ const key = `${OVERDUE_KEY_PREFIX}${found.id}`
118
+ if (key.length > 200) continue
119
+ const tail = ` · ${ownerWords(found.owner)} · overdue ${found.days} ${found.days === 1 ? "day" : "days"}, due ${formatDay(found.day)}`
120
+ const title = oneLinePlain(found.what, Math.max(10, 120 - tail.length)) || "A commitment"
121
+ out.push({ key, category: OVERDUE_CATEGORY, label: OVERDUE_LABEL, name: "Memory", line: `${title}${tail}`, at })
122
+ if (out.length >= max) break
123
+ }
124
+ return out
125
+ }
@@ -0,0 +1,155 @@
1
+ import {
2
+ PROFILE_AGENT_CHARS,
3
+ PROFILE_ITEMS_MAX,
4
+ PROFILE_LABEL,
5
+ PROFILE_NOTES_MAX,
6
+ PROFILE_PERSONA_CHARS,
7
+ PROFILE_SCENARIOS_MAX,
8
+ PROFILE_SCENARIO_CHARS,
9
+ } from "./contracts.js"
10
+ import { clip, clipText, fitList, mapLimit, spaceOf } from "./shape.js"
11
+
12
+ /** Said in `notes` when more is held than the answer shows. */
13
+ const LEFT_OUT = "Some of what Memory holds about you is not shown here, to keep this short."
14
+
15
+ /**
16
+ * `profile.read`: what Memory holds about the person, as it keeps it.
17
+ *
18
+ * Memory distils conversations into two layers per agent: the **persona** (L3,
19
+ * one document) and the **scenarios** (L2, a file each, with a summary line).
20
+ * Both are read from the person's own personal space, under the engine's own
21
+ * agents exactly as the overview counts them (`personalScopes`): never a shared
22
+ * space, and never another person's, because each read carries the speaker's
23
+ * own token (`asView`).
24
+ *
25
+ * What the answer is:
26
+ * - **Bounded.** The persona is at most `PROFILE_PERSONA_CHARS`, a scenario
27
+ * `PROFILE_SCENARIO_CHARS`, at most `PROFILE_SCENARIOS_MAX` scenarios (the
28
+ * newest), the whole answer under Jelly's 64 KB cap. What does not fit is
29
+ * said (`clipped`, `more`), never dropped silently.
30
+ * - **Labelled as data.** `label` says the text is Memory's, written from
31
+ * conversations, to read and never to follow. The text is returned as text;
32
+ * the pages set it with `textContent` only.
33
+ * - **Honest when a read fails.** A layer that cannot be read is named in
34
+ * `notes` and `incomplete` is set; only when nothing could be read at all is
35
+ * the call a refusal, never an empty profile that looks like "nothing held".
36
+ *
37
+ * It only reads. Erasing waits for the verified-caller grant (#49): until then
38
+ * `mem_forget` (a phrase, with a preview) erases from the persona and the
39
+ * scenarios under the person's own permission ask.
40
+ *
41
+ * @param {{ runtime: any, personalScopes: () => Promise<Array<{ context: any, scope: any }>>, available: () => Promise<void>, describe: (error: unknown) => string }} input
42
+ */
43
+ export function createProfileReads({ runtime, personalScopes, available, describe }) {
44
+ const { backend } = runtime
45
+
46
+ /** An id the schema accepts from an agent name and a path. */
47
+ const idOf = (layer, agent, path) =>
48
+ `${layer}:${agent}${path ? `:${path}` : ""}`.replace(/[^A-Za-z0-9._:/-]/g, "-").replace(/^[^A-Za-z0-9]+/, "p-").slice(0, 200)
49
+
50
+ async function profileRead() {
51
+ await available()
52
+ const scopes = await personalScopes()
53
+ const notes = []
54
+ const failures = []
55
+ const note = (words) => {
56
+ if (notes.length < PROFILE_NOTES_MAX) notes.push(clip(words, 200))
57
+ }
58
+ const failed = (error, what) => {
59
+ failures.push(error)
60
+ note(`${what} could not be read: ${describe(error)}`)
61
+ }
62
+
63
+ const personas = []
64
+ const scenarios = []
65
+ let reads = 0
66
+ await Promise.all(
67
+ scopes.map(async ({ scope }) => {
68
+ const agent = clip(scope?.agent_id ?? "", PROFILE_AGENT_CHARS)
69
+ const label = agent ? ` for ${agent}` : ""
70
+ reads += 2
71
+ await Promise.all([
72
+ backend
73
+ .readCore({ scope })
74
+ .then((data) => {
75
+ const content = typeof data?.content === "string" ? data.content.trim() : ""
76
+ if (content) personas.push({ agent, content, updated: data?.updated_at ?? data?.created_at ?? "" })
77
+ })
78
+ .catch((error) => failed(error, `The persona${label}`)),
79
+ backend
80
+ .listScenarios({ scope })
81
+ .then((data) => {
82
+ for (const entry of data?.entries ?? []) {
83
+ const path = String(entry?.path ?? "")
84
+ if (path && !path.endsWith("/")) scenarios.push({ scope, agent, path, summary: String(entry.summary ?? ""), updated: String(entry.updated_at ?? "") })
85
+ }
86
+ })
87
+ .catch((error) => failed(error, `The scenario list${label}`)),
88
+ ])
89
+ }),
90
+ )
91
+
92
+ // Every read failed: that is a refusal, not an empty profile.
93
+ if (failures.length === reads) throw failures[0]
94
+
95
+ const newest = scenarios.sort((a, b) => b.updated.localeCompare(a.updated) || a.path.localeCompare(b.path))
96
+ const chosen = newest.slice(0, PROFILE_SCENARIOS_MAX)
97
+ const text = await mapLimit(chosen, 4, async (entry) => {
98
+ try {
99
+ const data = await backend.readScenario({ path: entry.path, scope: entry.scope })
100
+ return { ...entry, content: String(data?.content ?? ""), updated: String(data?.updated_at ?? entry.updated) }
101
+ } catch (error) {
102
+ failed(error, `The scenario ${clip(entry.path, 60)}`)
103
+ return null
104
+ }
105
+ })
106
+
107
+ const items = [
108
+ ...personas.map((persona) => {
109
+ const { text: body, clipped } = clipText(persona.content, PROFILE_PERSONA_CHARS, PROFILE_PERSONA_CHARS * 4)
110
+ return { id: idOf("persona", persona.agent), layer: "persona", agent: persona.agent, path: "persona", summary: "", text: body, clipped, updated: clip(persona.updated, 40) }
111
+ }),
112
+ ...text
113
+ .filter((entry) => entry && entry.content.trim())
114
+ .map((entry) => {
115
+ const { text: body, clipped } = clipText(entry.content.trim(), PROFILE_SCENARIO_CHARS, PROFILE_SCENARIO_CHARS * 4)
116
+ return { id: idOf("scenario", entry.agent, entry.path), layer: "scenario", agent: entry.agent, path: clip(entry.path, 200), summary: clip(entry.summary, 300), text: body, clipped, updated: clip(entry.updated, 40) }
117
+ }),
118
+ ]
119
+ const out = {
120
+ space: spaceOf(scopes[0]?.context ?? null),
121
+ label: PROFILE_LABEL,
122
+ items: [],
123
+ more: newest.length > chosen.length,
124
+ incomplete: failures.length > 0,
125
+ notes,
126
+ }
127
+ const shown = items.slice(0, PROFILE_ITEMS_MAX)
128
+ if (fitList(out, "items", shown) || items.length > shown.length) out.more = true
129
+ if (out.more) note(LEFT_OUT)
130
+ return out
131
+ }
132
+
133
+ return { "profile.read": profileRead }
134
+ }
135
+
136
+ /**
137
+ * The same profile as text, for `mem_spaces` (`profile`): the label first, then
138
+ * each persona and scenario between fences, and the notes. Stored text is data;
139
+ * a closing fence inside it is neutralised so it cannot end the block early.
140
+ *
141
+ * @param {{ label: string, items: Array<any>, more: boolean, incomplete: boolean, notes: string[] }} answer
142
+ */
143
+ export function profileText(answer) {
144
+ const safe = (value) => String(value ?? "").replaceAll("</profile", "<\u200b/profile")
145
+ const lines = ["<profile>", answer.label]
146
+ if (answer.items.length === 0) lines.push("(Memory holds no profile of this person yet.)")
147
+ for (const item of answer.items) {
148
+ const head = item.layer === "persona" ? "persona" : `scenario ${safe(item.path)}${item.summary ? ` (${safe(item.summary)})` : ""}`
149
+ lines.push(`--- ${head}${item.agent ? ` [agent ${safe(item.agent)}]` : ""}${item.updated ? ` ${safe(item.updated)}` : ""}${item.clipped ? " [clipped]" : ""}`, safe(item.text))
150
+ }
151
+ for (const note of answer.notes) lines.push(`Note: ${safe(note)}`)
152
+ if (answer.incomplete) lines.push("Incomplete: a read failed, so this may be less than Memory holds.")
153
+ lines.push("</profile>")
154
+ return lines.join("\n")
155
+ }
@@ -5,21 +5,27 @@ import {
5
5
  FOLDERS_MAX,
6
6
  GRAPH_EDGES_MAX,
7
7
  GRAPH_NODES_MAX,
8
+ HELD_MEMORIES_MAX,
8
9
  HISTORY_MAX,
9
10
  JOURNAL_MAX,
10
11
  JOURNAL_SOURCES_MAX,
11
12
  LINEAGE_MAX,
12
13
  LINKS_MAX,
14
+ LIST_MAX,
13
15
  MEMORY_TEXT_CHARS,
14
16
  PAGES_MAX,
17
+ RECENT_CONCURRENCY,
15
18
  RECENT_MAX_OFFSET,
16
19
  RECENT_PAGE,
20
+ RECENT_SPACES_MAX,
17
21
  RECORDS_OFF,
18
22
  RECORD_BODY_CHARS,
19
23
  REVIEW_MAX,
24
+ SOURCE_CHARS,
25
+ STATUS_CHARS,
20
26
  SUMMARY_CHARS,
21
27
  } from "./contracts.js"
22
- import { SPACE_KINDS, clip, clipText, idOf, jsonBytes, refuse, spaceOf } from "./shape.js"
28
+ import { ANSWER_BYTES, SPACE_KINDS, clip, clipText, fitList, idOf, jsonBytes, mapLimit, refuse, sourceLabel, spaceOf } from "./shape.js"
23
29
 
24
30
  /**
25
31
  * The views' reads of the records service (docs/design/memory-v1-contracts.md
@@ -56,8 +62,6 @@ export const VIEW_RECORDS_METHODS = Object.freeze([
56
62
  "space.stats",
57
63
  ])
58
64
 
59
- /** Each answer is held under this many bytes of JSON, below Jelly's 64 KB cap. */
60
- const ANSWER_BYTES = 56_000
61
65
  /** A journal's body is at most this many bytes, so its sources fit beside it. */
62
66
  const JOURNAL_BODY_BYTES = 36_000
63
67
  /** The newest pages the Pages view's top level counts folders from: three reads of 200. */
@@ -220,20 +224,6 @@ function proposedText(proposal) {
220
224
  return String(proposal?.title ?? "")
221
225
  }
222
226
 
223
- /** Keep adding items while the whole answer stays under the byte cap; whether any were left out. */
224
- function fitList(answer, key, items) {
225
- let fitted = false
226
- for (const item of items) {
227
- answer[key].push(item)
228
- if (jsonBytes(answer) > ANSWER_BYTES) {
229
- answer[key].pop()
230
- fitted = true
231
- break
232
- }
233
- }
234
- return fitted
235
- }
236
-
237
227
  /** The fact a memory record states: its body before "Why:", else its title (as `mem_recall` reads it). */
238
228
  function factOf(record) {
239
229
  const body = String(record?.body ?? "").split(/\n\s*\nWhy:/)[0].trim()
@@ -254,9 +244,11 @@ export function memoriesIn(stats) {
254
244
  }
255
245
 
256
246
  /**
257
- * @param {{ runtime: any, personalScopes: () => Promise<Array<{ context: any }>>, available: () => Promise<void> }} input
247
+ * @param {{ runtime: any, personalScopes: () => Promise<Array<{ context: any }>>, available: () => Promise<void>, describe?: (error: unknown) => string }} input
248
+ * `describe` says a failed read in words (a space that could not be read is
249
+ * reported with them); without it the records failure words, or a plain line.
258
250
  */
259
- export function createRecordsReads({ runtime, personalScopes, available }) {
251
+ export function createRecordsReads({ runtime, personalScopes, available, describe = (error) => recordsFailureWords(error) || "Memory could not answer." }) {
260
252
  /** A records call's options for one of `personalScopes()`'s entries. */
261
253
  const whereOf = (entry) => ({
262
254
  ...(entry?.scope ? { scope: entry.scope } : {}),
@@ -310,10 +302,88 @@ export function createRecordsReads({ runtime, personalScopes, available }) {
310
302
  return refuse("Name a page or a record.")
311
303
  }
312
304
 
305
+ /** The kinds of `stated_by` a row may name. */
306
+ const rowStatedBy = (value) => (["person", "agent", "inferred", "external"].includes(value) ? { stated_by: value } : {})
307
+ const rowSource = (source) => {
308
+ const label = sourceLabel(source)
309
+ return label ? { source: clip(label, SOURCE_CHARS) } : {}
310
+ }
311
+
312
+ /** A memory record as one row of the recent list. */
313
+ function memoryRow(record, space) {
314
+ return {
315
+ id: idOf(record.id),
316
+ text: clip(factOf(record), MEMORY_TEXT_CHARS),
317
+ type: clip(record.type ?? "memory", 40),
318
+ at: clip(record.updated ?? record.created ?? "", 40),
319
+ space,
320
+ status: clip(record.status || "current", STATUS_CHARS),
321
+ ...rowStatedBy(record.stated_by),
322
+ ...rowSource(record.source),
323
+ }
324
+ }
325
+
326
+ /** A proposal that would create a memory, as a row: held for review, not saved as a memory yet. */
327
+ function heldMemoryRow(proposal, space) {
328
+ const payload = proposal?.fields?.payload
329
+ const text = typeof payload?.title === "string" && payload.title.trim() ? payload.title : String(proposal?.title ?? "").replace(/^create:\s*/, "")
330
+ return {
331
+ id: idOf(proposal.id),
332
+ text: clip(text, MEMORY_TEXT_CHARS),
333
+ type: clip(payload?.type ?? "memory", 40),
334
+ at: clip(proposal.created ?? "", 40),
335
+ space,
336
+ status: "proposed",
337
+ ...rowStatedBy(proposal.stated_by),
338
+ ...rowSource(proposal.source),
339
+ }
340
+ }
341
+
342
+ /** Whether a proposal is a memory held for review (not a page, a commitment or a share). */
343
+ const isHeldMemory = (proposal) => proposal?.type === "create" && proposal?.fields?.payload?.kind === "memory" && idOf(proposal?.id) !== ""
344
+
313
345
  /**
314
- * The newest memories of the personal space, newest first: records of kind
315
- * `memory` (current and contested), 50 a page, two pages deep, as 0.8's list
316
- * of atoms was. A memory's text is the fact it states, without its "Why:".
346
+ * The spaces a recent list covers, each checked for this person: their own
347
+ * personal space, then the shared spaces control lists for them, up to
348
+ * `RECENT_SPACES_MAX`. Nothing is read in a space control does not list for
349
+ * the caller (control answers for the speaker's own token, so another
350
+ * person's spaces never appear here), and the gateway checks access again on
351
+ * every read. Another personal space is never read. Spaces past the cap are
352
+ * returned as `skipped`, to be reported, not dropped.
353
+ */
354
+ async function recentTargets(input) {
355
+ if (input?.space !== undefined) return { targets: [await target(input)], skipped: [] }
356
+ const [first] = await personalScopes()
357
+ const own = { where: whereOf(first), space: spaceOf(first?.context ?? null) }
358
+ if (!runtime.control) return { targets: [own], skipped: [] }
359
+ const listed = (await runtime.control.listSpaces({ userId: runtime.config?.user })) ?? []
360
+ const scope = first?.scope
361
+ const others = []
362
+ const seen = new Set([own.space.id])
363
+ for (const space of listed) {
364
+ const spaceId = idOf(space?.space_id)
365
+ if (!spaceId || seen.has(spaceId) || space?.kind === "personal") continue
366
+ seen.add(spaceId)
367
+ others.push({
368
+ where: { ...(scope ? { scope } : {}), space: spaceId },
369
+ space: { id: spaceId, name: clip(space.name || spaceId, 200), kind: SPACE_KINDS.has(space.kind) ? space.kind : "unknown" },
370
+ })
371
+ }
372
+ const room = Math.max(0, RECENT_SPACES_MAX - 1)
373
+ return { targets: [own, ...others.slice(0, room)], skipped: others.slice(room) }
374
+ }
375
+
376
+ /**
377
+ * The newest memories across every space the person can read, newest first:
378
+ * records of kind `memory` (current and contested), and the memories held
379
+ * for review (`status: "proposed"`). 50 a page, two pages deep, as 0.8's
380
+ * list of atoms was. A memory's text is the fact it states, without its
381
+ * "Why:", and each row names its space, who said it and where it came from
382
+ * where the record says.
383
+ *
384
+ * Each space is read on its own: one that cannot be read now is named in
385
+ * `incomplete` with the reason, and the rest are shown. Only when no space
386
+ * could be read is the call a refusal.
317
387
  */
318
388
  async function memoriesRecent(input) {
319
389
  await available()
@@ -321,17 +391,39 @@ export function createRecordsReads({ runtime, personalScopes, available }) {
321
391
  if (typeof offset !== "number" || !Number.isInteger(offset) || offset < 0 || offset > RECENT_MAX_OFFSET || offset % RECENT_PAGE !== 0) {
322
392
  refuse(`offset is a multiple of ${RECENT_PAGE} from 0 to ${RECENT_MAX_OFFSET}`)
323
393
  }
324
- const where = await target({})
325
- const answer = await records("records.list", { kind: "memory", limit: offset + RECENT_PAGE + 1 }, where.where)
326
- const rows = (answer?.records ?? []).filter((record) => idOf(record?.id))
394
+ const { targets, skipped } = await recentTargets(input)
395
+ // The newest `offset + 51` of each space hold the newest of them all.
396
+ const want = offset + RECENT_PAGE + 1
397
+ const results = await mapLimit(targets, RECENT_CONCURRENCY, async (entry) => {
398
+ const row = { id: entry.space.id, name: entry.space.name }
399
+ const [memories, held] = await Promise.allSettled([
400
+ records("records.list", { kind: "memory", limit: want }, entry.where),
401
+ records("review.list", { limit: HELD_MEMORIES_MAX }, entry.where),
402
+ ])
403
+ const rows = []
404
+ if (memories.status === "fulfilled") {
405
+ for (const record of memories.value?.records ?? []) if (idOf(record?.id)) rows.push(memoryRow(record, row))
406
+ }
407
+ if (held.status === "fulfilled") {
408
+ for (const proposal of held.value?.proposals ?? []) if (isHeldMemory(proposal)) rows.push(heldMemoryRow(proposal, row))
409
+ }
410
+ const error = [memories, held].find((read) => read.status === "rejected")?.reason
411
+ if (error) runtime.log?.warn?.(`view memories.recent: a read in space ${entry.space.id} failed`, error)
412
+ return { entry, rows, error, read: memories.status === "fulfilled" || held.status === "fulfilled" }
413
+ })
414
+ const failed = results.filter((result) => result.error !== undefined)
415
+ // Nothing could be read in any space: the first failure is the answer, in its own words.
416
+ if (!results.some((result) => result.read)) throw failed[0].error
417
+ const rows = results.flatMap((result) => result.rows).sort((a, b) => b.at.localeCompare(a.at) || b.id.localeCompare(a.id))
327
418
  return {
328
- space: where.space,
329
- items: rows.slice(offset, offset + RECENT_PAGE).map((record) => ({
330
- id: idOf(record.id),
331
- text: clip(factOf(record), MEMORY_TEXT_CHARS),
332
- type: clip(record.type ?? "memory", 40),
333
- at: clip(record.updated ?? record.created ?? "", 40),
334
- })),
419
+ space: targets[0].space,
420
+ // Every space something was read from; one that failed in part is here and in `incomplete`.
421
+ spaces: results.filter((result) => result.read).map((result) => result.entry.space),
422
+ incomplete: [
423
+ ...failed.map((result) => ({ id: result.entry.space.id, name: result.entry.space.name, reason: clip(describe(result.error), 200) })),
424
+ ...skipped.map((entry) => ({ id: entry.space.id, name: entry.space.name, reason: clip(`Not read: a list covers at most ${RECENT_SPACES_MAX} spaces. Choose this space to see its memories.`, 200) })),
425
+ ].slice(0, LIST_MAX),
426
+ items: rows.slice(offset, offset + RECENT_PAGE),
335
427
  more: offset + RECENT_PAGE <= RECENT_MAX_OFFSET && rows.length > offset + RECENT_PAGE,
336
428
  }
337
429
  }
@@ -436,11 +528,13 @@ export function createRecordsReads({ runtime, personalScopes, available }) {
436
528
  .slice(0, EVIDENCE_MAX)
437
529
  return {
438
530
  id: idOf(proposal.id),
531
+ status: clip(proposal.status || "proposed", STATUS_CHARS),
439
532
  action: clip(fields.action || proposal.type || "", 40),
440
533
  title: clip(proposal.title ?? "", 200),
441
534
  target: clip(fields.target_path || fields.target_id || "", 200),
442
535
  reason: clip(fields.reason ?? "", 300),
443
536
  stated_by: stated,
537
+ ...rowSource(proposal.source),
444
538
  external: stated === "external",
445
539
  evidence,
446
540
  proposed: clipText(proposedText(proposal), 600, 1800).text,
package/src/views/rpc.js CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  VIEW_METHODS,
11
11
  } from "./contracts.js"
12
12
  import { createRecordsReads, recordsFailureWords } from "./records-reads.js"
13
+ import { oneLinePlain, overdueInboxItems } from "./overdue.js"
14
+ import { createProfileReads } from "./profile.js"
13
15
  import { SPACE_KINDS, ViewRefusal, clip, clipText, idOf, refuse, spaceOf } from "./shape.js"
14
16
  import { createHeldInboxDecision } from "./inbox-decision.js"
15
17
 
@@ -70,6 +72,7 @@ const CREDENTIALS = Object.freeze({
70
72
  [SOURCES.identity]: "jelly",
71
73
  [SOURCES.secret]: "key",
72
74
  [SOURCES.option]: "option",
75
+ [SOURCES.connect]: "opencode",
73
76
  })
74
77
 
75
78
  /**
@@ -133,6 +136,8 @@ export function createViewReads({ runtime, agents = async () => [] }) {
133
136
  */
134
137
  async function unavailableNow() {
135
138
  let reason = runtime.unavailable?.() ?? ""
139
+ // A /connect sign-in made since setup (src/connect.js): ask OpenCode once.
140
+ if (reason && (await credentials?.probeSignIn?.())) reason = runtime.unavailable?.() ?? ""
136
141
  if (!reason && inView() && typeof runtime.availability === "function") reason = await runtime.availability()
137
142
  return viewWords(reason)
138
143
  }
@@ -151,7 +156,20 @@ export function createViewReads({ runtime, agents = async () => [] }) {
151
156
  }
152
157
  }
153
158
 
154
- const recordsReads = createRecordsReads({ runtime, personalScopes, available })
159
+ const recordsReads = createRecordsReads({ runtime, personalScopes, available, describe: viewFailureWords })
160
+ const profileReads = createProfileReads({ runtime, personalScopes, available, describe: viewFailureWords })
161
+
162
+ /**
163
+ * The overview of a memory that can't be used now. `state` tells a page which
164
+ * of three things to say: nothing set up (the person has something to do in
165
+ * Settings), a credential memory turned down (the key), or a server that is
166
+ * only not answering (wait and try again, nothing to change).
167
+ */
168
+ function notConnected(reason, base, status = 0) {
169
+ const held = credentialState()
170
+ const state = overviewState({ ...held, address: base.address, status })
171
+ return { connected: false, reason: clip(reason, 400), state, ...held, ...base }
172
+ }
155
173
 
156
174
  async function overview() {
157
175
  const address = originOf(String(config.controlURL ?? "")) || originOf(String(config.baseURL ?? "").replace(/\/core$/, ""))
@@ -162,19 +180,14 @@ export function createViewReads({ runtime, agents = async () => [] }) {
162
180
  ...(address ? { address: clip(address, 300) } : {}),
163
181
  }
164
182
  const reason = await unavailableNow()
165
- if (reason) return { connected: false, reason: clip(reason, 400), ...credentialState(), ...base }
183
+ if (reason) return notConnected(reason, base)
166
184
  let scopes
167
185
  try {
168
186
  scopes = await personalScopes()
169
187
  } catch (error) {
170
188
  runtime.log?.warn?.("view overview failed", error)
171
189
  // Asked of the credential after the request, so a refusal it met shows.
172
- return {
173
- connected: false,
174
- reason: clip(viewFailureWords(error), 400),
175
- ...credentialState(),
176
- ...base,
177
- }
190
+ return notConnected(viewFailureWords(error), base, Number(error?.status) || 0)
178
191
  }
179
192
  // Memories are records from 0.9 (the space's count); conversations,
180
193
  // summaries and the profile are still the core's, per agent.
@@ -335,14 +348,35 @@ export function createViewReads({ runtime, agents = async () => [] }) {
335
348
  }
336
349
  }
337
350
 
351
+ /**
352
+ * What waits for the person, for a host that declares an Inbox (`jelly.inbox`):
353
+ * the personal space's pending proposals (`proposal:<id>`), then one item for
354
+ * each overdue commitment (`commitment:<id>`, `overdue.js`).
355
+ *
356
+ * Memory only answers: the host asks when the person reads the Inbox, so a
357
+ * host without that capability never calls this, nothing is published, and
358
+ * OpenCode keeps its Due list (`mem_commitments`, the pinned block). The host
359
+ * replaces its whole copy with each answer, so a part that cannot be read
360
+ * fails the whole read (the host then keeps what it had) rather than answer a
361
+ * list that would drop items still true.
362
+ */
338
363
  async function inboxList() {
339
- const review = await recordsReads.methods["review.list"]({})
340
- return { items: review.items.flatMap((item) => {
364
+ await available()
365
+ const [review, overdue] = await Promise.all([recordsReads.methods["review.list"]({}), overdueNotices()])
366
+ const proposals = review.items.flatMap((item) => {
341
367
  if (!/^rec_[0-9A-Za-z]{1,64}$/.test(item.id)) return []
342
368
  if (!inboxTime(item.created)) return []
343
- const title = String(item.title).replace(/[\p{Cc}\p{Cf}<>]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 120)
369
+ const title = oneLinePlain(item.title, 120)
344
370
  return [{ key: `proposal:${item.id}`, category: "request", label: "Proposal", name: "Memory", line: title || "A proposal is waiting for review", at: item.created }]
345
- }) }
371
+ })
372
+ return { items: [...proposals, ...overdue] }
373
+ }
374
+
375
+ /** One item for each of the person's overdue commitments: the same rule `commitments.list` marks `overdue`. */
376
+ async function overdueNotices() {
377
+ const [first] = await personalScopes()
378
+ const records = (await runtime.records.read(first.scope)).records
379
+ return overdueInboxItems(records.items, { now: runtime.clock.now(), zone: runtime.clock.zone })
346
380
  }
347
381
 
348
382
  return {
@@ -354,6 +388,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
354
388
  "wiki.pages": wikiPages,
355
389
  "wiki.read": wikiRead,
356
390
  ...recordsReads.methods,
391
+ ...profileReads,
357
392
  }
358
393
  }
359
394
 
@@ -367,6 +402,22 @@ function viewWords(reason) {
367
402
  return reason === UNLINKED_SENTENCE && inView() ? VIEW_UNLINKED_SENTENCE : reason
368
403
  }
369
404
 
405
+ /**
406
+ * Why `memory.overview` is `connected: false`, as the page tells it: "unconfigured"
407
+ * (no credential, no address, or no linked Jelly account), "refused" (a credential
408
+ * memory or Jelly turned down: a refusal code, or a 401 or 403), otherwise
409
+ * "unreachable". Jelly's "unavailable" code is its own outage, not a refusal.
410
+ *
411
+ * @param {{ credential: string, address?: string, refused?: string, status?: number }} facts
412
+ * @returns {"unconfigured" | "refused" | "unreachable"}
413
+ */
414
+ export function overviewState({ credential, address, refused, status }) {
415
+ // Not signed in is nothing set up yet (a Jelly account to link), not a key turned down.
416
+ if (credential === "none" || !address || refused === "not_signed_in") return "unconfigured"
417
+ if ((refused && refused !== "unavailable") || status === 401 || status === 403) return "refused"
418
+ return "unreachable"
419
+ }
420
+
370
421
  /** A failed read in words; a view call's unlinked speaker in the view's words. */
371
422
  function viewFailureWords(error) {
372
423
  if (isUnlinked(error) && inView()) return VIEW_UNLINKED_SENTENCE