@joe-broadhead/opencode-mem 0.11.2 → 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.
@@ -38,6 +38,8 @@
38
38
  * host refuses a page's input that carries it.
39
39
  */
40
40
 
41
+ import { WIKI_ERROR_CHARS, WIKI_STATES } from "../wiki-state.js"
42
+
41
43
  /** A memory, space, wiki or page id as the views pass it back: visible ASCII, bounded. */
42
44
  export const ID_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$"
43
45
  /**
@@ -571,8 +573,16 @@ const wikiListOutput = {
571
573
  items: {
572
574
  type: "object",
573
575
  additionalProperties: false,
574
- required: ["id", "name", "pages"],
575
- properties: { id, name: line(200), pages: { type: "integer", minimum: 0 } },
576
+ required: ["id", "name", "pages", "status"],
577
+ properties: {
578
+ id,
579
+ name: line(200),
580
+ pages: { type: "integer", minimum: 0 },
581
+ /** The state a host shows on the wiki (jelly #89 A1). */
582
+ status: { type: "string", enum: [...WIKI_STATES] },
583
+ /** Why a failed wiki failed, at most 400 characters. */
584
+ error: line(WIKI_ERROR_CHARS),
585
+ },
576
586
  },
577
587
  },
578
588
  },
@@ -593,6 +603,8 @@ const wikiPagesOutput = {
593
603
  properties: { ref: id, title: line(200) },
594
604
  },
595
605
  },
606
+ /** The pages are the last ready set, kept while an ingest runs (jelly #89 A2). */
607
+ stale: { type: "boolean" },
596
608
  },
597
609
  }
598
610
 
