@joe-broadhead/opencode-mem 0.7.1 → 0.8.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.
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Reading and writing a space's records wiki ("Memory records",
3
+ * `commitments.json`). The pure rules live in `records.js`.
4
+ *
5
+ * Two of one person's agents can write the file at once, and the wiki raw
6
+ * route has no conditional write yet (GAPS S2). So a write is a
7
+ * read-modify-write that detects a change since its read:
8
+ *
9
+ * 1. Read the file and apply the change.
10
+ * 2. Re-read just before writing. If the file changed, apply the same change
11
+ * (it names its target by id) to the newer copy and start again.
12
+ * 3. Write, then read back. If another writer replaced the file in between,
13
+ * and the change is not in what is stored now, apply it to that copy and
14
+ * write again.
15
+ *
16
+ * Every write is built from the newest copy read, so a record another writer
17
+ * added is kept: a change touches only its own id. After three rounds without
18
+ * a stable read, the write reports a conflict instead of overwriting.
19
+ */
20
+ import {
21
+ RECORDS_FILE,
22
+ RECORDS_WIKI,
23
+ applyChange,
24
+ dayIn,
25
+ emptyRecords,
26
+ parseRecords,
27
+ serializeRecords,
28
+ } from "./records.js"
29
+ import { errorMessage } from "./util.js"
30
+
31
+ export const MAX_ROUNDS = 3
32
+
33
+ /** True when a stored copy already reflects a change (nothing left to write). */
34
+ function reflects(records, change, item) {
35
+ const stored = records.items.find((entry) => entry.id === change.id)
36
+ if (change.action === "delete") return !stored
37
+ if (!stored || !item) return false
38
+ return JSON.stringify(stored) === JSON.stringify(item)
39
+ }
40
+
41
+ /**
42
+ * @param {{ backend: any, control?: any, log?: any }} deps
43
+ */
44
+ export function createRecordsStore({ backend, control, log }) {
45
+ /** Records wiki id per container: one lookup per space and process. */
46
+ const wikiIds = new Map()
47
+ const known = new Set()
48
+
49
+ function remember(teamID, wikiID) {
50
+ wikiIds.set(teamID, wikiID)
51
+ known.add(wikiID)
52
+ }
53
+
54
+ /** True for a wiki id this process knows is a records wiki. */
55
+ function isRecordsWiki(wikiID) {
56
+ return known.has(String(wikiID ?? ""))
57
+ }
58
+
59
+ /**
60
+ * Find the space's records wiki. A wiki listing that fails is an error, not
61
+ * an empty space: a write must never create a second records wiki because a
62
+ * read timed out.
63
+ */
64
+ async function locate(scope) {
65
+ const key = String(scope.team_id ?? "")
66
+ if (wikiIds.has(key)) return wikiIds.get(key)
67
+ // The wiki list and the asset catalogue can each miss a wiki the other
68
+ // has (knowledge.js discoverKnowledge merges them for the same reason), so
69
+ // both are read; only both failing is an error.
70
+ const [wikis, assets] = await Promise.allSettled([
71
+ backend.listWiki({ scope }),
72
+ typeof backend.listAccessibleAssets === "function"
73
+ ? backend.listAccessibleAssets({ scope, assetType: "llm_wiki" })
74
+ : Promise.reject(new Error("no asset listing")),
75
+ ])
76
+ if (wikis.status === "rejected" && assets.status === "rejected") throw wikis.reason
77
+ const fromList = (wikis.value?.items ?? []).find((item) => item?.name === RECORDS_WIKI && item?.wiki_id)?.wiki_id
78
+ const fromAssets = (assets.value?.items ?? []).find(
79
+ (item) => item?.asset_type === "llm_wiki" && item?.name === RECORDS_WIKI && (item?.content_ref || item?.asset_id),
80
+ )
81
+ const found = fromList ?? fromAssets?.content_ref ?? fromAssets?.asset_id
82
+ if (!found) return ""
83
+ remember(key, String(found))
84
+ return String(found)
85
+ }
86
+
87
+ /** Create the records wiki and, where a control plane owns the catalogue, register it. */
88
+ async function create(scope, spaceContext) {
89
+ const wiki = await backend.createWiki({ scope, name: RECORDS_WIKI })
90
+ const wikiID = String(wiki?.wiki_id ?? "")
91
+ if (!wikiID) throw new Error("wiki/create returned no wiki_id")
92
+ const registered = typeof wiki?.resource_id === "string" && wiki.resource_id.trim()
93
+ if (!registered && control && spaceContext?.space_id) {
94
+ const userId = spaceContext.user_id
95
+ if (userId) {
96
+ await control.createResource({
97
+ userId,
98
+ spaceId: spaceContext.space_id,
99
+ resource: { kind: "wiki", upstream_id: wikiID, name: RECORDS_WIKI },
100
+ })
101
+ }
102
+ }
103
+ remember(String(scope.team_id ?? ""), wikiID)
104
+ return wikiID
105
+ }
106
+
107
+ async function readText(scope, wikiID) {
108
+ let data
109
+ try {
110
+ data = await backend.readWikiRaw({ scope, wikiID, filenames: [RECORDS_FILE] })
111
+ } catch (error) {
112
+ // The cached id may belong to a wiki that was deleted since.
113
+ if (Number(error?.status) === 404) {
114
+ for (const [key, value] of wikiIds) if (value === wikiID) wikiIds.delete(key)
115
+ known.delete(wikiID)
116
+ }
117
+ throw error
118
+ }
119
+ const item = (data?.items ?? []).find((entry) => entry?.filename === RECORDS_FILE)
120
+ return typeof item?.content === "string" ? item.content : ""
121
+ }
122
+
123
+ /**
124
+ * The space's commitments. No records wiki yet is an empty set.
125
+ *
126
+ * @returns {Promise<{ wikiID: string, records: ReturnType<typeof emptyRecords>, text: string }>}
127
+ */
128
+ async function read(scope) {
129
+ const wikiID = await locate(scope)
130
+ if (!wikiID) return { wikiID: "", records: emptyRecords(), text: "" }
131
+ const text = await readText(scope, wikiID)
132
+ const parsed = parseRecords(text)
133
+ if (parsed.error) throw new Error(parsed.error)
134
+ return { wikiID, records: parsed.records, text }
135
+ }
136
+
137
+ /**
138
+ * Apply one change with the concurrency check described above.
139
+ *
140
+ * @param {any} scope
141
+ * @param {any} spaceContext
142
+ * @param {{ action: "add" | "update" | "delete", id: string, fields?: Record<string, any> }} change
143
+ * @param {{ now: number, zone: string, session?: string }} context
144
+ * @returns {Promise<{ item?: any, records?: any, rounds?: number, unchanged?: boolean, error?: string, conflict?: boolean }>}
145
+ */
146
+ async function change(scope, spaceContext, change, context) {
147
+ const today = dayIn(context.now, context.zone)
148
+ let wikiID = await locate(scope)
149
+ if (!wikiID && change.action !== "add") return { error: `no commitment ${change.id} in this space: it has no commitments yet` }
150
+ if (!wikiID) wikiID = await create(scope, spaceContext)
151
+
152
+ let text = await readText(scope, wikiID)
153
+ for (let round = 1; round <= MAX_ROUNDS; round += 1) {
154
+ const parsed = parseRecords(text)
155
+ if (parsed.error) return { error: `${parsed.error}; nothing was written` }
156
+ const applied = applyChange(parsed.records, change, { today, session: context.session })
157
+ if (applied.error) return { error: applied.error }
158
+ if (applied.unchanged) return { item: applied.item, records: parsed.records, rounds: round, unchanged: true }
159
+ const next = { ...parsed.records, version: parsed.records.version + 1, items: applied.items }
160
+ const body = serializeRecords(next)
161
+
162
+ // Re-read just before writing: a write since our read means our copy is
163
+ // old, so the change is applied again to the newer one.
164
+ const latest = await readText(scope, wikiID)
165
+ if (latest !== text) {
166
+ log?.debug?.("records changed since read; merging", { round })
167
+ text = latest
168
+ continue
169
+ }
170
+
171
+ await backend.writeWikiRaw({ scope, wikiID, files: [{ filename: RECORDS_FILE, content: body }] })
172
+
173
+ // Read back: a writer that raced us between the re-read and the write
174
+ // shows here. If our change is in what is stored, we are done;
175
+ // otherwise apply it to the stored copy and write again.
176
+ const stored = await readText(scope, wikiID)
177
+ if (stored === body) return { item: applied.item, records: next, rounds: round }
178
+ const storedParsed = parseRecords(stored)
179
+ if (!storedParsed.error && reflects(storedParsed.records, change, applied.item)) {
180
+ return { item: applied.item, records: storedParsed.records, rounds: round }
181
+ }
182
+ log?.debug?.("records replaced after write; merging", { round })
183
+ text = stored
184
+ }
185
+ return {
186
+ conflict: true,
187
+ error: `another agent kept changing this space's commitments; nothing was overwritten. Try again in a moment.`,
188
+ }
189
+ }
190
+
191
+ /** Note a records wiki seen in a listing, so mem_wiki refuses it by id too. */
192
+ function noteRecordsWiki(wikiID) {
193
+ if (wikiID) known.add(String(wikiID))
194
+ }
195
+
196
+ return { read, change, locate, isRecordsWiki, noteRecordsWiki, remember }
197
+ }
198
+
199
+ /** A records read for the pinned block: never throws; a failure is `null`. */
200
+ export async function readRecordsQuietly(store, scope, log) {
201
+ try {
202
+ return (await store.read(scope)).records
203
+ } catch (error) {
204
+ log?.debug?.("records read failed", { error: errorMessage(error) })
205
+ return null
206
+ }
207
+ }
package/src/records.js ADDED
@@ -0,0 +1,440 @@
1
+ /**
2
+ * Commitments: things someone will do, with a time or a trigger, kept as a
3
+ * structured record with a state (docs/design/memory-value-design.md §7).
4
+ *
5
+ * Atoms cannot hold this: they cannot be updated, upstream assigns their type,
6
+ * and `work_task` atoms are withheld from recall by design. So each space
7
+ * keeps one reserved, never-ingested wiki, "Memory records", holding one file,
8
+ * `commitments.json`:
9
+ *
10
+ * { "marker": "opencode-mem:records v1", "version": 7, "items": [ … ] }
11
+ *
12
+ * This module is pure: parse, validate, apply a change, merge a change into a
13
+ * newer copy, and render the Due list and the list answer. The I/O and the
14
+ * concurrency check live in `records-store.js`.
15
+ */
16
+ import { isInstructionShaped } from "./curation.js"
17
+ import { neutralizeFenceClosers, oneLine } from "./util.js"
18
+
19
+ export const RECORDS_WIKI = "Memory records"
20
+ export const RECORDS_FILE = "commitments.json"
21
+ export const RECORDS_MARKER = "opencode-mem:records v1"
22
+
23
+ export const STATES = Object.freeze(["open", "done", "cancelled"])
24
+ export const MAX_WHAT_CHARS = 300
25
+ export const MAX_TRIGGER_CHARS = 200
26
+ /** Closed commitments are kept this long, then dropped on the next write. */
27
+ export const CLOSED_RETENTION_DAYS = 90
28
+ /** One space's file stays small: the Due list and the views read it whole. */
29
+ export const MAX_ITEMS = 500
30
+ /**
31
+ * The Due list holds overdue items and those due within this many working
32
+ * days after today. The design's kill rule ("the Due list nags") sets it to 0:
33
+ * overdue and today only.
34
+ */
35
+ export const DUE_WORKING_DAYS = 2
36
+ export const DUE_MAX_LINES = 5
37
+
38
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/
39
+ const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/
40
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,79}$/
41
+ const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
42
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
43
+
44
+ /** An empty records file. */
45
+ export function emptyRecords() {
46
+ return { marker: RECORDS_MARKER, version: 0, items: [] }
47
+ }
48
+
49
+ /**
50
+ * Read a records file. A missing file is an empty record set; a file that is
51
+ * not ours (no marker) or not JSON is an error, so a write never replaces
52
+ * something it does not understand.
53
+ *
54
+ * @param {string | null | undefined} text
55
+ * @returns {{ records?: { marker: string, version: number, items: any[] }, error?: string }}
56
+ */
57
+ export function parseRecords(text) {
58
+ if (text === null || text === undefined || String(text).trim() === "") return { records: emptyRecords() }
59
+ let parsed
60
+ try {
61
+ parsed = JSON.parse(String(text))
62
+ } catch {
63
+ return { error: "the records file is not valid JSON" }
64
+ }
65
+ if (!parsed || typeof parsed !== "object" || parsed.marker !== RECORDS_MARKER) {
66
+ return { error: "the records file has no opencode-mem records marker" }
67
+ }
68
+ const version = Number.isInteger(parsed.version) && parsed.version >= 0 ? parsed.version : 0
69
+ const items = (Array.isArray(parsed.items) ? parsed.items : []).filter(
70
+ (item) => item && typeof item === "object" && typeof item.id === "string" && typeof item.what === "string",
71
+ )
72
+ return { records: { marker: RECORDS_MARKER, version, items } }
73
+ }
74
+
75
+ /** The file's text; the marker is the first key, as a share's marker is its first line. */
76
+ export function serializeRecords(records) {
77
+ return `${JSON.stringify({ marker: RECORDS_MARKER, version: records.version, items: records.items }, null, 2)}\n`
78
+ }
79
+
80
+ /** True when a file's text is a records file (used to keep it out of mem_wiki). */
81
+ export function isRecordsText(text) {
82
+ try {
83
+ return JSON.parse(String(text))?.marker === RECORDS_MARKER
84
+ } catch {
85
+ return false
86
+ }
87
+ }
88
+
89
+ function validCalendarDate(year, month, day) {
90
+ const date = new Date(Date.UTC(year, month - 1, day))
91
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
92
+ }
93
+
94
+ /**
95
+ * Validate a due value: a date (`YYYY-MM-DD`, by the end of that day in the
96
+ * agent's zone) or a date-time with an offset. The tool cannot know what
97
+ * "Friday" meant, so it refuses anything else rather than guess.
98
+ *
99
+ * @returns {{ due?: string, error?: string }}
100
+ */
101
+ export function validateDue(value) {
102
+ const text = String(value ?? "").trim()
103
+ const date = text.match(DATE)
104
+ if (date) {
105
+ if (!validCalendarDate(Number(date[1]), Number(date[2]), Number(date[3]))) {
106
+ return { error: `${text} is not a calendar date; due is YYYY-MM-DD, for example 2026-11-06` }
107
+ }
108
+ return { due: text }
109
+ }
110
+ const time = text.match(DATE_TIME)
111
+ if (time && validCalendarDate(Number(time[1]), Number(time[2]), Number(time[3])) && Number(time[4]) < 24 && Number(time[5]) < 60) {
112
+ if (Number.isFinite(Date.parse(text))) return { due: text }
113
+ }
114
+ return {
115
+ error: `due must be a date, YYYY-MM-DD (for example 2026-11-06), or a date-time with an offset (for example 2026-11-06T15:00:00+00:00); got ${JSON.stringify(oneLine(text, 60))}. Resolve "Friday" or "next week" against today first.`,
116
+ }
117
+ }
118
+
119
+ /** The calendar day an instant falls on in a zone, as `YYYY-MM-DD`. */
120
+ export function dayIn(instant, zone) {
121
+ const parts = Object.fromEntries(
122
+ new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" })
123
+ .formatToParts(new Date(instant))
124
+ .map((part) => [part.type, part.value]),
125
+ )
126
+ return `${parts.year}-${parts.month}-${parts.day}`
127
+ }
128
+
129
+ /** The day a commitment is due, in the zone: a bare date is itself. */
130
+ export function dueDay(due, zone) {
131
+ if (!due) return ""
132
+ return DATE.test(due) ? due : dayIn(Date.parse(due), zone)
133
+ }
134
+
135
+ function addDays(day, count) {
136
+ const [year, month, date] = day.split("-").map(Number)
137
+ const next = new Date(Date.UTC(year, month - 1, date + count))
138
+ return next.toISOString().slice(0, 10)
139
+ }
140
+
141
+ function weekday(day) {
142
+ const [year, month, date] = day.split("-").map(Number)
143
+ return new Date(Date.UTC(year, month - 1, date)).getUTCDay()
144
+ }
145
+
146
+ /** The n-th working day (Monday to Friday) after `day`; 0 is `day` itself. */
147
+ export function workingDaysAfter(day, count) {
148
+ let current = day
149
+ let left = count
150
+ while (left > 0) {
151
+ current = addDays(current, 1)
152
+ const dow = weekday(current)
153
+ if (dow !== 0 && dow !== 6) left -= 1
154
+ }
155
+ return current
156
+ }
157
+
158
+ /** "Fri 6 Nov", the form every answer and view echoes back. */
159
+ export function formatDay(day) {
160
+ if (!DATE.test(String(day ?? ""))) return String(day ?? "")
161
+ const [, month, date] = day.split("-").map(Number)
162
+ return `${WEEKDAYS[weekday(day)]} ${date} ${MONTHS[month - 1]}`
163
+ }
164
+
165
+ /** "Fri 6 Nov" or "Fri 6 Nov 15:00 (+00:00)" for a date-time. */
166
+ export function formatDue(due, zone) {
167
+ if (!due) return ""
168
+ if (DATE.test(due)) return formatDay(due)
169
+ const day = dueDay(due, zone)
170
+ const time = new Intl.DateTimeFormat("en-GB", { timeZone: zone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(
171
+ new Date(Date.parse(due)),
172
+ )
173
+ return `${formatDay(day)} ${time}`
174
+ }
175
+
176
+ /** A new id: `cmt_` and eight base32 characters. */
177
+ export function newCommitmentId(random = Math.random) {
178
+ const alphabet = "abcdefghijklmnopqrstuvwxyz234567"
179
+ let id = "cmt_"
180
+ for (let index = 0; index < 8; index += 1) id += alphabet[Math.floor(random() * alphabet.length)]
181
+ return id
182
+ }
183
+
184
+ /**
185
+ * Validate the text fields of an add or update. `what` and `trigger` are
186
+ * stored and pushed into the system prompt, so they pass the instruction
187
+ * guard; they are not held to the status guard (a commitment is the home for
188
+ * exactly what that guard refuses).
189
+ *
190
+ * @returns {{ fields?: Record<string, any>, error?: string }}
191
+ */
192
+ export function validateFields(input, { requireWhat = false } = {}) {
193
+ const fields = {}
194
+ const has = (key) => input?.[key] !== undefined && input?.[key] !== null
195
+ if (requireWhat || has("what")) {
196
+ const what = oneLine(input?.what ?? "", MAX_WHAT_CHARS + 1).trim()
197
+ if (!what) return { error: "what is required: what will be done, starting with a verb (\"Send the Q4 numbers to Ama\")" }
198
+ if (what.length > MAX_WHAT_CHARS) return { error: `what is limited to ${MAX_WHAT_CHARS} characters` }
199
+ fields.what = what
200
+ }
201
+ if (has("owner")) {
202
+ const owner = oneLine(input.owner, 80).trim()
203
+ if (!owner) return { error: 'owner is "user", "agent", or a person\'s name' }
204
+ fields.owner = /^(user|me|you)$/i.test(owner) ? "user" : /^agent$/i.test(owner) ? "agent" : owner
205
+ }
206
+ if (has("due")) {
207
+ if (String(input.due).trim() === "") fields.due = ""
208
+ else {
209
+ const due = validateDue(input.due)
210
+ if (due.error) return { error: due.error }
211
+ fields.due = due.due
212
+ }
213
+ }
214
+ if (has("trigger")) {
215
+ const trigger = oneLine(input.trigger, MAX_TRIGGER_CHARS + 1).trim()
216
+ if (trigger.length > MAX_TRIGGER_CHARS) return { error: `trigger is limited to ${MAX_TRIGGER_CHARS} characters` }
217
+ fields.trigger = trigger
218
+ }
219
+ if (has("project")) {
220
+ const project = String(input.project).trim().toLowerCase()
221
+ if (project && !SLUG.test(project)) return { error: 'project is the page slug: lower-case words joined by hyphens, for example "checkout-v3"' }
222
+ fields.project = project
223
+ }
224
+ if (has("link")) fields.link = oneLine(input.link, 300).trim()
225
+ if (has("state")) {
226
+ const state = String(input.state).trim().toLowerCase()
227
+ if (!STATES.includes(state)) return { error: `state must be one of ${STATES.join(", ")}` }
228
+ fields.state = state
229
+ }
230
+ for (const key of ["what", "trigger", "owner", "link"]) {
231
+ if (fields[key] && isInstructionShaped(fields[key])) {
232
+ return { error: `${key} contains an instruction. Memory is a data channel and never carries commands.` }
233
+ }
234
+ }
235
+ return { fields }
236
+ }
237
+
238
+ /** Lower-case words only: "Send the Q4 numbers to Ama." equals "send the q4 numbers to Ama". */
239
+ export function normalText(value) {
240
+ return String(value ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()
241
+ }
242
+
243
+ function sameText(left, right) {
244
+ return normalText(left) !== "" && normalText(left) === normalText(right)
245
+ }
246
+
247
+ const STOP_WORDS = new Set("the a an and or to of for on in at by with from my our your me us".split(" "))
248
+
249
+ /** Open commitments whose words mostly overlap `what`: possible duplicates to show the agent. */
250
+ export function similarOpen(items, what, exceptId) {
251
+ const words = (value) => new Set(normalText(value).split(" ").filter((word) => word.length > 1 && !STOP_WORDS.has(word)))
252
+ const target = words(what)
253
+ if (target.size === 0) return []
254
+ return (items ?? []).filter((item) => {
255
+ if (item.state !== "open" || item.id === exceptId) return false
256
+ const other = words(item.what)
257
+ let shared = 0
258
+ for (const word of target) if (other.has(word)) shared += 1
259
+ return shared / Math.max(target.size, other.size) >= 0.5
260
+ })
261
+ }
262
+
263
+ /** Drop empty optional fields so a cleared field is gone, not an empty string. */
264
+ function compact(item) {
265
+ const out = {}
266
+ for (const [key, value] of Object.entries(item)) {
267
+ if (value === "" || value === undefined || value === null) continue
268
+ out[key] = value
269
+ }
270
+ return out
271
+ }
272
+
273
+ /**
274
+ * Closed commitments older than the retention window are dropped. A closed
275
+ * item with no `closed` date uses `updated`.
276
+ */
277
+ export function prune(items, today) {
278
+ const cutoff = addDays(today, -CLOSED_RETENTION_DAYS)
279
+ return items.filter((item) => item.state === "open" || String(item.closed ?? item.updated ?? today) >= cutoff)
280
+ }
281
+
282
+ /**
283
+ * One change, applied to a record set. A change is replayable: it names its
284
+ * target by id, so the same change can be applied again to a newer copy of
285
+ * the file that someone else wrote in between (`records-store.js`).
286
+ *
287
+ * @param {{ items: any[] }} records
288
+ * @param {{ action: "add" | "update" | "delete", id: string, fields?: Record<string, any> }} change
289
+ * @param {{ today: string, session?: string }} context
290
+ * @returns {{ items?: any[], item?: any, error?: string, unchanged?: boolean }}
291
+ */
292
+ export function applyChange(records, change, context) {
293
+ const items = records.items.slice()
294
+ const index = items.findIndex((item) => item.id === change.id)
295
+ if (change.action === "add") {
296
+ if (index >= 0) return { items, item: items[index], unchanged: true }
297
+ // The same open commitment, worded the same, is not added twice.
298
+ const same = items.find((item) => item.state === "open" && sameText(item.what, change.fields.what))
299
+ if (same) return { items, item: same, unchanged: true, duplicate: true }
300
+ if (items.filter((item) => item.state === "open").length >= MAX_ITEMS) {
301
+ return { error: `this space already holds ${MAX_ITEMS} open commitments; close or delete some first` }
302
+ }
303
+ const item = compact({
304
+ id: change.id,
305
+ what: change.fields.what,
306
+ owner: change.fields.owner ?? "user",
307
+ due: change.fields.due,
308
+ trigger: change.fields.trigger,
309
+ state: "open",
310
+ project: change.fields.project,
311
+ link: change.fields.link,
312
+ created: context.today,
313
+ updated: context.today,
314
+ session: context.session,
315
+ })
316
+ items.push(item)
317
+ return { items: prune(items, context.today), item }
318
+ }
319
+ if (index < 0) return { error: `no commitment ${oneLine(change.id, 40)} in this space` }
320
+ if (change.action === "delete") {
321
+ const [item] = items.splice(index, 1)
322
+ return { items: prune(items, context.today), item }
323
+ }
324
+ const before = items[index]
325
+ const next = { ...before, ...change.fields, updated: context.today }
326
+ if (change.fields.state && change.fields.state !== before.state) {
327
+ if (change.fields.state === "open") delete next.closed
328
+ else next.closed = context.today
329
+ }
330
+ const item = compact(next)
331
+ items[index] = item
332
+ return { items: prune(items, context.today), item }
333
+ }
334
+
335
+ /** Open first, then by due day (overdue first), undated last, then by creation. */
336
+ export function sortItems(items, zone) {
337
+ const rank = (item) => (item.state === "open" ? 0 : 1)
338
+ return items.slice().sort((a, b) => {
339
+ if (rank(a) !== rank(b)) return rank(a) - rank(b)
340
+ const left = dueDay(a.due, zone) || "9999-99-99"
341
+ const right = dueDay(b.due, zone) || "9999-99-99"
342
+ if (left !== right) return left < right ? -1 : 1
343
+ return String(a.created ?? "").localeCompare(String(b.created ?? ""))
344
+ })
345
+ }
346
+
347
+ /** How a person or the agent reads the owner. */
348
+ function ownerLabel(owner) {
349
+ return oneLine(owner || "user", 80)
350
+ }
351
+
352
+ /** Text from a record that is about to be shown: fence-safe, one line. */
353
+ function shown(value, max) {
354
+ return neutralizeFenceClosers(oneLine(value, max))
355
+ }
356
+
357
+ /**
358
+ * When a commitment is due, relative to today: "overdue since Mon 2 Nov",
359
+ * "today", or "Fri 6 Nov".
360
+ */
361
+ export function dueLabel(item, today, zone) {
362
+ const day = dueDay(item.due, zone)
363
+ if (!day) return ""
364
+ if (day < today) return `overdue since ${formatDay(day)}`
365
+ if (day === today) return DATE.test(item.due) ? "today" : `today ${formatDue(item.due, zone).split(" ").pop()}`
366
+ return formatDue(item.due, zone)
367
+ }
368
+
369
+ /**
370
+ * The pinned block's Due section: overdue items and those due within the next
371
+ * `DUE_WORKING_DAYS` working days, oldest first, at most `DUE_MAX_LINES`
372
+ * lines, then a count of the other open items. It carries no time of day, so
373
+ * its bytes change only when a commitment or the date changes, and the
374
+ * provider's prompt cache holds within a day. A line whose text is an
375
+ * instruction is withheld and counted, as every pinned line is.
376
+ *
377
+ * @returns {{ text: string, withheld: number }}
378
+ */
379
+ export function dueSection(items, { today, zone, workingDays = DUE_WORKING_DAYS }) {
380
+ const open = sortItems(
381
+ (items ?? []).filter((item) => item.state === "open"),
382
+ zone,
383
+ )
384
+ const horizon = workingDaysAfter(today, workingDays)
385
+ let withheld = 0
386
+ const due = []
387
+ for (const item of open) {
388
+ const day = dueDay(item.due, zone)
389
+ if (!day || day > horizon) continue
390
+ if (isInstructionShaped(item.what) || isInstructionShaped(item.owner)) {
391
+ withheld += 1
392
+ continue
393
+ }
394
+ due.push(item)
395
+ }
396
+ if (due.length === 0) return { text: "", withheld }
397
+ const lines = due
398
+ .slice(0, DUE_MAX_LINES)
399
+ .map((item) => `- ${dueLabel(item, today, zone)}: ${shown(item.what, 160)} (${shown(ownerLabel(item.owner), 60)}) [${shown(item.id, 20)}]`)
400
+ const more = open.length - withheld - lines.length
401
+ if (more > 0) lines.push(`(${more} more open: mem_commitments list)`)
402
+ return { text: `## Due (${formatDay(today)})\n${lines.join("\n")}`, withheld }
403
+ }
404
+
405
+ /**
406
+ * Filter a list request: `state` (open by default, or done, cancelled, all),
407
+ * `project`, `owner`, and `due_before` (a day).
408
+ */
409
+ export function filterItems(items, filter, zone) {
410
+ const state = String(filter?.state ?? "open").toLowerCase()
411
+ const project = String(filter?.project ?? "").trim().toLowerCase()
412
+ const owner = String(filter?.owner ?? "").trim().toLowerCase()
413
+ const before = String(filter?.due_before ?? "").trim()
414
+ return sortItems(
415
+ (items ?? []).filter((item) => {
416
+ if (state !== "all" && item.state !== state) return false
417
+ if (project && item.project !== project) return false
418
+ if (owner && String(item.owner ?? "user").toLowerCase() !== (owner === "me" ? "user" : owner)) return false
419
+ if (before) {
420
+ const day = dueDay(item.due, zone)
421
+ if (!day || day >= before) return false
422
+ }
423
+ return true
424
+ }),
425
+ zone,
426
+ )
427
+ }
428
+
429
+ /** One line of a list answer. */
430
+ export function itemLine(item, today, zone) {
431
+ const parts = [`${shown(item.id, 20)}`, shown(item.what, MAX_WHAT_CHARS)]
432
+ const when = item.state === "open" ? dueLabel(item, today, zone) : item.due ? formatDue(item.due, zone) : ""
433
+ if (when) parts.push(item.state === "open" ? when : `due ${when}`)
434
+ if (item.trigger) parts.push(`when: ${shown(item.trigger, MAX_TRIGGER_CHARS)}`)
435
+ parts.push(`owner ${shown(ownerLabel(item.owner), 80)}`)
436
+ if (item.state !== "open") parts.push(`${item.state}${item.closed ? ` ${formatDay(item.closed)}` : ""}`)
437
+ if (item.project) parts.push(`project ${shown(item.project, 80)}`)
438
+ if (item.link) parts.push(`link ${shown(item.link, 200)}`)
439
+ return `- ${parts.join(" · ")}`
440
+ }