@joe-broadhead/opencode-mem 0.9.5 → 0.9.12

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 (53) hide show
  1. package/CHANGELOG.md +1281 -0
  2. package/README.md +105 -31
  3. package/docs/agent-protocol.md +28 -27
  4. package/docs/permissions.md +148 -0
  5. package/package.json +24 -12
  6. package/skills/mem.pages/SKILL.md +35 -16
  7. package/skills/mem.sharing/SKILL.md +39 -6
  8. package/skills/mem.sources/SKILL.md +41 -10
  9. package/skills/mem.usage/SKILL.md +37 -16
  10. package/src/backend/records.js +8 -0
  11. package/src/backend/v3.js +15 -10
  12. package/src/call-shapes.js +18 -25
  13. package/src/capture-pause.js +136 -0
  14. package/src/capture.js +7 -5
  15. package/src/collector-service.js +212 -35
  16. package/src/collector.js +186 -47
  17. package/src/commands.js +37 -0
  18. package/src/compaction.js +4 -2
  19. package/src/config.js +151 -1
  20. package/src/curation.js +6 -10
  21. package/src/events.js +144 -36
  22. package/src/forget-purge.js +377 -0
  23. package/src/forgotten.js +152 -0
  24. package/src/hooks.js +9 -4
  25. package/src/index.js +5 -3
  26. package/src/permissions.js +116 -38
  27. package/src/protocol.js +21 -11
  28. package/src/records.js +4 -1
  29. package/src/runtime.js +202 -15
  30. package/src/shapes.js +63 -0
  31. package/src/sources.js +183 -12
  32. package/src/spaces.js +58 -1
  33. package/src/spool.js +442 -64
  34. package/src/stated.js +334 -0
  35. package/src/storable.js +477 -0
  36. package/src/tools/aliases.js +36 -147
  37. package/src/tools/commitments.js +69 -12
  38. package/src/tools/index.js +25 -43
  39. package/src/tools/ingest.js +33 -128
  40. package/src/tools/memory.js +503 -904
  41. package/src/tools/page-sections.js +147 -0
  42. package/src/tools/page.js +314 -82
  43. package/src/tools/recall-browse.js +173 -0
  44. package/src/tools/recall.js +36 -8
  45. package/src/tools/share.js +494 -131
  46. package/src/tools/shared.js +97 -19
  47. package/src/tools/spaces.js +194 -101
  48. package/src/tools/status.js +31 -3
  49. package/src/tools/wiki.js +5 -13
  50. package/src/util.js +10 -59
  51. package/src/views/profile.js +2 -3
  52. package/src/views/records-reads.js +6 -1
  53. package/src/erase.js +0 -36
