@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
@@ -0,0 +1,753 @@
1
+ <!doctype html>
2
+ <html lang="en-GB">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-5dtPKkjegOPG8bawdSzGBjixnIaSCLYcZOUAwbRWFAc=' 'sha256-/0aqZ5aL9ON4+6IAVSSwbjH6b/AakzUoE2N5RwMn9BM=' 'sha256-UFDM8ap4jToks3HZElR/QPTqeB5En3ePptw+BAJf5Dk='; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
6
+ <title>Graph</title>
7
+ <style>
8
+ :root {
9
+ color: var(--jelly-text, CanvasText);
10
+ background: var(--jelly-surface, Canvas);
11
+ font: 14px/1.45 var(--jelly-font, system-ui, sans-serif);
12
+ }
13
+ * { box-sizing: border-box; }
14
+ body { margin: 0; padding: 2px; }
15
+ p { margin: 0; }
16
+ h1 { font-size: 16px; margin: 0 0 4px; overflow-wrap: anywhere; }
17
+ .muted { color: var(--jelly-muted, GrayText); font-size: 12px; }
18
+ .state { font-weight: 600; display: flex; align-items: center; gap: 6px; }
19
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--jelly-accent, Highlight); flex: none; }
20
+ .dot.off { background: transparent; border: 1.5px solid var(--jelly-muted, GrayText); }
21
+ .dot.danger { background: var(--jelly-danger, CanvasText); }
22
+ .bar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin: 0 0 8px; }
23
+ .bar.flat { margin: 0; }
24
+ .grow { flex: 1; min-width: 0; overflow-wrap: anywhere; }
25
+ .button, .chip, select, textarea, input {
26
+ font: inherit; font-size: 12px; color: var(--jelly-text, CanvasText); background: var(--jelly-raised, Canvas);
27
+ border: 1px solid var(--jelly-border, GrayText); border-radius: var(--jelly-radius, 8px);
28
+ }
29
+ .button { padding: 2px 8px; cursor: pointer; white-space: nowrap; }
30
+ .button[aria-pressed="true"] { color: var(--jelly-on-accent, HighlightText); background: var(--jelly-accent, Highlight); border-color: var(--jelly-accent, Highlight); }
31
+ .button.quiet { border-color: transparent; background: transparent; padding-left: 0; }
32
+ select { padding: 2px 4px; }
33
+ textarea { width: 100%; padding: 4px 6px; resize: vertical; }
34
+ .button:focus-visible, .chip:focus-visible, .row:focus-visible, select:focus-visible, textarea:focus-visible, input:focus-visible, summary:focus-visible {
35
+ outline: 2px solid var(--jelly-accent, Highlight); outline-offset: 2px;
36
+ }
37
+ .chip {
38
+ display: inline-block; max-width: 22em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
39
+ vertical-align: bottom; padding: 0 7px; margin: 0 2px; border-radius: 999px; cursor: pointer;
40
+ }
41
+ .chip.event, .chip.turn { border-style: dashed; }
42
+ .badge { display: inline-block; font-size: 11px; font-weight: 600; border: 1px solid var(--jelly-border, GrayText); border-radius: 999px; padding: 0 6px; margin-left: 4px; }
43
+ .badge.warn { border-color: var(--jelly-danger, CanvasText); color: var(--jelly-danger, CanvasText); }
44
+ ul.rows { list-style: none; margin: 0; padding: 0; }
45
+ ul.rows > li { border-top: 1px solid var(--jelly-border, GrayText); }
46
+ ul.rows > li:first-child { border-top: 0; }
47
+ .row {
48
+ display: block; width: 100%; text-align: left; font: inherit; color: var(--jelly-text, CanvasText); background: transparent;
49
+ border: 0; padding: 6px 2px; cursor: pointer; overflow-wrap: anywhere;
50
+ }
51
+ .row > span { display: block; }
52
+ .row .title { font-weight: 600; }
53
+ .md { overflow-wrap: anywhere; }
54
+ .md h2 { font-size: 15px; margin: 12px 0 4px; }
55
+ .md h3 { font-size: 14px; margin: 10px 0 4px; }
56
+ .md h4, .md h5 { font-size: 13px; margin: 8px 0 2px; }
57
+ .md p, .md ul, .md ol, .md pre, .md blockquote { margin: 4px 0; }
58
+ .md ul, .md ol { padding-left: 20px; }
59
+ .md li.nested { margin-left: 16px; }
60
+ .md hr { border: 0; border-top: 1px solid var(--jelly-border, GrayText); margin: 10px 0; }
61
+ .md blockquote, blockquote.quote { margin: 4px 0; padding-left: 8px; border-left: 3px solid var(--jelly-border, GrayText); }
62
+ .md pre { overflow: auto; padding: 6px 8px; background: var(--jelly-raised, Canvas); border: 1px solid var(--jelly-border, GrayText); border-radius: var(--jelly-radius, 8px); }
63
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
64
+ .link { text-decoration: underline; }
65
+ .address { color: var(--jelly-muted, GrayText); overflow-wrap: anywhere; }
66
+ .panel { margin: 8px 0; padding: 8px; border: 1px solid var(--jelly-border, GrayText); border-radius: var(--jelly-radius, 8px); background: var(--jelly-raised, Canvas); }
67
+ .panel:empty { display: none; }
68
+ .panel h2 { font-size: 14px; margin: 0 0 4px; }
69
+ dl.fields { display: grid; grid-template-columns: max-content 1fr; gap: 2px 10px; margin: 6px 0; font-size: 12px; }
70
+ dl.fields dt { color: var(--jelly-muted, GrayText); }
71
+ dl.fields dd { margin: 0; overflow-wrap: anywhere; }
72
+ footer, .section { margin-top: 12px; padding-top: 8px; border-top: 1px solid var(--jelly-border, GrayText); }
73
+ details > summary { cursor: pointer; font-size: 12px; }
74
+ .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
75
+ .proposal { padding: 8px 0; }
76
+ .proposal > * + * { margin-top: 4px; }
77
+ .title { font-weight: 600; }
78
+ #map { display: block; width: 100%; height: auto; margin: 4px 0; background: var(--jelly-surface, Canvas); border: 1px solid var(--jelly-border, GrayText); border-radius: var(--jelly-radius, 8px); }
79
+ .edge { stroke: var(--jelly-border, GrayText); stroke-width: 1.2; }
80
+ .edge.supersedes { stroke-dasharray: 5 3; }
81
+ .edge.source { stroke-dasharray: 1.5 3; }
82
+ .node { cursor: pointer; }
83
+ .node circle { fill: var(--jelly-raised, Canvas); stroke: var(--jelly-text, CanvasText); stroke-width: 1.2; }
84
+ .node.n-memory circle, .node.n-commitment circle, .node.n-proposal circle { fill: var(--jelly-muted, GrayText); }
85
+ .node.n-event circle, .node.n-turn circle { fill: transparent; stroke-dasharray: 1.5 2; }
86
+ .node.n-dangling circle { fill: transparent; stroke: var(--jelly-muted, GrayText); stroke-dasharray: 2 2; }
87
+ .node.n-start circle { fill: var(--jelly-accent, Highlight); stroke: var(--jelly-accent, Highlight); }
88
+ .node text { font-size: 11px; fill: var(--jelly-text, CanvasText); }
89
+ .node:focus { outline: none; }
90
+ .node:focus-visible circle { stroke: var(--jelly-accent, Highlight); stroke-width: 3; }
91
+ fieldset { border: 0; padding: 0; margin: 4px 0; }
92
+ </style>
93
+ </head>
94
+ <body>
95
+ <main id="root" aria-live="polite"><p class="muted">Loading…</p></main>
96
+ <div hidden><svg id="map" viewBox="0 0 640 420" role="group" aria-label="Map of your pages"></svg></div>
97
+ <script>
98
+ // jelly-view.js: a client of Jelly's view bridge. Paste it into the page's own <script>:
99
+ // a sealed page loads no script by URL and is given no global. Call jellyView() as the
100
+ // script starts; it resolves with the client when the app says hello.
101
+ function jellyView() {
102
+ return new Promise((resolve) => {
103
+ addEventListener("message", function hello(event) {
104
+ const said = event.data;
105
+ if (event.source !== parent || said?.v !== 1 || said.kind !== "hello" || !event.ports[0])
106
+ return;
107
+ removeEventListener("message", hello);
108
+ const port = event.ports[0];
109
+ const listeners = new Set();
110
+ const latest = new Map();
111
+ const queue = [];
112
+ let sequence = 0;
113
+ let current;
114
+ const theme = (tokens) => {
115
+ const style = document.documentElement.style;
116
+ for (const [name, value] of Object.entries(tokens))
117
+ if (name === "scheme") style.colorScheme = value;
118
+ else style.setProperty(`--jelly-${name}`, value);
119
+ };
120
+ // The app answers one request at a time, so requests go in turn.
121
+ const next = () => {
122
+ if (current !== undefined || queue.length === 0) return;
123
+ current = queue.shift();
124
+ current.timer = setTimeout(
125
+ () => settle({ ok: false, error: "No answer from the app" }),
126
+ 15000,
127
+ );
128
+ port.postMessage(current.message);
129
+ };
130
+ const settle = (answer) => {
131
+ const done = current;
132
+ current = undefined;
133
+ clearTimeout(done.timer);
134
+ if (answer.ok) done.resolve(answer.value);
135
+ else done.reject(new Error(answer.error));
136
+ next();
137
+ };
138
+ port.onmessage = ({ data }) => {
139
+ if (data?.v !== 1) return;
140
+ if (typeof data.kind !== "string") {
141
+ if (current !== undefined && data.re === current.message.id) settle(data);
142
+ return;
143
+ }
144
+ // A call waiting for the person is answered by `until`, not in 15 s.
145
+ if (data.kind === "rpc.waiting" && data.re === current?.message.id) {
146
+ clearTimeout(current.timer);
147
+ current.timer = setTimeout(
148
+ () => settle({ ok: false, error: "No answer from the app" }),
149
+ Math.max(0, Date.parse(data.until) - Date.now()) + 15000,
150
+ );
151
+ }
152
+ if (data.kind === "theme.changed") theme(data.theme);
153
+ // A wait is news only while it lasts, so a later listener is not told of it.
154
+ if (data.kind !== "rpc.waiting") latest.set(data.kind, data);
155
+ for (const listener of listeners) listener(data);
156
+ };
157
+ port.start();
158
+ theme(said.theme);
159
+ const request = (op, fields = {}) =>
160
+ new Promise((resolve, reject) => {
161
+ queue.push({ resolve, reject, message: { ...fields, v: 1, id: String(++sequence), op } });
162
+ next();
163
+ });
164
+ resolve({
165
+ hello: said,
166
+ // A listener first hears the latest push of each kind that came before it.
167
+ on(listener) {
168
+ for (const push of latest.values()) listener(push);
169
+ listeners.add(listener);
170
+ return () => listeners.delete(listener);
171
+ },
172
+ request,
173
+ data: () => request("data.get"),
174
+ state: () => request("state.get"),
175
+ setState: (revision, data) => request("state.set", { revision, data }),
176
+ call: (method, input = {}) => request("rpc.call", { method, input }),
177
+ openAgent: (prefill) => request("open-agent", prefill === undefined ? {} : { prefill }),
178
+ resize: (height) =>
179
+ request("resize", { height: Math.min(1200, Math.max(1, Math.ceil(height))) }),
180
+ decline: () => request("decline"),
181
+ });
182
+ });
183
+ });
184
+ }
185
+ </script>
186
+ <script>
187
+ // markdown.js: Memory's safe Markdown subset for its view pages. Paste it into the page's own
188
+ // <script>, as jelly-view.js is. It builds elements one by one and sets every word with
189
+ // textContent: no markup is ever parsed, so text from a record, a mail or a page can't run.
190
+ // Headings, paragraphs, lists, quotes, rules, code, bold, italic and links; a link shows its
191
+ // words and its address as text (a sealed page cannot open it). [[target]] and [[target|label]]
192
+ // and the citations [turn msg-…] and [event evt_…] become chips that the page's own hooks make.
193
+ function markdown(source, hooks) {
194
+ const SAFE_SCHEMES = ["http", "https", "mailto"];
195
+ const make = (tag, className, text) => {
196
+ const node = document.createElement(tag);
197
+ if (className) node.className = className;
198
+ if (text !== undefined) node.textContent = text;
199
+ return node;
200
+ };
201
+ const chip = (kind, ref, label) =>
202
+ hooks && typeof hooks.chip === "function" ? hooks.chip(kind, ref, label) : make("span", "chip", label || ref);
203
+ // One token at a time, leftmost first: a link, a citation, code, bold, a Markdown link, an
204
+ // address in angle brackets, italic.
205
+ const INLINE = /\[\[([^\]\n|]{1,300})(?:\|([^\]\n]{1,200}))?\]\]|\[(turn|event) ([^\]\s]{1,200})\]|`([^`\n]{1,500})`|\*\*([^*\n]{1,500})\*\*|\[([^\]\n]{1,300})\]\(((?:[^()\s]|\([^()\s]{0,100}\)){0,500})\)|<([a-z][a-z0-9+.-]{0,20}:[^>\s]{1,500})>|(?:^|(?<=[\s(]))[*_]([^*_\n]{1,500})[*_](?=$|[\s).,;:!?])/g;
206
+ const address = (value) => {
207
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(value);
208
+ return scheme && SAFE_SCHEMES.includes(scheme[1].toLowerCase()) ? value : "";
209
+ };
210
+ function inline(text, depth) {
211
+ const out = [];
212
+ let at = 0;
213
+ INLINE.lastIndex = 0;
214
+ for (let match = INLINE.exec(text); match; match = INLINE.exec(text)) {
215
+ if (match.index > at) out.push(document.createTextNode(text.slice(at, match.index)));
216
+ at = INLINE.lastIndex;
217
+ if (match[1] !== undefined) out.push(chip("record", match[1].trim(), (match[2] || "").trim()));
218
+ else if (match[3] !== undefined) out.push(chip(match[3], match[4], ""));
219
+ else if (match[5] !== undefined) out.push(make("code", "", match[5]));
220
+ else if (match[6] !== undefined) {
221
+ const strong = make("strong");
222
+ strong.append(...(depth < 2 ? inline(match[6], depth + 1) : [document.createTextNode(match[6])]));
223
+ out.push(strong);
224
+ } else if (match[7] !== undefined) {
225
+ const link = make("span", "link", match[7]);
226
+ const safe = address(match[8]);
227
+ out.push(link);
228
+ if (safe && safe !== match[7]) out.push(make("span", "address", ` (${safe})`));
229
+ } else if (match[9] !== undefined) {
230
+ const safe = address(match[9]);
231
+ out.push(make("span", safe ? "address" : "", safe || match[9]));
232
+ } else {
233
+ const em = make("em");
234
+ em.append(...(depth < 2 ? inline(match[10], depth + 1) : [document.createTextNode(match[10])]));
235
+ out.push(em);
236
+ }
237
+ // A nested call moved the shared cursor: put it back.
238
+ INLINE.lastIndex = at;
239
+ }
240
+ if (at < text.length) out.push(document.createTextNode(text.slice(at)));
241
+ return out;
242
+ }
243
+ const blocks = [];
244
+ const lines = String(source ?? "").replace(/\r\n?/g, "\n").split("\n");
245
+ let paragraph = [];
246
+ let list = null;
247
+ const flush = () => {
248
+ if (paragraph.length > 0) {
249
+ const node = make("p");
250
+ node.append(...inline(paragraph.join(" "), 0));
251
+ blocks.push(node);
252
+ paragraph = [];
253
+ }
254
+ };
255
+ const close = () => {
256
+ flush();
257
+ list = null;
258
+ };
259
+ for (let index = 0; index < lines.length; index += 1) {
260
+ const line = lines[index];
261
+ const trimmed = line.trim();
262
+ if (/^(```|~~~)/.test(trimmed)) {
263
+ close();
264
+ const fence = trimmed.slice(0, 3);
265
+ const code = [];
266
+ for (index += 1; index < lines.length && !lines[index].trim().startsWith(fence); index += 1) code.push(lines[index]);
267
+ const pre = make("pre");
268
+ pre.append(make("code", "", code.join("\n")));
269
+ blocks.push(pre);
270
+ continue;
271
+ }
272
+ if (!trimmed) {
273
+ close();
274
+ continue;
275
+ }
276
+ const heading = /^(#{1,6})\s+(.*)$/.exec(trimmed);
277
+ if (heading) {
278
+ close();
279
+ const node = make(`h${Math.min(heading[1].length + 1, 5)}`);
280
+ node.append(...inline(heading[2].replace(/\s+#+$/, ""), 0));
281
+ blocks.push(node);
282
+ continue;
283
+ }
284
+ if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) {
285
+ close();
286
+ blocks.push(make("hr"));
287
+ continue;
288
+ }
289
+ const item = /^(\s*)(?:([-*+])|(\d{1,9})[.)])\s+(.*)$/.exec(line);
290
+ if (item) {
291
+ flush();
292
+ const tag = item[2] ? "ul" : "ol";
293
+ if (!list || list.tagName.toLowerCase() !== tag) {
294
+ list = make(tag);
295
+ blocks.push(list);
296
+ }
297
+ const entry = make("li", item[1].length >= 2 ? "nested" : "");
298
+ entry.append(...inline(item[4], 0));
299
+ list.append(entry);
300
+ continue;
301
+ }
302
+ if (trimmed.startsWith(">")) {
303
+ close();
304
+ const quote = make("blockquote");
305
+ quote.append(...inline(trimmed.replace(/^>\s?/, ""), 0));
306
+ blocks.push(quote);
307
+ continue;
308
+ }
309
+ if (list && /^\s{2,}/.test(line)) {
310
+ list.lastChild.append(document.createTextNode(" "), ...inline(trimmed, 0));
311
+ continue;
312
+ }
313
+ list = null;
314
+ paragraph.push(trimmed);
315
+ }
316
+ close();
317
+ return blocks;
318
+ }
319
+ </script>
320
+ <script>
321
+ const root = document.getElementById("root");
322
+ let view = null;
323
+ // The space a read goes to: a shared space's id, or undefined for the person's own.
324
+ let space;
325
+ let spaceKind = "personal";
326
+
327
+ function el(tag, className, text) {
328
+ const node = document.createElement(tag);
329
+ if (className) node.className = className;
330
+ if (text !== undefined) node.textContent = text;
331
+ return node;
332
+ }
333
+ function button(label, onClick, className = "button") {
334
+ const node = el("button", className, label);
335
+ node.type = "button";
336
+ node.addEventListener("click", onClick);
337
+ return node;
338
+ }
339
+ function state(words, dot) {
340
+ const line = el("p", "state");
341
+ const mark = el("span", `dot ${dot}`);
342
+ mark.setAttribute("aria-hidden", "true");
343
+ line.append(mark, words);
344
+ return line;
345
+ }
346
+ function fit() {
347
+ // The body's own height: the document is at least as tall as the frame, so it never shrinks.
348
+ if (view) view.resize(document.body.getBoundingClientRect().height).catch(() => undefined);
349
+ }
350
+ function show(...nodes) {
351
+ root.replaceChildren(...nodes);
352
+ root.removeAttribute("aria-busy");
353
+ fit();
354
+ }
355
+ function busy() {
356
+ root.setAttribute("aria-busy", "true");
357
+ }
358
+ // A read's input: the page's own fields and the chosen space.
359
+ function input(fields = {}) {
360
+ return space ? { ...fields, space } : fields;
361
+ }
362
+ // What every view says when the server has no records service (src/views/contracts.js).
363
+ const RECORDS_OFF = "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.";
364
+ function failed(what, error, retry) {
365
+ if (error.message === RECORDS_OFF) return show(el("p", "muted", RECORDS_OFF));
366
+ return show(state(what, "danger"), el("p", "muted", error.message), button("Try again", retry));
367
+ }
368
+ function number(value) {
369
+ return Number(value || 0).toLocaleString("en-GB");
370
+ }
371
+ // "Sun 8 Nov" for a day, from YYYY-MM-DD or an ISO time.
372
+ function dayWords(value) {
373
+ const date = new Date(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value);
374
+ if (Number.isNaN(date.getTime())) return value || "";
375
+ return date.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short", timeZone: "UTC" });
376
+ }
377
+ function waiting(push, what) {
378
+ if (push.kind === "rpc.waiting") show(state("Waiting for you", "off"), el("p", "muted", `Allow this in Jelly to see ${what}.`));
379
+ }
380
+
381
+ // The space picker, when the person has more than one space; null otherwise.
382
+ let spaceList = null;
383
+ async function spacePicker(redraw) {
384
+ if (spaceList === null) {
385
+ try {
386
+ spaceList = (await view.call("spaces.list")).spaces;
387
+ } catch {
388
+ spaceList = [];
389
+ }
390
+ }
391
+ if (spaceList.length < 2) return null;
392
+ const label = el("label", "muted", "Space ");
393
+ const select = el("select");
394
+ for (const entry of spaceList) {
395
+ const option = el("option", "", entry.kind === "personal" ? `${entry.name} (yours)` : entry.name);
396
+ option.value = entry.kind === "personal" ? "" : entry.id;
397
+ if ((space ?? "") === option.value) option.selected = true;
398
+ select.append(option);
399
+ }
400
+ select.addEventListener("change", () => {
401
+ space = select.value || undefined;
402
+ spaceKind = space ? spaceList.find((entry) => entry.id === space)?.kind ?? "shared" : "personal";
403
+ redraw();
404
+ });
405
+ label.append(select);
406
+ return label;
407
+ }
408
+
409
+ const RECORD_ID = /^rec_[0-9A-Za-z]{1,64}$/;
410
+ const PAGE_PATH = /^[a-z0-9][a-z0-9-]{0,63}(\/[a-z0-9][a-z0-9-]{0,63}){0,3}$/;
411
+ // The read that names a link's target, or null when it names nothing Memory keeps.
412
+ function recordInput(ref) {
413
+ if (RECORD_ID.test(ref)) return { id: ref };
414
+ if (PAGE_PATH.test(ref)) return { path: ref };
415
+ return null;
416
+ }
417
+ const TYPE_WORDS = {
418
+ person: "Person", project: "Project", team: "Team", topic: "Topic", runbook: "Runbook", glossary: "Glossary",
419
+ journal: "Journal", index: "Dashboard", decision: "Decision", fact: "Fact", preference: "Preference",
420
+ constraint: "Constraint", procedure: "Procedure", commitment: "Commitment",
421
+ };
422
+ // A link chip's words: its label, "record" for a bare record id, else the page's last part.
423
+ function linkWords(ref, label) {
424
+ if (label) return label;
425
+ return RECORD_ID.test(ref) ? "record" : ref.split("/").pop();
426
+ }
427
+ function linkName(ref, label) {
428
+ return RECORD_ID.test(ref) && !label ? `Open the cited record ${ref}` : `Open ${linkWords(ref, label)}`;
429
+ }
430
+ function typeWords(kind, type) {
431
+ const word = TYPE_WORDS[type] || (type ? type.charAt(0).toUpperCase() + type.slice(1) : "Record");
432
+ if (kind === "page" && type !== "journal" && type !== "index") return `${word} page`;
433
+ if (kind === "proposal") return "Proposal";
434
+ return word;
435
+ }
436
+ // A status that is not plain current, in words.
437
+ function statusBadge(status) {
438
+ if (!status || status === "current") return null;
439
+ const words = { superseded: "Replaced", retired: "Retired", contested: "Contested", proposed: "Waiting for review" }[status] || status;
440
+ return el("span", status === "contested" ? "badge warn" : "badge", words);
441
+ }
442
+ function fieldList(fields) {
443
+ if (!fields.length) return null;
444
+ const list = el("dl", "fields");
445
+ for (const field of fields) list.append(el("dt", "", field.name), el("dd", "", field.value));
446
+ return list;
447
+ }
448
+ // A cited source, as the page knows it: an event's source, title and address; a turn's.
449
+ function sourceNote(kind, ref, source) {
450
+ const nodes = [el("h2", "", kind === "event" ? "Cited message" : "Cited conversation")];
451
+ const list = el("dl", "fields");
452
+ const add = (name, value, className) => {
453
+ if (!value) return;
454
+ list.append(el("dt", "", name), el("dd", className || "", value));
455
+ };
456
+ add("From", source ? source.source : "");
457
+ add("Title", source ? source.title : "");
458
+ add("Address", source ? source.url : "", "address");
459
+ add("Id", ref);
460
+ nodes.push(list);
461
+ if (kind === "event") nodes.push(el("p", "muted", "Memory keeps the messages it collects for 30 days, then only the quote and the address."));
462
+ return nodes;
463
+ }
464
+
465
+ // Memory's Graph: the records around one page and how they link, one or two steps out,
466
+ // drawn as a map. The layout is a small force simulation run here, to the end, before
467
+ // anything is drawn: no library and no motion. Choose a node (click, or Tab and Enter) to
468
+ // open it; from there the map can centre on it. The same nodes are listed as text below.
469
+ const map = document.getElementById("map");
470
+ const SVG = map.namespaceURI;
471
+ const WIDTH = 640;
472
+ const HEIGHT = 420;
473
+ const MARGIN = 28;
474
+ const TYPES = [
475
+ ["person", "People"], ["project", "Projects"], ["team", "Teams"], ["topic", "Topics"], ["runbook", "Runbooks"],
476
+ ["decision", "Decisions"], ["journal", "Journal"], ["fact", "Facts"], ["preference", "Preferences"],
477
+ ["constraint", "Constraints"], ["procedure", "Procedures"], ["commitment", "Commitments"],
478
+ ];
479
+ let centre = null;
480
+ let first = null;
481
+ let depth = 1;
482
+ const types = new Set();
483
+
484
+ // Fruchterman and Reingold's layout, deterministic: the same graph is always drawn the same way.
485
+ // Nodes push each other apart, links pull their ends together, a little gravity keeps the map
486
+ // whole, and the step shrinks as it cools. The centre stays in the middle.
487
+ function layout(count, edges, start, width = WIDTH, height = HEIGHT) {
488
+ const k = Math.sqrt((width * height) / Math.max(count, 1)) * 0.6;
489
+ const pos = [];
490
+ for (let i = 0; i < count; i += 1) {
491
+ const angle = (2 * Math.PI * i) / Math.max(count, 1);
492
+ const radius = i === start ? 0 : (Math.min(width, height) / 3) * (0.6 + (i % 4) / 6);
493
+ pos.push({ x: Math.cos(angle) * radius, y: Math.sin(angle) * radius });
494
+ }
495
+ let heat = width / 10;
496
+ for (let step = 0; step < 300; step += 1) {
497
+ const move = pos.map(() => ({ x: 0, y: 0 }));
498
+ for (let i = 0; i < count; i += 1) {
499
+ for (let j = i + 1; j < count; j += 1) {
500
+ const dx = pos[i].x - pos[j].x;
501
+ const dy = pos[i].y - pos[j].y;
502
+ const d = Math.max(Math.hypot(dx, dy), 0.01);
503
+ const force = (k * k) / d;
504
+ move[i].x += (dx / d) * force;
505
+ move[i].y += (dy / d) * force;
506
+ move[j].x -= (dx / d) * force;
507
+ move[j].y -= (dy / d) * force;
508
+ }
509
+ }
510
+ for (const edge of edges) {
511
+ const dx = pos[edge.from].x - pos[edge.to].x;
512
+ const dy = pos[edge.from].y - pos[edge.to].y;
513
+ const d = Math.max(Math.hypot(dx, dy), 0.01);
514
+ const force = (d * d) / k;
515
+ move[edge.from].x -= (dx / d) * force;
516
+ move[edge.from].y -= (dy / d) * force;
517
+ move[edge.to].x += (dx / d) * force;
518
+ move[edge.to].y += (dy / d) * force;
519
+ }
520
+ for (let i = 0; i < count; i += 1) {
521
+ if (i === start) continue;
522
+ move[i].x -= pos[i].x * 0.08 * k / 10;
523
+ move[i].y -= pos[i].y * 0.08 * k / 10;
524
+ const length = Math.hypot(move[i].x, move[i].y);
525
+ if (length > 0) {
526
+ pos[i].x += (move[i].x / length) * Math.min(length, heat);
527
+ pos[i].y += (move[i].y / length) * Math.min(length, heat);
528
+ }
529
+ }
530
+ heat = Math.max(heat * 0.97, 0.5);
531
+ }
532
+ // Fit the drawing to the frame, keeping its proportions, with the centre where it fell.
533
+ const xs = pos.map((point) => point.x);
534
+ const ys = pos.map((point) => point.y);
535
+ const minX = Math.min(...xs, 0);
536
+ const maxX = Math.max(...xs, 0);
537
+ const minY = Math.min(...ys, 0);
538
+ const maxY = Math.max(...ys, 0);
539
+ const scale = Math.min((width - 2 * MARGIN) / Math.max(maxX - minX, 1), (height - 2 * MARGIN) / Math.max(maxY - minY, 1), 3);
540
+ const offsetX = (width - (maxX - minX) * scale) / 2;
541
+ const offsetY = (height - (maxY - minY) * scale) / 2;
542
+ return pos.map((point) => ({ x: offsetX + (point.x - minX) * scale, y: offsetY + (point.y - minY) * scale }));
543
+ }
544
+
545
+ function svg(tag, attributes) {
546
+ const node = document.createElementNS(SVG, tag);
547
+ for (const [name, value] of Object.entries(attributes)) node.setAttribute(name, String(value));
548
+ return node;
549
+ }
550
+
551
+ function nodeWords(node) {
552
+ if (node.dangling) return `${node.path}: no page yet`;
553
+ if (node.kind === "event") return `A cited message, ${node.title}`;
554
+ if (node.kind === "turn") return `A cited conversation, ${node.title}`;
555
+ return `${node.title}, ${typeWords(node.kind, node.type).toLowerCase()}`;
556
+ }
557
+
558
+ async function openNode(node, panel) {
559
+ const close = button("Close", () => {
560
+ panel.replaceChildren();
561
+ fit();
562
+ });
563
+ if (node.kind === "event" || node.kind === "turn") {
564
+ panel.replaceChildren(...sourceNote(node.kind, node.title, null), close);
565
+ close.focus();
566
+ return fit();
567
+ }
568
+ if (node.dangling || (!node.id && !node.path)) {
569
+ panel.replaceChildren(el("p", "muted", `Nothing is written at ${node.path || "this link"} yet.`), close);
570
+ close.focus();
571
+ return fit();
572
+ }
573
+ const read = node.id ? { id: node.id } : { path: node.path };
574
+ panel.replaceChildren(el("p", "muted", "Opening…"));
575
+ fit();
576
+ let record;
577
+ try {
578
+ record = await view.call("pages.read", input(read));
579
+ } catch (error) {
580
+ panel.replaceChildren(el("p", "muted", error.message), close);
581
+ return fit();
582
+ }
583
+ const title = el("h2", "", record.title);
584
+ const badge = statusBadge(record.status);
585
+ if (badge) title.append(badge);
586
+ const body = el("div", "md");
587
+ body.append(...markdown(record.body, {
588
+ chip: (kind, ref, label) => el("span", `chip ${kind}`, kind === "record" ? linkWords(ref, label) : kind === "event" ? "message" : "conversation"),
589
+ }));
590
+ const actions = el("div", "bar");
591
+ actions.append(button("Centre the map here", () => {
592
+ centre = read;
593
+ draw();
594
+ }), close);
595
+ panel.replaceChildren(title, el("p", "muted", [typeWords(record.kind, record.type), record.path].filter(Boolean).join(" · ")), ...[fieldList(record.fields)].filter(Boolean), body, actions);
596
+ actions.firstChild.focus();
597
+ fit();
598
+ }
599
+
600
+ function drawMap(answer, panel) {
601
+ const points = layout(answer.nodes.length, answer.edges, answer.start);
602
+ const lines = svg("g", { class: "edges" });
603
+ for (const edge of answer.edges) {
604
+ const a = points[edge.from];
605
+ const b = points[edge.to];
606
+ lines.append(svg("line", { x1: a.x.toFixed(1), y1: a.y.toFixed(1), x2: b.x.toFixed(1), y2: b.y.toFixed(1), class: `edge ${edge.type}` }));
607
+ }
608
+ const degree = answer.nodes.map(() => 0);
609
+ for (const edge of answer.edges) {
610
+ degree[edge.from] += 1;
611
+ degree[edge.to] += 1;
612
+ }
613
+ const labelled = new Set(answer.nodes.length <= 40
614
+ ? answer.nodes.map((_, index) => index)
615
+ : degree.map((count, index) => [count, index]).sort((a, b) => b[0] - a[0]).slice(0, 30).map(([, index]) => index));
616
+ labelled.add(answer.start);
617
+ const dots = svg("g", { class: "nodes" });
618
+ answer.nodes.forEach((node, index) => {
619
+ const point = points[index];
620
+ const kind = node.dangling ? "dangling" : node.kind || "page";
621
+ const group = svg("g", { class: `node n-${kind}${index === answer.start ? " n-start" : ""}`, tabindex: 0, role: "button", "aria-label": nodeWords(node) });
622
+ const radius = index === answer.start ? 9 : kind === "page" ? 6 : 4.5;
623
+ group.append(svg("circle", { cx: point.x.toFixed(1), cy: point.y.toFixed(1), r: radius }));
624
+ if (labelled.has(index)) {
625
+ const label = svg("text", { x: (point.x + radius + 3).toFixed(1), y: (point.y + 4).toFixed(1) });
626
+ label.textContent = node.title.length > 26 ? `${node.title.slice(0, 25)}…` : node.title;
627
+ group.append(label);
628
+ }
629
+ const title = svg("title", {});
630
+ title.textContent = nodeWords(node);
631
+ group.append(title);
632
+ group.addEventListener("click", () => openNode(node, panel));
633
+ group.addEventListener("keydown", (event) => {
634
+ if (event.key === "Enter" || event.key === " ") {
635
+ event.preventDefault();
636
+ openNode(node, panel);
637
+ }
638
+ });
639
+ dots.append(group);
640
+ });
641
+ map.replaceChildren(lines, dots);
642
+ map.setAttribute("aria-label", `Map of ${answer.nodes.length} records around ${answer.nodes[answer.start]?.title ?? "this page"}`);
643
+ return map;
644
+ }
645
+
646
+ function controls() {
647
+ const bar = el("div", "bar");
648
+ const steps = el("div", "bar flat");
649
+ steps.setAttribute("role", "group");
650
+ steps.setAttribute("aria-label", "How far out");
651
+ for (const value of [1, 2]) {
652
+ const choice = button(value === 1 ? "1 step" : "2 steps", () => {
653
+ depth = value;
654
+ draw();
655
+ });
656
+ choice.setAttribute("aria-pressed", String(depth === value));
657
+ steps.append(choice);
658
+ }
659
+ bar.append(steps);
660
+ if (first && centre && JSON.stringify(first) !== JSON.stringify(centre)) {
661
+ bar.append(button("Back to the start", () => {
662
+ centre = first;
663
+ draw();
664
+ }));
665
+ }
666
+ const filter = el("details");
667
+ filter.append(el("summary", "", types.size ? `Types: ${types.size} chosen` : "Types: all"));
668
+ const boxes = el("fieldset", "bar flat");
669
+ boxes.append(el("legend", "visually-hidden", "Show only these types"));
670
+ for (const [value, words] of TYPES) {
671
+ const label = el("label", "muted");
672
+ const box = el("input");
673
+ box.type = "checkbox";
674
+ box.checked = types.has(value);
675
+ box.addEventListener("change", () => {
676
+ if (box.checked) types.add(value);
677
+ else types.delete(value);
678
+ draw();
679
+ });
680
+ label.append(box, ` ${words}`);
681
+ boxes.append(label);
682
+ }
683
+ filter.append(boxes);
684
+ bar.append(filter);
685
+ return bar;
686
+ }
687
+
688
+ async function firstCentre() {
689
+ const top = await view.call("pages.list", input());
690
+ if (top.pages.some((page) => page.path === "index")) return { path: "index" };
691
+ if (top.pages.length > 0) return { path: top.pages[0].path };
692
+ for (const folder of top.folders.filter((entry) => entry.name !== "journal").concat(top.folders.filter((entry) => entry.name === "journal"))) {
693
+ const inner = await view.call("pages.list", input({ folder: folder.name }));
694
+ if (inner.pages.length > 0) return { path: inner.pages[0].path };
695
+ }
696
+ return null;
697
+ }
698
+
699
+ async function draw() {
700
+ busy();
701
+ const bar = el("div", "bar");
702
+ let answer;
703
+ try {
704
+ if (!centre) {
705
+ centre = await firstCentre();
706
+ first = centre;
707
+ }
708
+ if (!centre) {
709
+ const picker = await spacePicker(restart);
710
+ if (picker) bar.append(picker);
711
+ return show(bar, el("p", "muted", "No pages to map yet. As your agent writes pages and links them, they show here."));
712
+ }
713
+ answer = await view.call("graph.links", input({ ...centre, depth, max: 120, ...(types.size ? { types: [...types] } : {}) }));
714
+ } catch (error) {
715
+ return failed("Couldn't map your pages", error, draw);
716
+ }
717
+ const picker = await spacePicker(restart);
718
+ if (picker) bar.append(picker);
719
+ const panel = el("section", "panel");
720
+ panel.setAttribute("aria-live", "polite");
721
+ const nodes = [bar, controls()];
722
+ if (answer.nodes.length === 0) return show(...nodes, el("p", "muted", "Nothing of these types links here."));
723
+ nodes.push(drawMap(answer, panel), el("p", "muted", "Lines: solid for a link, dashed where one record replaced another, dotted to a cited message."));
724
+ if (answer.truncated) nodes.push(el("p", "muted", "Only the nearest records are shown: centre on one to see further."));
725
+ nodes.push(panel);
726
+ const list = el("details", "section");
727
+ list.append(el("summary", "", `The ${answer.nodes.length} records as a list`));
728
+ const items = el("ul", "rows");
729
+ answer.nodes.forEach((node) => {
730
+ const item = el("li");
731
+ item.append(button(nodeWords(node), () => openNode(node, panel), "button quiet"));
732
+ items.append(item);
733
+ });
734
+ list.append(items);
735
+ nodes.push(list);
736
+ show(...nodes);
737
+ }
738
+
739
+ function restart() {
740
+ centre = null;
741
+ first = null;
742
+ types.clear();
743
+ draw();
744
+ }
745
+
746
+ jellyView().then((client) => {
747
+ view = client;
748
+ view.on((push) => waiting(push, "the map of your pages"));
749
+ draw();
750
+ });
751
+ </script>
752
+ </body>
753
+ </html>