@@ -630,6 +642,8 @@ const commitmentsOutput = {
630
642
  state: { type: "string", enum: ["open", "done", "cancelled"] },
631
643
  /** The due day as "Fri 6 Nov" (with a time for a date-time), or "" when undated. */
632
644
  when: line(40),
645
+ /** The due day as an ISO 8601 local date; absent when the commitment waits on a trigger. */
646
+ due: line(40),
633
647
  overdue: { type: "boolean" },
634
648
  dueToday: { type: "boolean" },
635
649
  trigger: line(200),
@@ -653,6 +667,110 @@ const object = (properties, required = Object.keys(properties)) => ({
653
667
  required,
654
668
  properties,
655
669
  })
670
+
671
+ /* ------------------------------------------------------- meetings and handovers (0.11.3) */
672
+
673
+ const MEETINGS_MAX = 100
674
+ const MEETING_TRANSCRIPT_CHARS = 12_000
675
+
676
+ /** One meeting page's row, as `meetings.list` answers it. */
677
+ const meetingRow = object(
678
+ {
679
+ id,
680
+ path: line(300),
681
+ title: line(200),
682
+ /** The meeting's start, ISO 8601. */
683
+ at: line(40),
684
+ /** Its end, when the page names one: a live meeting has none. */
685
+ endsAt: line(40),
686
+ /** The names the page records for the meeting, as strings. */
687
+ people: list(line(200), 50),
688
+ },
689
+ ["id", "path", "title", "at"],
690
+ )
691
+
692
+ const meetingsListOutput = object(
693
+ {
694
+ space,
695
+ items: list(meetingRow, MEETINGS_MAX),
696
+ more: flag,
697
+ cursor: line(CURSOR_CHARS),
698
+ },
699
+ ["space", "items", "more"],
700
+ )
701
+
702
+ const meetingReadOutput = object(
703
+ {
704
+ space,
705
+ ...meetingRow.properties,
706
+ /** The page's own notes. */
707
+ body: line(200_000),
708
+ /** The stored transcript, cut at the declared ceiling. */
709
+ transcript: line(MEETING_TRANSCRIPT_CHARS),
710
+ transcriptMore: flag,
711
+ },
712
+ ["id", "path", "title", "at", "body"],
713
+ )
714
+
715
+ /** A hand-over request addressed to the person. */
716
+ const shareRequestRow = object(
717
+ {
718
+ id,
719
+ state: { type: "string", enum: ["pending", "accepted", "declined"] },
720
+ target: object({ type: { type: "string", enum: ["space", "page"] }, id, label: line(300), space: line(200) }, ["type", "id", "label"]),
721
+ from: object({ user_id: line(200), name: line(200) }, ["user_id"]),
722
+ to: object({ user_id: line(200), name: line(200) }, ["user_id"]),
723
+ at: line(40),
724
+ note: line(300),
725
+ },
726
+ ["id", "state", "target", "from", "to", "at"],
727
+ )
728
+
729
+ const shareRequestsOutput = object({ requests: list(shareRequestRow, 100) })
730
+
731
+ /**
732
+ * The project pages one answer may name (jelly's ask 11). A cap, like the
733
+ * person read's, and past it `more` says so: a space is read in one page of
734
+ * `records.list`'s own ceiling, and the space is named when it holds more.
735
+ */
736
+ export const PROJECTS_MAX = 200
737
+
738
+ const projectsInput = viewInput({
739
+ /** A space from `spaces.list`; omitted, every space the person can read. */
740
+ space: id,
741
+ })
742
+
743
+ const projectsOutput = object({
744
+ /**
745
+ * The project pages the caller can read, by name and then by path: each one
746
+ * the page's own id, its title and path, and the space it lives in. A project
747
+ * another member keeps to themselves is never listed.
748
+ */
749
+ items: list(
750
+ object(
751
+ {
752
+ /** The record's own id, as `records.list` gives it. */
753
+ id,
754
+ /** The page's title: the name a host spells and shows ("Harbour"). */
755
+ name: line(200),
756
+ /** The page's path in its space ("projects/harbour"). */
757
+ path: id,
758
+ /** The space the page lives in. */
759
+ space: rowSpace,
760
+ },
761
+ ["id", "name", "path", "space"],
762
+ ),
763
+ PROJECTS_MAX,
764
+ ),
765
+ /** Whether more project pages are held than this answer lists. */
766
+ more: flag,
767
+ /** A space that could not be read, or was not read, and why: named, never dropped. */
768
+ incomplete: list(
769
+ object({ id, name: line(200), reason: line(200) }, ["id", "name", "reason"]),
770
+ LIST_MAX,
771
+ ),
772
+ })
773
+
656
774
  /** A space the person chose from `spaces.list`; omitted, their personal space. */
657
775
  const spaceInput = { space: id }
658
776
  /** A page's owning person in its space: the record's own owner, named by the space's roster; absent when no one can be named. */
@@ -830,6 +948,8 @@ const reviewListOutput = object({
830
948
  proposed: line(600),
831
949
  expires: line(40),
832
950
  created: line(40),
951
+ /** When it was created, ISO 8601 with milliseconds. */
952
+ at: line(40),
833
953
  /** #55: what accepting it would make, when the payload is a record (a share names none). */
834
954
  payload: object(
835
955
  {
@@ -918,6 +1038,8 @@ const pagesListOutput = object({
918
1038
  title: line(200),
919
1039
  type: line(40),
920
1040
  updated: line(40),
1041
+ /** The last change as an ISO 8601 instant; `updated` stays the display day. */
1042
+ changedAt: line(40),
921
1043
  /** The page's owning person, where the page names one. */
922
1044
  owner: pageOwner,
923
1045
  /** How many pages link to this one, at most `BACKLINKS_MAX`; absent when the count could not be read. */
@@ -1559,6 +1681,34 @@ export const VIEW_METHODS = Object.freeze([
1559
1681
  input: commitmentsInput,
1560
1682
  output: commitmentsOutput,
1561
1683
  },
1684
+ {
1685
+ name: "meetings.list",
1686
+ label: "list your meeting pages",
1687
+ permission: "mem_page",
1688
+ input: viewInput({ ...spaceInput, cursor: line(CURSOR_CHARS) }),
1689
+ output: meetingsListOutput,
1690
+ },
1691
+ {
1692
+ name: "meetings.read",
1693
+ label: "read a meeting page and its transcript",
1694
+ permission: "mem_page",
1695
+ input: viewInput({ ...spaceInput, id }, ["id"]),
1696
+ output: meetingReadOutput,
1697
+ },
1698
+ {
1699
+ name: "share.requests",
1700
+ label: "list the hand-over requests addressed to you",
1701
+ permission: "mem_share",
1702
+ input: viewInput(),
1703
+ output: shareRequestsOutput,
1704
+ },
1705
+ {
1706
+ name: "projects.list",
1707
+ label: "list your project pages",
1708
+ permission: "mem_page",
1709
+ input: projectsInput,
1710
+ output: projectsOutput,
1711
+ },
1562
1712
  {
1563
1713
  name: "journal.list",
1564
1714
  label: "list your journal pages",
@@ -11,6 +11,12 @@ import { idOf, SPACE_KINDS } from "./shape.js"
11
11
  * metadata for the person who made the write, never a second copy of what the
12
12
  * store holds. A call that stored or changed one record answers a receipt; a
13
13
  * call that changed several, or that refused before writing, answers none.
14
+ *
15
+ * 0.11.3 (jelly's #89 ask A4): it carries the write's `state` and its item's
16
+ * `link`, the same two fields the answer's first line carries
17
+ * (`src/views/write-state.js`, docs/write-states.md), so a host draws the
18
+ * receipt card from one place. A receipt is answered only when the call saved
19
+ * or changed one record, so its state is always `stored`.
14
20
  */
15
21
 
16
22
  /** The writes that answer a receipt, in the view's own words. */
@@ -34,6 +40,17 @@ export function writeReceipt(verb, { record, space } = {}) {
34
40
 
35
41
  /** Characters of a receipt's title. */
36
42
  export const RECEIPT_TITLE_CHARS = 200
43
+ /** Characters of a receipt's text: enough for the card, not the whole page. */
44
+ export const RECEIPT_TEXT_CHARS = 2000
45
+
46
+ /** A receipt's place: the item kind the record's own kind names, and its address. */
47
+ function placeOf(record) {
48
+ const id = line(record?.id, 240)
49
+ const kind = line(record?.kind, 20)
50
+ if (kind === "page") return `page:${line(record?.path, 240) || id}`
51
+ if (kind === "commitment") return `commitment:${id}`
52
+ return `memory:${id}`
53
+ }
37
54
 
38
55
  /** One line, at most `max` characters, with no control character left in it. */
39
56
  const line = (value, max) =>
@@ -48,12 +65,16 @@ const line = (value, max) =>
48
65
  * report as saved (no record id, or an action the view does not know).
49
66
  *
50
67
  * @param {{ action?: string, record?: any, space?: { id?: string, name?: string, kind?: string } }} input
51
- * @returns {{ v: 1, action: string, id: string, kind: string, type: string, status: string, space: { id: string, name: string, kind: string }, title: string } | undefined}
68
+ * @returns {{ v: 1, action: string, id: string, kind: string, type: string, status: string, state: string, link: string, space: { id: string, name: string, kind: string }, title: string } | undefined}
52
69
  */
53
70
  export function receiptView({ action, record, space } = {}) {
54
71
  if (!RECEIPT_ACTIONS.includes(action)) return undefined
55
72
  const id = idOf(record?.id)
56
73
  if (!id) return undefined
74
+ const fullText = typeof record?.body === "string" && record.body.trim()
75
+ ? record.body
76
+ : typeof record?.fields?.what === "string" ? record.fields.what : typeof record?.what === "string" ? record.what : ""
77
+ const text = fullText.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, " ").slice(0, RECEIPT_TEXT_CHARS)
57
78
  return {
58
79
  v: 1,
59
80
  action,
@@ -61,12 +82,16 @@ export function receiptView({ action, record, space } = {}) {
61
82
  kind: line(record?.kind, 20),
62
83
  type: line(record?.type, 40),
63
84
  status: line(record?.status, 20),
85
+ // A receipt is a saved record: the same state and place a first line names.
86
+ state: "stored",
87
+ link: placeOf(record),
64
88
  space: {
65
89
  id: idOf(space?.id) || "unknown",
66
90
  name: line(space?.name, 200),
67
91
  kind: SPACE_KINDS.has(space?.kind) ? space.kind : "unknown",
68
92
  },
69
93
  title: line(record?.title, RECEIPT_TITLE_CHARS),
94
+ ...(text ? { text, textMore: fullText.length > RECEIPT_TEXT_CHARS } : {}),
70
95
  }
71
96
  }
72
97
 
@@ -27,6 +27,7 @@ import {
27
27
  OWNER_ID_CHARS,
28
28
  OWNER_NAME_CHARS,
29
29
  PAGES_MAX,
30
+ PROJECTS_MAX,
30
31
  PROPOSAL_SOURCES_MAX,
31
32
  RECENT_CONCURRENCY,
32
33
  RECENT_MAX_OFFSET,
@@ -1115,6 +1116,7 @@ export function createRecordsReads({ runtime, personalScopes, available, describ
1115
1116
  proposed: clipText(proposedText(proposal), 600, 1800).text,
1116
1117
  expires: clip(fields.expires ?? "", 40),
1117
1118
  created: clip(proposal.created ?? "", 40),
1119
+ at: clip(proposal.created ?? "", 40),
1118
1120
  ...(payload ? { payload } : {}),
1119
1121
  }
1120
1122
  }
@@ -1208,11 +1210,19 @@ export function createRecordsReads({ runtime, personalScopes, available, describ
1208
1210
  * `src/tools/held-write.js`), so a host can ask in that session's composer.
1209
1211
  * `review.list` returns the declared items; the Inbox adds the rest.
1210
1212
  */
1211
- async function reviewWith(input) {
1213
+ async function reviewWith(input, { oldest = false } = {}) {
1212
1214
  await available()
1213
1215
  const where = await target(input)
1214
1216
  const answer = await records("review.list", { limit: REVIEW_MAX + 1 }, where.where)
1215
- const proposals = (answer?.proposals ?? []).filter((proposal) => idOf(proposal?.id))
1217
+ // A review queue reads oldest first, ties by id; the Inbox keeps the
1218
+ // service's newest-first order it had (`oldest` false).
1219
+ const proposals = (answer?.proposals ?? [])
1220
+ .filter((proposal) => idOf(proposal?.id))
1221
+ .sort((a, b) =>
1222
+ oldest
1223
+ ? String(a.created ?? "").localeCompare(String(b.created ?? "")) || String(a.id).localeCompare(String(b.id))
1224
+ : 0,
1225
+ )
1216
1226
  const out = { space: where.space, items: [], more: false }
1217
1227
  const fitted = fitList(
1218
1228
  out,
@@ -1228,10 +1238,157 @@ export function createRecordsReads({ runtime, personalScopes, available, describ
1228
1238
  }
1229
1239
 
1230
1240
  async function reviewList(input) {
1231
- const { space, items, more } = await reviewWith(input)
1241
+ const { space, items, more } = await reviewWith(input, { oldest: true })
1232
1242
  return { space, items: items.map((entry) => entry.item), more }
1233
1243
  }
1234
1244
 
1245
+ /** One meeting page's row, from the record the store keeps. */
1246
+ function meetingRowOf(record) {
1247
+ const fields = record?.fields && typeof record.fields === "object" ? record.fields : {}
1248
+ const meeting = fields.meeting && typeof fields.meeting === "object" && !Array.isArray(fields.meeting) ? fields.meeting : {}
1249
+ const at = typeof meeting.startedAt === "string" ? clip(meeting.startedAt, 40) : clip(record?.created ?? record?.updated ?? "", 40)
1250
+ const people = (Array.isArray(fields.attendees) ? fields.attendees : [])
1251
+ .map((entry) => (typeof entry === "string" ? entry : entry?.name))
1252
+ .filter((name) => typeof name === "string" && name.trim())
1253
+ .map((name) => clip(name, 200))
1254
+ .slice(0, 50)
1255
+ return {
1256
+ id: idOf(record?.id),
1257
+ path: clip(record?.path ?? "", 300),
1258
+ title: clip(record?.title ?? record?.path ?? "", 200),
1259
+ at,
1260
+ ...(typeof meeting.endedAt === "string" ? { endsAt: clip(meeting.endedAt, 40) } : {}),
1261
+ ...(people.length ? { people } : {}),
1262
+ }
1263
+ }
1264
+
1265
+ /**
1266
+ * The project pages the caller can read, by name (jelly's ask 11): the
1267
+ * person's own space and every space they can reach, read one space at a
1268
+ * time. Each row is the page's own id, its title, its path and the space it
1269
+ * lives in. `records.list` applies the space's own visibility before it
1270
+ * answers, and a space control does not list for the caller is never read,
1271
+ * so another member's private pages are never named.
1272
+ */
1273
+ async function projectsList(input) {
1274
+ await available()
1275
+ const { targets, skipped } = await recentTargets(input)
1276
+ const results = await mapLimit(targets, RECENT_CONCURRENCY, async (entry) => {
1277
+ const space = { id: entry.space.id, name: entry.space.name }
1278
+ try {
1279
+ const answer = await records("records.list", { kind: "page", type: "project", limit: PROJECTS_MAX }, entry.where)
1280
+ const projects = []
1281
+ for (const record of answer?.records ?? []) {
1282
+ if (record?.type !== "project") continue
1283
+ const id = idOf(record.id)
1284
+ const path = idOf(record.path)
1285
+ if (!id || !path) continue
1286
+ const name = clip(plainLine(record.title || String(path).split("/").pop() || ""), 200)
1287
+ if (name) projects.push({ id, name, path, space })
1288
+ }
1289
+ return { projects, past: Boolean(answer?.cursor) }
1290
+ } catch (error) {
1291
+ runtime.log?.warn?.(`view projects.list: a read in space ${entry.space.id} failed`, error)
1292
+ return { error }
1293
+ }
1294
+ })
1295
+ const failed = results.filter((result) => result.error !== undefined)
1296
+ if (!results.some((result) => Array.isArray(result.projects))) throw failed[0].error
1297
+ const order = new Map(targets.map((entry, index) => [entry.space.id, index]))
1298
+ const projects = results
1299
+ .flatMap((result) => result.projects ?? [])
1300
+ .sort(
1301
+ (a, b) =>
1302
+ a.name.localeCompare(b.name, "en-GB") ||
1303
+ order.get(a.space.id) - order.get(b.space.id) ||
1304
+ a.path.localeCompare(b.path),
1305
+ )
1306
+ const out = {
1307
+ items: [],
1308
+ more: projects.length > PROJECTS_MAX || results.some((result) => result.past === true),
1309
+ incomplete: [
1310
+ ...failed.map((result) => ({ id: result.entry.space.id, name: result.entry.space.name, reason: clip(describe(result.error), 200) })),
1311
+ ...skipped.map((entry) => ({
1312
+ id: entry.space.id,
1313
+ name: entry.space.name,
1314
+ reason: clip(`Not read: a list covers at most ${RECENT_SPACES_MAX} spaces. Choose this space to see its projects.`, 200),
1315
+ })),
1316
+ ].slice(0, LIST_MAX),
1317
+ }
1318
+ const fitted = fitList(out, "items", projects.slice(0, PROJECTS_MAX))
1319
+ if (fitted) out.more = true
1320
+ return out
1321
+ }
1322
+
1323
+ async function meetingsList(input) {
1324
+ await available()
1325
+ const where = await target(input)
1326
+ const cursor = typeof input?.cursor === "string" ? input.cursor.trim() : ""
1327
+ if (cursor && cursor.length > CURSOR_CHARS) refuse("That is not a listing cursor.")
1328
+ const answer = await records("records.list", { kind: "page", type: "meeting", limit: 100, ...(cursor ? { cursor } : {}) }, where.where)
1329
+ const rows = (answer?.records ?? [])
1330
+ .filter((record) => idOf(record?.id) && record.type === "meeting")
1331
+ .map(meetingRowOf)
1332
+ .sort((a, b) => String(b.at).localeCompare(String(a.at)))
1333
+ return { space: where.space, items: rows, more: Boolean(answer?.cursor), ...(answer?.cursor ? { cursor: clip(answer.cursor, CURSOR_CHARS) } : {}) }
1334
+ }
1335
+
1336
+ async function meetingsRead(input) {
1337
+ await available()
1338
+ const where = await target(input)
1339
+ const id = idOf(input?.id)
1340
+ if (!id) refuse("That is not a meeting id.")
1341
+ const answer = await records("records.get", { ids: [id] }, where.where)
1342
+ const record = (answer?.records ?? []).find((entry) => entry?.id === id && entry?.type === "meeting")
1343
+ if (!record) refuse("That meeting isn't in this space.")
1344
+ const fields = record.fields && typeof record.fields === "object" ? record.fields : {}
1345
+ const transcript = typeof fields.transcript === "string" ? clip(fields.transcript, 12_000) : ""
1346
+ return {
1347
+ space: where.space,
1348
+ ...meetingRowOf(record),
1349
+ body: clip(record.body ?? "", 40_000),
1350
+ transcript,
1351
+ transcriptMore: typeof fields.transcript === "string" && fields.transcript.length > 12_000,
1352
+ }
1353
+ }
1354
+
1355
+ /**
1356
+ * The hand-over requests addressed to the caller. Control lists both the
1357
+ * requests a person sent and the ones they received; only the received ones
1358
+ * are this read's subject, so a Share -> Decide page never offers a request
1359
+ * the person cannot answer.
1360
+ */
1361
+ async function shareRequests() {
1362
+ await available()
1363
+ if (!runtime.control || typeof runtime.control.listTransfers !== "function") return { requests: [] }
1364
+ const answer = await runtime.control.listTransfers({ userId: runtime.config?.user })
1365
+ const rows = (Array.isArray(answer?.requests) ? answer.requests : [])
1366
+ .filter((row) => row?.direction === "received" || (!row?.direction && row?.to?.user_id === runtime.config?.user))
1367
+ .filter((row) => idOf(row?.id) || String(row?.id ?? "").trim())
1368
+ .sort((a, b) => {
1369
+ const left = a?.state === "pending" ? 0 : 1
1370
+ const right = b?.state === "pending" ? 0 : 1
1371
+ if (left !== right) return left - right
1372
+ return String(b?.requested_at ?? "").localeCompare(String(a?.requested_at ?? ""))
1373
+ })
1374
+ .slice(0, 100)
1375
+ .map((row) => ({
1376
+ id: String(row?.id ?? "").slice(0, 200),
1377
+ state: ["pending", "accepted", "declined"].includes(row?.state) ? row.state : "pending",
1378
+ target: {
1379
+ type: row?.target?.type === "page" ? "page" : "space",
1380
+ id: clip(row?.target?.id ?? "", 200),
1381
+ label: clip(row?.target?.name || row?.target?.id || "", 300),
1382
+ ...(row?.target?.space ? { space: clip(row.target.space, 200) } : {}),
1383
+ },
1384
+ from: { user_id: clip(row?.from?.user_id ?? "", 200), ...(row?.from?.name ? { name: clip(row.from.name, 200) } : {}) },
1385
+ to: { user_id: clip(row?.to?.user_id ?? "", 200), ...(row?.to?.name ? { name: clip(row.to.name, 200) } : {}) },
1386
+ at: clip(row?.requested_at ?? "", 40),
1387
+ ...(row?.note ? { note: clip(row.note, 300) } : {}),
1388
+ }))
1389
+ return { requests: rows }
1390
+ }
1391
+
1235
1392
  /**
1236
1393
  * A listed page. Its owner is named from the space's roster, which the listing
1237
1394
  * reads once (`memberNames`), so a page of a hundred rows asks control once; a
@@ -1245,6 +1402,7 @@ export function createRecordsReads({ runtime, personalScopes, available, describ
1245
1402
  title: clip(record.title || record.path, 200),
1246
1403
  type: clip(record.type ?? "", 40),
1247
1404
  updated: clip(record.updated ?? "", 40),
1405
+ ...(/^\d{4}-\d{2}-\d{2}T/.test(String(record.updated ?? "")) ? { changedAt: clip(record.updated, 40) } : {}),
1248
1406
  ...(member ? { owner: { id: clip(member.id, OWNER_ID_CHARS), name: clip(member.name, OWNER_NAME_CHARS) } } : {}),
1249
1407
  }
1250
1408
  }
@@ -1595,6 +1753,10 @@ export function createRecordsReads({ runtime, personalScopes, available, describ
1595
1753
  "journal.list": journalList,
1596
1754
  "journal.read": journalRead,
1597
1755
  "review.list": reviewList,
1756
+ "projects.list": projectsList,
1757
+ "meetings.list": meetingsList,
1758
+ "meetings.read": meetingsRead,
1759
+ "share.requests": shareRequests,
1598
1760
  "pages.list": pagesList,
1599
1761
  "pages.read": pagesRead,
1600
1762
  "pages.history": pagesHistory,
package/src/views/rpc.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { UNLINKED_SENTENCE, asView, inView, isUnlinked, originOf, PACKAGE_NAME, SOURCES, unavailableReason } from "../credentials.js"
2
2
  import { dayIn, dueDay, filterItems, formatDay, formatDue } from "../records.js"
3
3
  import { isRecordsWikiName } from "../tools/knowledge.js"
4
+ import { wikiCache, wikiErrorOf, wikiStateOf } from "../wiki-state.js"
4
5
  import {
5
6
  COMMITMENTS_MAX,
6
7
  INBOX_ITEM_MEETING,
@@ -342,6 +343,9 @@ export function createViewReads({ runtime, agents = async () => [], operations =
342
343
  return first.context ? runtime.sharedScope({ context: first.context }) : runtime.sharedScope()
343
344
  }
344
345
 
346
+ /** The last ready page set of each wiki, across an ingest (jelly #89 A2). */
347
+ const pageCache = wikiCache({ stateDir: config.stateDir, log: runtime.log })
348
+
345
349
  async function wikiList() {
346
350
  await available()
347
351
  const scope = await knowledgeScope()
@@ -351,42 +355,55 @@ export function createViewReads({ runtime, agents = async () => [], operations =
351
355
  // The records wiki is commitments' store, shown by commitments.list.
352
356
  .filter((item) => idOf(item?.wiki_id) && !isRecordsWikiName(item?.name))
353
357
  .slice(0, LIST_MAX)
354
- .map((item) => ({
355
- id: idOf(item.wiki_id),
356
- name: clip(item.name || item.wiki_id, 200),
357
- pages: Math.max(0, Math.floor(Number(item.page_count) || 0)),
358
- })),
358
+ .map((item) => {
359
+ // The state a host can show (jelly #89 A1): ready, processing, or
360
+ // failed with the reason, at most 400 characters.
361
+ const error = wikiErrorOf(item, pageCache.error(item.wiki_id))
362
+ return {
363
+ id: idOf(item.wiki_id),
364
+ name: clip(item.name || item.wiki_id, 200),
365
+ pages: Math.max(0, Math.floor(Number(item.page_count) || 0)),
366
+ status: wikiStateOf(item),
367
+ ...(error ? { error } : {}),
368
+ }
369
+ }),
359
370
  }
360
371
  }
361
372
 
362
- /** A wiki the caller can list, or a refusal: a view names only what it was shown. */
373
+ /** A wiki the caller can list, and its hub item, or a refusal: a view names only what it was shown. */
363
374
  async function visibleWiki(scope, value) {
364
375
  const wiki = idOf(value)
365
376
  if (!wiki) refuse("That is not a wiki id.")
366
377
  const data = await backend.listWiki({ scope })
367
- if (!(data?.items ?? []).some((item) => item?.wiki_id === wiki && !isRecordsWikiName(item?.name))) {
368
- refuse("That wiki isn't in your memory.")
369
- }
370
- return wiki
378
+ const item = (data?.items ?? []).find((entry) => entry?.wiki_id === wiki && !isRecordsWikiName(entry?.name))
379
+ if (!item) refuse("That wiki isn't in your memory.")
380
+ return { wiki, item }
371
381
  }
372
382
 
373
383
  async function wikiPages(input) {
374
384
  await available()
375
385
  const scope = await knowledgeScope()
376
- const wiki = await visibleWiki(scope, input?.wiki)
386
+ const { wiki, item } = await visibleWiki(scope, input?.wiki)
387
+ const state = wikiStateOf(item)
377
388
  const data = await backend.listWikiPages({ scope, wikiID: wiki })
378
- return {
379
- pages: (data?.items ?? [])
380
- .map((item) => ({ ref: idOf(item?.path ?? item?.id), title: clip(item?.title || item?.path || item?.id, 200) }))
381
- .filter((page) => page.ref)
382
- .slice(0, LIST_MAX),
389
+ const listed = (data?.items ?? [])
390
+ .map((entry) => ({ ref: idOf(entry?.path ?? entry?.id), title: clip(entry?.title || entry?.path || entry?.id, 200) }))
391
+ .filter((page) => page.ref)
392
+ .slice(0, LIST_MAX)
393
+ if (state === "ready" && listed.length > 0) pageCache.rememberPages(wiki, listed)
394
+ // The hub lists no pages while a wiki ingests; the last ready set is
395
+ // listed instead, marked stale, so the person's pages never vanish (A2).
396
+ if (listed.length === 0 && state !== "ready") {
397
+ const stale = pageCache.pages(wiki)
398
+ if (stale.length > 0) return { pages: stale, stale: true }
383
399
  }
400
+ return { pages: listed }
384
401
  }
385
402
 
386
403
  async function wikiRead(input) {
387
404
  await available()
388
405
  const scope = await knowledgeScope()
389
- const wiki = await visibleWiki(scope, input?.wiki)
406
+ const { wiki } = await visibleWiki(scope, input?.wiki)
390
407
  const ref = idOf(input?.ref)
391
408
  if (!ref) refuse("That is not a page.")
392
409
  const data = await backend.readWikiPage({ scope, wikiID: wiki, refs: [ref] })
@@ -425,6 +442,7 @@ export function createViewReads({ runtime, agents = async () => [], operations =
425
442
  owner: clip(item.owner || "user", 80),
426
443
  state: ["open", "done", "cancelled"].includes(item.state) ? item.state : "open",
427
444
  when: clip(item.due ? formatDue(item.due, zone) : "", 40),
445
+ ...(day ? { due: clip(day, 40) } : {}),
428
446
  overdue: item.state === "open" && Boolean(day) && day < today,
429
447
  dueToday: item.state === "open" && day === today,
430
448
  ...(item.trigger ? { trigger: clip(item.trigger, 200) } : {}),
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The first line of every write's answer (0.11.3, jelly's #89 ask A4): the
3
+ * state a host and an agent can quote, the written item's id, and its place,
4
+ * as `state: stored · id: rec_… · link: page:projects/harbour`. The prose the
5
+ * answer carried before follows on the next line, unchanged, so nothing a host
6
+ * or a test parsed in 0.11.2 changes.
7
+ *
8
+ * `state` is the state of the item after the call, never of the call:
9
+ * - `stored`: the item is saved in its store and readable now;
10
+ * - `held`: nothing is saved; it waits for the person in the Inbox, and `id`
11
+ * names the proposal;
12
+ * - `processing`: the item is saved, and an ingest it started is making search
13
+ * and the pages derived from it current;
14
+ * - `queued`: nothing is saved yet; the wiki is ingesting an earlier write, and
15
+ * this write is written when that ingest finishes;
16
+ * - `ready`: the change is complete and there is no item to open (a delete);
17
+ * - `failed`: the call did not finish cleanly; the prose says whether the item
18
+ * was saved and what failed;
19
+ * - `refused`: nothing was written. A refusal names no id and no place.
20
+ *
21
+ * `link` is the item's place, one of `memory:<id>`, `commitment:<id>`,
22
+ * `page:<path>` or `wiki:<wiki id>/<filename>` (a wiki document has no id of
23
+ * its own, so its place is also its id). The format is documented once, in
24
+ * docs/write-states.md.
25
+ */
26
+
27
+ /** The seven states a write answers, in the order the doc lists them. */
28
+ export const WRITE_STATES = Object.freeze(["stored", "held", "processing", "queued", "ready", "failed", "refused"])
29
+
30
+ /** What a host splits the first line on. */
31
+ export const WRITE_STATE_SEPARATOR = " · "
32
+
33
+ /** The longest id and place a first line carries, so one field cannot flood an answer. */
34
+ export const WRITE_STATE_ID_CHARS = 240
35
+ export const WRITE_STATE_LINK_CHARS = 300
36
+
37
+ const one = (value, max) =>
38
+ String(value ?? "")
39
+ .replace(/[\u0000-\u001f\u007f]/g, " ")
40
+ .replace(/\s+/g, " ")
41
+ .trim()
42
+ .slice(0, max)
43
+
44
+ /** A memory's place: its record id. */
45
+ export const memoryPlace = (id) => `memory:${one(id, WRITE_STATE_ID_CHARS)}`
46
+
47
+ /** A commitment's place: its record id (`cmt_…` while it is filed under the wiki). */
48
+ export const commitmentPlace = (id) => `commitment:${one(id, WRITE_STATE_ID_CHARS)}`
49
+
50
+ /** A page's place: its path. */
51
+ export const pagePlace = (path) => `page:${one(path, WRITE_STATE_ID_CHARS)}`
52
+
53
+ /** A wiki document's place: its wiki and its source file. */
54
+ export const wikiPlace = (wikiID, filename) => `wiki:${one(wikiID, 80)}/${one(filename, 160)}`
55
+
56
+ /**
57
+ * The first line, without a newline: `state: refused`, or
58
+ * `state: held · id: rec_… · link: page:projects/harbour`. `id` and `link`
59
+ * come together, and a refusal carries neither.
60
+ *
61
+ * @param {{ state: string, id?: string, link?: string }} write
62
+ * @returns {string}
63
+ */
64
+ export function writeStateLine({ state, id, link } = {}) {
65
+ if (!WRITE_STATES.includes(state)) throw new Error(`a write answers one of ${WRITE_STATES.join(", ")}; got ${JSON.stringify(state)}`)
66
+ const parts = [`state: ${state}`]
67
+ if (state !== "refused" && id) {
68
+ parts.push(`id: ${one(id, WRITE_STATE_ID_CHARS)}`)
69
+ if (link) parts.push(`link: ${one(link, WRITE_STATE_LINK_CHARS)}`)
70
+ }
71
+ return parts.join(WRITE_STATE_SEPARATOR)
72
+ }
73
+
74
+ /**
75
+ * A tool result with the write's first line above its prose, or the result
76
+ * exactly as it is when the call wrote nothing and names nothing.
77
+ *
78
+ * @param {{ content: string }} result
79
+ * @param {{ state: string, id?: string, link?: string }} write
80
+ */
81
+ export function withWriteState(result, write) {
82
+ return { ...result, content: `${writeStateLine(write)}\n${result?.content ?? ""}` }
83
+ }
84
+
85
+ /** A result that wrote nothing. */
86
+ export const refusedAnswer = (result) => withWriteState(result, { state: "refused" })
87
+
88
+ /** A result whose call did not finish cleanly. */
89
+ export const failedAnswer = (result) => withWriteState(result, { state: "failed" })