package/src/stated.js ADDED
@@ -0,0 +1,334 @@
1
+ /**
2
+ * What the person said in a session, for the checks that keep a write to what
3
+ * they said (0.9.9, WRITES-099). The 0.9.8 gate found commitments stored with a
4
+ * due date nobody gave ("next week" became 2026-11-20, or a date came from a
5
+ * recalled note): `mem_commitments` now keeps a `due` or a `trigger` only when
6
+ * the person's own messages in the session name it.
7
+ *
8
+ * The plugin sees each user message once, at admission (the `prompt` hook and
9
+ * the admission events), so it keeps the last few per session, bounded. A
10
+ * subagent's prompt is the parent agent's brief, not the person's words, so a
11
+ * known subagent session is checked against its root session's messages.
12
+ *
13
+ * The date check is deliberately literal: a date counts only when a message
14
+ * names that day (an ISO date, a day and month, a weekday, today, tomorrow,
15
+ * "in 3 days", the end of the week or month). "Next week" names no day.
16
+ */
17
+
18
+ /** Messages kept per session, newest last. */
19
+ const MESSAGES_PER_SESSION = 8
20
+ /** Sessions kept; the oldest is dropped first. */
21
+ const SESSIONS_MAX = 500
22
+ /** Characters kept per message: enough for any date or trigger in it. */
23
+ const MESSAGE_CHARS = 4_000
24
+
25
+ const DAY_MS = 86_400_000
26
+
27
+ /** Month names (lower case, without accents) in English, German, French and Spanish, to their number. */
28
+ const MONTH_NAMES = {
29
+ january: 1, jan: 1, januar: 1, janvier: 1, janv: 1, enero: 1, ene: 1,
30
+ february: 2, feb: 2, februar: 2, fevrier: 2, fevr: 2, febrero: 2,
31
+ march: 3, mar: 3, marz: 3, maerz: 3, mars: 3, marzo: 3,
32
+ april: 4, apr: 4, avril: 4, avr: 4, abril: 4, abr: 4,
33
+ may: 5, mai: 5, mayo: 5,
34
+ june: 6, jun: 6, juni: 6, juin: 6, junio: 6,
35
+ july: 7, jul: 7, juli: 7, juillet: 7, juil: 7, julio: 7,
36
+ august: 8, aug: 8, aout: 8, agosto: 8,
37
+ september: 9, sep: 9, sept: 9, septembre: 9, septiembre: 9, setiembre: 9,
38
+ october: 10, oct: 10, oktober: 10, okt: 10, octobre: 10, octubre: 10,
39
+ november: 11, nov: 11, novembre: 11, noviembre: 11,
40
+ december: 12, dec: 12, dezember: 12, dez: 12, decembre: 12, diciembre: 12, dic: 12,
41
+ }
42
+ /** Weekday names in the same four languages, to their day (Sunday is 0). */
43
+ const WEEKDAY_NAMES = {
44
+ sunday: 0, sun: 0, sonntag: 0, dimanche: 0, domingo: 0,
45
+ monday: 1, mon: 1, montag: 1, lundi: 1, lunes: 1,
46
+ tuesday: 2, tue: 2, tues: 2, dienstag: 2, mardi: 2, martes: 2,
47
+ wednesday: 3, wed: 3, mittwoch: 3, mercredi: 3, miercoles: 3,
48
+ thursday: 4, thu: 4, thur: 4, thurs: 4, donnerstag: 4, jeudi: 4, jueves: 4,
49
+ friday: 5, fri: 5, freitag: 5, vendredi: 5, viernes: 5,
50
+ saturday: 6, sat: 6, samstag: 6, sonnabend: 6, samedi: 6, sabado: 6,
51
+ }
52
+ /** Counts as words, in the four languages ("a" and "an" are one). */
53
+ const NUMBER_WORDS = {
54
+ a: 1, an: 1, one: 1, ein: 1, eine: 1, einer: 1, einem: 1, einen: 1, un: 1, une: 1, una: 1, uno: 1,
55
+ two: 2, zwei: 2, deux: 2, dos: 2, three: 3, drei: 3, trois: 3, tres: 3, four: 4, vier: 4, quatre: 4, cuatro: 4,
56
+ five: 5, funf: 5, fuenf: 5, cinq: 5, cinco: 5, six: 6, sechs: 6, seis: 6, seven: 7, sieben: 7, sept: 7, siete: 7,
57
+ eight: 8, acht: 8, huit: 8, ocho: 8, nine: 9, neun: 9, neuf: 9, nueve: 9, ten: 10, zehn: 10, dix: 10, diez: 10,
58
+ eleven: 11, twelve: 12, fourteen: 14, vierzehn: 14, quatorze: 14, catorce: 14, thirty: 30,
59
+ }
60
+ /** A unit of "in 3 days", to days or months. */
61
+ const UNITS = [
62
+ [/^(?:day|days|tag|tage|tagen|jour|jours|dia|dias)$/, { days: 1 }],
63
+ [/^(?:week|weeks|woche|wochen|semaine|semaines|semana|semanas)$/, { days: 7 }],
64
+ [/^(?:month|months|monat|monate|monaten|mois|mes|meses)$/, { months: 1 }],
65
+ ]
66
+
67
+ const alternation = (names) => Object.keys(names).sort((a, b) => b.length - a.length).join("|")
68
+ const MONTH = `(${alternation(MONTH_NAMES)})(?![a-z])\\.?`
69
+ const WEEKDAY = `(${alternation(WEEKDAY_NAMES)})(?![a-z])\\.?`
70
+ const COUNT = `(\\d{1,3}|${alternation(NUMBER_WORDS)})`
71
+ const UNIT = "(days?|weeks?|months?|tag(?:e|en)?|wochen?|monat(?:e|en)?|jours?|semaines?|mois|d[i]as?|semanas?|mes(?:es)?)"
72
+ /** An ordinal or day-number suffix: 20th, 1st, 1er, 20., 20º. */
73
+ const ORD = "(?:st|nd|rd|th|er|e|eme|o|º|ª|\\.)?"
74
+ const NEXT_MONTH = "(?:next month|nachsten monats|kommenden monats|du mois prochain|du mois suivant|del mes que viene|del proximo mes|del mes siguiente)"
75
+ const END_OF = "(?:end of(?: the)?|ende(?: des| der)?|fin(?: du| de| del| de la)?|a fin(?:al)?es de|finales de)"
76
+ const MONTH_WORD = "(?:month|monats?|mois|mes)"
77
+
78
+ /** Lower case, accents removed, apostrophes and dashes as spaces: "Après-demain" is "apres demain". */
79
+ export function normalizeText(text) {
80
+ return String(text ?? "")
81
+ .normalize("NFD")
82
+ .replace(/\p{M}/gu, "")
83
+ .replace(/ß/g, "ss")
84
+ .toLowerCase()
85
+ .replace(/[’'`]/g, " ")
86
+ .replace(/(?<=[a-z])-(?=[a-z])/g, " ")
87
+ }
88
+ /** Words that say when, not what: a trigger is checked on its other words. */
89
+ const TRIGGER_STOP = new Set([
90
+ "after", "before", "once", "when", "whenever", "until", "unless", "then", "that", "this", "these", "those", "there", "their",
91
+ "with", "from", "into", "onto", "upon", "about", "have", "has", "been", "being", "will", "would", "should", "could", "must",
92
+ "next", "time", "comes", "come", "back", "done", "gets", "get", "goes", "going", "is", "are", "the", "and", "for",
93
+ ])
94
+
95
+ /** A per-runtime record of the person's recent messages, by session. */
96
+ export function createStatedText({ now = Date.now } = {}) {
97
+ const sessions = new Map()
98
+ /** Per session: each due date dropped, with the person's words it was tied to (see keepStated). */
99
+ const dropped = new Map()
100
+ let seq = 0
101
+
102
+ /** Keep one admitted user message. The same text twice in a row (one message, two events) is kept once. */
103
+ function note(sessionID, text, at = now()) {
104
+ const key = String(sessionID ?? "")
105
+ const value = typeof text === "string" ? text.slice(0, MESSAGE_CHARS).trim() : ""
106
+ if (!key || !value) return
107
+ const list = sessions.get(key) ?? []
108
+ if (list.at(-1)?.text === value) return
109
+ list.push({ text: value, at, seq: ++seq })
110
+ while (list.length > MESSAGES_PER_SESSION) list.shift()
111
+ sessions.delete(key)
112
+ sessions.set(key, list)
113
+ while (sessions.size > SESSIONS_MAX) sessions.delete(sessions.keys().next().value)
114
+ }
115
+
116
+ /** The person's recent messages in a session, oldest first; an empty list when none was seen. */
117
+ function of(sessionID) {
118
+ return [...(sessions.get(String(sessionID ?? "")) ?? [])]
119
+ }
120
+
121
+ /** The due dates dropped in a session, by date: changed in place by the commitments check. */
122
+ function drops(sessionID) {
123
+ const key = String(sessionID ?? "")
124
+ if (!dropped.has(key)) {
125
+ dropped.set(key, new Map())
126
+ while (dropped.size > SESSIONS_MAX) dropped.delete(dropped.keys().next().value)
127
+ }
128
+ return dropped.get(key)
129
+ }
130
+
131
+ function drop(sessionID) {
132
+ sessions.delete(String(sessionID ?? ""))
133
+ dropped.delete(String(sessionID ?? ""))
134
+ }
135
+
136
+ return { note, of, drops, drop }
137
+ }
138
+
139
+ /** "2026-11-13" from a UTC day number. */
140
+ function isoOf(day) {
141
+ return new Date(day * DAY_MS).toISOString().slice(0, 10)
142
+ }
143
+
144
+ /** The UTC day number of a calendar date, or NaN when the date does not exist. */
145
+ function dayOf(year, month, date) {
146
+ const time = Date.UTC(year, month - 1, date)
147
+ const back = new Date(time)
148
+ return back.getUTCFullYear() === year && back.getUTCMonth() === month - 1 && back.getUTCDate() === date ? time / DAY_MS : NaN
149
+ }
150
+
151
+ /** The last day of a month (month may run past 12). */
152
+ function lastDay(year, month) {
153
+ return Date.UTC(year, month, 0) / DAY_MS
154
+ }
155
+
156
+ /** The calendar day (YYYY-MM-DD) an instant falls on in a time zone. */
157
+ function localDay(instant, zone) {
158
+ const parts = Object.fromEntries(
159
+ new Intl.DateTimeFormat("en-CA", { timeZone: zone || "UTC", year: "numeric", month: "2-digit", day: "2-digit" })
160
+ .formatToParts(new Date(instant))
161
+ .map((part) => [part.type, part.value]),
162
+ )
163
+ return `${parts.year}-${parts.month}-${parts.day}`
164
+ }
165
+
166
+ function count(word) {
167
+ return /^\d+$/.test(word) ? Number(word) : NUMBER_WORDS[word] ?? NaN
168
+ }
169
+
170
+ /** The same day `months` months on, clamped to the month's last day. */
171
+ function addMonths(day, months) {
172
+ const date = new Date(day * DAY_MS)
173
+ const target = date.getUTCMonth() + months
174
+ return Math.min(Date.UTC(date.getUTCFullYear(), target, date.getUTCDate()) / DAY_MS, lastDay(date.getUTCFullYear(), target + 1))
175
+ }
176
+
177
+ /**
178
+ * Every day (YYYY-MM-DD) one message names, read against the day it was sent,
179
+ * in English, German, French or Spanish. A day without a year is this year's
180
+ * or next year's; a day without a month ("the 20th") is this month's or next
181
+ * month's; a numeric date is read both ways (13/11 and 11/13); a weekday is
182
+ * its next two occurrences ("next Friday" is either).
183
+ *
184
+ * @param {string} text
185
+ * @param {{ at?: number, zone?: string }} [options]
186
+ * @returns {Set<string>}
187
+ */
188
+ export function daysNamed(text, { at = Date.now(), zone = "UTC" } = {}) {
189
+ let lower = ` ${normalizeText(text)} `
190
+ const today = Date.parse(`${localDay(at, zone)}T00:00:00Z`) / DAY_MS
191
+ const now = new Date(today * DAY_MS)
192
+ const year = now.getUTCFullYear()
193
+ const month = now.getUTCMonth() + 1
194
+ const days = new Set()
195
+ const add = (day) => {
196
+ if (Number.isFinite(day)) days.add(isoOf(day))
197
+ }
198
+ const yearsFor = (given) => (given ? [Number(given.length === 2 ? `20${given}` : given)] : [year, year + 1])
199
+ const all = (pattern) => [...lower.matchAll(new RegExp(pattern, "g"))]
200
+
201
+ // Calendar dates: ISO, day-month-year with dashes, day and month names, numbers.
202
+ for (const m of all("\\b(\\d{4})-(\\d{1,2})-(\\d{1,2})\\b")) add(dayOf(Number(m[1]), Number(m[2]), Number(m[3])))
203
+ for (const m of all("\\b(\\d{1,2})-(\\d{1,2})-(\\d{4})\\b")) add(dayOf(Number(m[3]), Number(m[2]), Number(m[1])))
204
+ for (const m of all(`\\b(\\d{1,2})${ORD}\\s+(?:of\\s+|de\\s+)?${MONTH}(?:,?\\s+(?:de\\s+|del\\s+)?(\\d{4}))?`)) {
205
+ for (const y of yearsFor(m[3])) add(dayOf(y, MONTH_NAMES[m[2]], Number(m[1])))
206
+ }
207
+ for (const m of all(`\\b${MONTH}\\s+(?:the\\s+)?(\\d{1,2})${ORD}(?![\\d:])(?:,?\\s+(\\d{4}))?`)) {
208
+ for (const y of yearsFor(m[3])) add(dayOf(y, MONTH_NAMES[m[1]], Number(m[2])))
209
+ }
210
+ for (const m of all("(?<![\\d./-])(\\d{1,2})[./](\\d{1,2})(?:[./](\\d{4}|\\d{2}))?\\.?(?![\\d./-]*\\d)")) {
211
+ for (const y of yearsFor(m[3])) {
212
+ add(dayOf(y, Number(m[2]), Number(m[1])))
213
+ add(dayOf(y, Number(m[1]), Number(m[2])))
214
+ }
215
+ }
216
+ // A day of the month alone ("on the 20th", "by the 1st", "le 20", "am 20."): this month's or next.
217
+ for (const m of all(`(?:\\b(?:the|le|el|am|zum|den|al|on|by)\\s+(\\d{1,2})${ORD}(?![\\d:])|\\b(\\d{1,2})(?:st|nd|rd|th|er)\\b)(?!\\s+(?:of\\s+|de\\s+)?${MONTH})`)) {
218
+ const date = Number(m[1] ?? m[2])
219
+ add(dayOf(year, month, date))
220
+ add(month === 12 ? dayOf(year + 1, 1, date) : dayOf(year, month + 1, date))
221
+ }
222
+ // "the 15th of next month", "le 15 du mois prochain", "el 15 del mes que viene".
223
+ for (const m of all(`\\b(\\d{1,2})${ORD}\\s+(?:of\\s+)?(?:the\\s+)?${NEXT_MONTH}`)) {
224
+ add(month === 12 ? dayOf(year + 1, 1, Number(m[1])) : dayOf(year, month + 1, Number(m[1])))
225
+ }
226
+
227
+ // Today, tomorrow and the day after.
228
+ const afterTomorrow = /\b(?:day after tomorrow|ubermorgen|uebermorgen|apres demain|pasado manana)\b/
229
+ if (afterTomorrow.test(lower)) add(today + 2)
230
+ lower = lower.replace(new RegExp(afterTomorrow.source, "g"), " ")
231
+ if (/\b(?:today|tonight|this (?:morning|afternoon|evening)|end of (?:the )?day|eod|heute|aujourd hui|ce soir|hoy|esta (?:tarde|noche))\b/.test(lower)) add(today)
232
+ if (/\b(?:tomorrow|morgen|demain|manana)\b/.test(lower)) add(today + 1)
233
+
234
+ // Weekdays: the next two of each named.
235
+ const weekday = now.getUTCDay()
236
+ for (const m of all(`\\b${WEEKDAY}`)) {
237
+ const ahead = (WEEKDAY_NAMES[m[1]] - weekday + 7) % 7
238
+ add(today + ahead)
239
+ add(today + ahead + 7)
240
+ }
241
+
242
+ // The end of a week is its Friday to Sunday; of a month, its last day.
243
+ const endOfWeek = (offset) => {
244
+ const friday = today + ((5 - weekday + 7) % 7) + offset
245
+ for (let day = 0; day < 3; day += 1) add(friday + day)
246
+ }
247
+ if (/\b(?:end of (?:the |this )?week|eow|this weekend|by the weekend|ende der woche|wochenende|fin de (?:la )?semaine|fin de (?:la )?semana)\b/.test(lower)) endOfWeek(0)
248
+ if (/\b(?:end of next week|next weekend)\b/.test(lower)) endOfWeek(7)
249
+ if (new RegExp(`\\b(?:${END_OF}\\s+(?:the\\s+|this\\s+|ce\\s+|este\\s+)?${MONTH_WORD}|eom|monatsende)\\b`).test(lower)) add(lastDay(year, month))
250
+ if (/\b(?:end of next month|ende (?:des )?nachsten monats|fin du mois prochain|fin del (?:mes que viene|proximo mes))\b/.test(lower)) add(lastDay(year, month + 1))
251
+ // "end of November", "Ende November", "fin novembre", "a finales de noviembre".
252
+ for (const m of all(`\\b${END_OF}\\s+${MONTH}`)) {
253
+ for (const y of [year, year + 1]) add(lastDay(y, MONTH_NAMES[m[1]]))
254
+ }
255
+
256
+ // "in 3 days", "in a month", "in drei Tagen", "dans une semaine", "en tres dias"; "3 days from now".
257
+ const ahead = (n, unit) => {
258
+ const rule = UNITS.find(([pattern]) => pattern.test(unit))?.[1]
259
+ if (!rule || !Number.isFinite(n)) return
260
+ add(rule.months ? addMonths(today, n * rule.months) : today + n * rule.days)
261
+ }
262
+ for (const m of all(`\\b(?:in|dans|en)\\s+${COUNT}\\s+${UNIT}\\b`)) ahead(count(m[1]), m[2])
263
+ for (const m of all(`\\b${COUNT}\\s+${UNIT}\\s+from (?:now|today)\\b`)) ahead(count(m[1]), m[2])
264
+ if (/\b(?:in a fortnight|a fortnight from now)\b/.test(lower)) add(today + 14)
265
+ return days
266
+ }
267
+
268
+ /**
269
+ * Whether the person's messages name the day of `due` (YYYY-MM-DD, or a
270
+ * date-time whose date part is read as given).
271
+ *
272
+ * @param {string} due
273
+ * @param {Array<{ text: string, at: number }>} messages
274
+ * @param {string} [zone]
275
+ */
276
+ export function dueStated(due, messages, zone = "UTC") {
277
+ const day = String(due ?? "").slice(0, 10)
278
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return false
279
+ return messages.some((message) => daysNamed(message.text, { at: message.at, zone }).has(day))
280
+ }
281
+
282
+ /**
283
+ * The person's words a due date can be tied to although no day was read from
284
+ * them: its day number ("20th", "20."), its month's name or its weekday's
285
+ * name, in any of the four languages ("Black Friday" ties 2026-11-27). An
286
+ * empty list: the date is tied to nothing the person said, so it is invented.
287
+ *
288
+ * @param {string} due
289
+ * @param {Array<{ text: string }>} messages
290
+ * @returns {string[]}
291
+ */
292
+ export function tiedWords(due, messages) {
293
+ const day = String(due ?? "").slice(0, 10)
294
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return []
295
+ const [year, month, date] = day.split("-").map(Number)
296
+ const weekday = new Date(Date.UTC(year, month - 1, date)).getUTCDay()
297
+ const names = [
298
+ ...Object.entries(MONTH_NAMES).filter(([, value]) => value === month).map(([name]) => name),
299
+ ...Object.entries(WEEKDAY_NAMES).filter(([, value]) => value === weekday).map(([name]) => name),
300
+ ]
301
+ const pattern = new RegExp(`(?<![a-z\\d.])0?${date}(?:st|nd|rd|th|er|e|o|º|ª)?(?![\\d.:/-]*\\d)|\\b(?:${names.sort((a, b) => b.length - a.length).join("|")})(?![a-z])`, "g")
302
+ const words = new Set()
303
+ for (const message of messages) for (const match of normalizeText(message.text).matchAll(pattern)) words.add(match[0])
304
+ return [...words]
305
+ }
306
+
307
+ /** True when `text` holds `word` as a word of its own. */
308
+ export function holdsWord(text, word) {
309
+ const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
310
+ return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(normalizeText(text))
311
+ }
312
+
313
+ /** The words of a trigger that say what must happen, stemmed to five letters. */
314
+ function triggerWords(text) {
315
+ return [...new Set(String(text ?? "").toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [])]
316
+ .filter((word) => word.length >= 3 && !TRIGGER_STOP.has(word))
317
+ .map((word) => word.slice(0, 5))
318
+ }
319
+
320
+ /**
321
+ * Whether the person's messages name the event of `trigger`: at least half of
322
+ * its content words (and one at the least) appear in them. A trigger of only
323
+ * "when" words names nothing to check and passes.
324
+ *
325
+ * @param {string} trigger
326
+ * @param {Array<{ text: string }>} messages
327
+ */
328
+ export function triggerStated(trigger, messages) {
329
+ const wanted = triggerWords(trigger)
330
+ if (wanted.length === 0) return true
331
+ const said = new Set(messages.flatMap((message) => triggerWords(message.text)))
332
+ const hits = wanted.filter((word) => said.has(word)).length
333
+ return hits >= Math.max(1, Math.ceil(wanted.length / 2))
334
+ }