advisers 0.1.0-preview.4 → 0.2.0

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/LICENSE +131 -21
  2. package/NOTICE +34 -0
  3. package/README-zh.md +40 -9
  4. package/README.md +53 -10
  5. package/THIRD-PARTY-NOTICES.md +277 -0
  6. package/bin/advisers.js +4230 -122
  7. package/index.js +1 -1
  8. package/lib/agent.js +414 -0
  9. package/lib/attachments.js +283 -0
  10. package/lib/capture.js +168 -0
  11. package/lib/context-window.js +123 -0
  12. package/lib/digest.js +27 -0
  13. package/lib/doc-review.js +30 -0
  14. package/lib/egress.js +27 -0
  15. package/lib/evidence.js +1995 -0
  16. package/lib/ical.js +542 -0
  17. package/lib/imap.js +181 -0
  18. package/lib/importers.js +1001 -0
  19. package/lib/learning.js +46 -0
  20. package/lib/mcp-server.js +869 -0
  21. package/lib/model.js +307 -0
  22. package/lib/notify.js +189 -0
  23. package/lib/nudge.js +10 -0
  24. package/lib/ocr.js +47 -0
  25. package/lib/pdf.js +105 -0
  26. package/lib/pet-brief-store.js +51 -0
  27. package/lib/pet-brief.js +644 -0
  28. package/lib/receipt-verify.js +624 -0
  29. package/lib/relative-date.js +393 -0
  30. package/lib/remind.js +690 -0
  31. package/lib/research.js +193 -0
  32. package/lib/review.js +88 -0
  33. package/lib/routine.js +22 -0
  34. package/lib/safety/classifier.js +392 -0
  35. package/lib/safety/explain.js +157 -0
  36. package/lib/safety/index.js +333 -0
  37. package/lib/safety/redact.js +212 -0
  38. package/lib/safety/rules.js +824 -0
  39. package/lib/scheduler.js +399 -0
  40. package/lib/source.js +294 -0
  41. package/lib/sqlite.js +1022 -0
  42. package/lib/sync.js +129 -0
  43. package/lib/timestamp.js +45 -0
  44. package/lib/tos/index.js +332 -0
  45. package/lib/tos/manifest.json +32 -0
  46. package/lib/tos/privacy.zh-CN.md +136 -0
  47. package/lib/tos/safety.zh-CN.md +101 -0
  48. package/lib/tos/summary.zh-CN.md +12 -0
  49. package/lib/tos/terms.zh-CN.md +439 -0
  50. package/lib/ui.js +49 -0
  51. package/lib/undo.js +83 -0
  52. package/lib/vault.js +51 -0
  53. package/package.json +26 -4
package/lib/remind.js ADDED
@@ -0,0 +1,690 @@
1
+ /**
2
+ * E1 — reminder planning and ICS export.
3
+ *
4
+ * Pure helpers: no SQLite, no network, no filesystem and no process state.
5
+ * All wall-clock reasoning is pinned to Asia/Shanghai, and `now` is injectable
6
+ * so tests (and a future CLI wiring) can replay an exact instant.
7
+ *
8
+ * The caller decides how reminders are delivered; this module only answers
9
+ * "which reminders are due at `now`" and "what does the calendar look like".
10
+ */
11
+
12
+ const DAY_MS = 86_400_000
13
+ /** Asia/Shanghai has been UTC+8 without DST since 1991. */
14
+ const SHANGHAI_OFFSET_MS = 8 * 60 * 60 * 1000
15
+
16
+ export const TIME_ZONE = 'Asia/Shanghai'
17
+ export const DEFAULT_HORIZON_DAYS = 7
18
+
19
+ const BUCKETS = new Set(['overdue', 'due-today', 'due-1d', 'upcoming'])
20
+ const LEVELS = new Set(['L1', 'L2', 'L3'])
21
+
22
+ const DAY_FORMAT = new Intl.DateTimeFormat('en-US', {
23
+ timeZone: TIME_ZONE,
24
+ year: 'numeric',
25
+ month: '2-digit',
26
+ day: '2-digit',
27
+ })
28
+ const TIME_FORMAT = new Intl.DateTimeFormat('en-US', {
29
+ timeZone: TIME_ZONE,
30
+ hour: '2-digit',
31
+ minute: '2-digit',
32
+ hourCycle: 'h23',
33
+ })
34
+
35
+ const LOCAL_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?)?$/
36
+ const COMPACT_DATE_TIME = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})?(Z)?)?$/
37
+
38
+ /** Parse `YYYY-MM-DD HH:mm[:ss]` as Asia/Shanghai wall time. */
39
+ function parseWallClock(match) {
40
+ const [, y, mo, d, h = '0', mi = '0', s = '0', fraction] = match
41
+ return buildDate(Number(y), Number(mo), Number(d), Number(h), Number(mi), Number(s), Number((fraction ?? '0').padEnd(3, '0')), SHANGHAI_OFFSET_MS)
42
+ }
43
+
44
+ /** Parse an RFC5545 compact date-time (`YYYYMMDDTHHMMSS[Z]`) as UTC or Shanghai wall time. */
45
+ function parseCompact(match) {
46
+ const [, y, mo, d, h = '0', mi = '0', s = '0', z] = match
47
+ return buildDate(Number(y), Number(mo), Number(d), Number(h), Number(mi), Number(s), 0, z ? 0 : SHANGHAI_OFFSET_MS)
48
+ }
49
+
50
+ function buildDate(year, month, day, hour, minute, second, millisecond, offsetMs) {
51
+ if (month < 1 || month > 12 || day < 1 || day > 31) return null
52
+ if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) return null
53
+ const date = new Date(Date.UTC(year, month - 1, day, hour, minute, second, millisecond) - offsetMs)
54
+ return Number.isNaN(date.getTime()) ? null : date
55
+ }
56
+
57
+ /**
58
+ * Convert a Date, epoch milliseconds, ISO string, or ICS compact date into a
59
+ * Date. Values without a zone are treated as Asia/Shanghai wall time so the
60
+ * result never depends on the host timezone.
61
+ */
62
+ function toDate(value) {
63
+ if (value instanceof Date) {
64
+ return Number.isNaN(value.getTime()) ? null : new Date(value.getTime())
65
+ }
66
+ if (typeof value === 'number') {
67
+ return Number.isFinite(value) ? new Date(value) : null
68
+ }
69
+ if (typeof value !== 'string') return null
70
+ const text = value.trim()
71
+ if (!text) return null
72
+ const wallClock = LOCAL_DATE_TIME.exec(text)
73
+ if (wallClock) return parseWallClock(wallClock)
74
+ const compact = COMPACT_DATE_TIME.exec(text)
75
+ if (compact) return parseCompact(compact)
76
+ const epoch = Date.parse(text)
77
+ return Number.isNaN(epoch) ? null : new Date(epoch)
78
+ }
79
+
80
+ function requireDate(value, label) {
81
+ const date = toDate(value)
82
+ if (!date) throw new RangeError(`invalid ${label}: ${String(value)}`)
83
+ return date
84
+ }
85
+
86
+ function requireNow(value) {
87
+ if (value === undefined) return new Date()
88
+ return requireDate(value, 'now')
89
+ }
90
+
91
+ function dayParts(date) {
92
+ const parts = DAY_FORMAT.formatToParts(date)
93
+ const pick = (type) => parts.find((part) => part.type === type)?.value
94
+ return { year: pick('year'), month: pick('month'), day: pick('day') }
95
+ }
96
+
97
+ /** Local calendar day in Asia/Shanghai, as `YYYY-MM-DD`. */
98
+ export function localDay(value) {
99
+ const date = toDate(value)
100
+ if (!date) return null
101
+ const { year, month, day } = dayParts(date)
102
+ return `${year}-${month}-${day}`
103
+ }
104
+
105
+ /** Minutes since local midnight in Asia/Shanghai (0–1439). */
106
+ export function localMinutesOfDay(value) {
107
+ const date = toDate(value)
108
+ if (!date) return null
109
+ const parts = TIME_FORMAT.formatToParts(date)
110
+ const pick = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0)
111
+ return (pick('hour') % 24) * 60 + pick('minute')
112
+ }
113
+
114
+ function localDayIndex(day) {
115
+ const [year, month, date] = day.split('-').map(Number)
116
+ return Math.round(Date.UTC(year, month - 1, date) / DAY_MS)
117
+ }
118
+
119
+ function formatLocalDateTime(date) {
120
+ const wall = new Date(date.getTime() + SHANGHAI_OFFSET_MS)
121
+ const pad = (value) => String(value).padStart(2, '0')
122
+ return `${wall.getUTCFullYear()}-${pad(wall.getUTCMonth() + 1)}-${pad(wall.getUTCDate())} ${pad(wall.getUTCHours())}:${pad(wall.getUTCMinutes())}`
123
+ }
124
+
125
+ /** `YYYYMMDDTHHMMSSZ` — the canonical UTC form used by DTSTAMP/DTSTART. */
126
+ export function formatIcsDate(value) {
127
+ const date = requireDate(value, 'date')
128
+ const pad = (number, width = 2) => String(number).padStart(width, '0')
129
+ return (
130
+ `${pad(date.getUTCFullYear(), 4)}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}` +
131
+ `T${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`
132
+ )
133
+ }
134
+
135
+ /**
136
+ * Parse an ICS date-time value. Both `20261114T103000Z` (UTC) and
137
+ * `20261114T183000` (floating, interpreted as Asia/Shanghai) are accepted, as
138
+ * well as ISO-8601 strings and Date objects for convenience.
139
+ */
140
+ export function parseIcsDate(value) {
141
+ return requireDate(value, 'ICS date')
142
+ }
143
+
144
+ /** Escape a value for an iCalendar TEXT field (commas, semicolons, newlines). */
145
+ export function escapeIcsText(value) {
146
+ return String(value ?? '')
147
+ .replace(/\\/g, '\\\\')
148
+ .replace(/\r\n|\r|\n/g, '\\n')
149
+ .replace(/;/g, '\\;')
150
+ .replace(/,/g, '\\,')
151
+ }
152
+
153
+ const OFFSET_PATTERN = /^([+-])(\d+)([dhm])(?:(\d{1,2}):(\d{2}))?$/
154
+ const MAX_OFFSET_DAYS = 3650
155
+ const MAX_OFFSET_HOURS = MAX_OFFSET_DAYS * 24
156
+ const MAX_OFFSET_MINUTES = MAX_OFFSET_HOURS * 60
157
+
158
+ /** Upper bound on per-commitment alarms so a ledger row cannot flood a calendar. */
159
+ export const MAX_REMINDER_OFFSETS = 24
160
+
161
+ const pad2 = (value) => String(value).padStart(2, '0')
162
+
163
+ /**
164
+ * Parse one custom reminder offset relative to the commitment due instant.
165
+ *
166
+ * Accepted grammar (Asia/Shanghai wall clock):
167
+ * - `-1d` / `+2d` — whole local days, same clock time as `dueAt`
168
+ * - `-2h` / `+90m` — hours or minutes relative to `dueAt`
169
+ * - `+0d09:00` — 09:00 on the due day (day shift + wall-clock time)
170
+ * - `-1d08:30` — 08:30 on the day before the due day
171
+ *
172
+ * The sign is mandatory. A time-of-day is only valid together with the `d`
173
+ * unit, and a zero-day time-of-day offset is canonicalised to `+`.
174
+ *
175
+ * @returns {{ offset: string, sign: 1|-1, days: number, hours: number,
176
+ * minutes: number, timeOfDay: { hour: number, minute: number }|null, source: string }}
177
+ */
178
+ export function parseReminderOffset(value) {
179
+ if (typeof value !== 'string') throw new TypeError('reminder offset must be a string')
180
+ const text = value.trim().toLowerCase()
181
+ if (!text) throw new TypeError('reminder offset must not be empty')
182
+ const match = OFFSET_PATTERN.exec(text)
183
+ if (!match) throw new TypeError(`invalid reminder offset: ${String(value)}`)
184
+ const [, rawSign, rawAmount, unit, rawHour, rawMinute] = match
185
+ const amount = Number(rawAmount)
186
+ if (!Number.isSafeInteger(amount)) throw new TypeError(`invalid reminder offset amount: ${String(value)}`)
187
+ let days = 0
188
+ let hours = 0
189
+ let minutes = 0
190
+ if (unit === 'd') {
191
+ days = amount
192
+ if (days > MAX_OFFSET_DAYS) throw new RangeError(`reminder offset too large: ${String(value)}`)
193
+ } else if (unit === 'h') {
194
+ hours = amount
195
+ if (hours > MAX_OFFSET_HOURS) throw new RangeError(`reminder offset too large: ${String(value)}`)
196
+ } else {
197
+ minutes = amount
198
+ if (minutes > MAX_OFFSET_MINUTES) throw new RangeError(`reminder offset too large: ${String(value)}`)
199
+ }
200
+ let timeOfDay = null
201
+ if (rawHour !== undefined) {
202
+ if (unit !== 'd') throw new TypeError(`time-of-day is only valid with a day offset: ${String(value)}`)
203
+ const hour = Number(rawHour)
204
+ const minute = Number(rawMinute)
205
+ if (hour > 23 || minute > 59) throw new RangeError(`invalid reminder offset time: ${String(value)}`)
206
+ timeOfDay = Object.freeze({ hour, minute })
207
+ }
208
+ const sign = rawSign === '-' ? -1 : 1
209
+ const canonicalSign = timeOfDay && days === 0 ? '+' : rawSign
210
+ const offset = timeOfDay
211
+ ? `${canonicalSign}${days}d${pad2(timeOfDay.hour)}:${pad2(timeOfDay.minute)}`
212
+ : unit === 'd'
213
+ ? `${canonicalSign}${days}d`
214
+ : unit === 'h'
215
+ ? `${canonicalSign}${hours}h`
216
+ : `${canonicalSign}${minutes}m`
217
+ return Object.freeze({ offset, sign, days, hours, minutes, timeOfDay, source: String(value) })
218
+ }
219
+
220
+ /**
221
+ * Strictly validate and canonicalise a list of offsets. Invalid input throws;
222
+ * use {@link reminderAlarms} for the lenient rendering path.
223
+ */
224
+ export function normalizeReminderOffsets(value) {
225
+ if (value == null) return []
226
+ if (!Array.isArray(value)) throw new TypeError('reminderOffsets must be an array of offset strings')
227
+ if (value.length > MAX_REMINDER_OFFSETS) {
228
+ throw new RangeError(`too many reminder offsets (max ${MAX_REMINDER_OFFSETS})`)
229
+ }
230
+ const seen = new Set()
231
+ const normalized = []
232
+ for (const entry of value) {
233
+ const parsed = parseReminderOffset(entry)
234
+ if (seen.has(parsed.offset)) continue
235
+ seen.add(parsed.offset)
236
+ normalized.push(parsed.offset)
237
+ }
238
+ return normalized
239
+ }
240
+
241
+ /** Lenient list reader used for rendering: skips invalid entries instead of throwing. */
242
+ function resolveReminderOffsets(value) {
243
+ if (value == null) return []
244
+ let items
245
+ if (Array.isArray(value)) items = value
246
+ else if (typeof value === 'string') items = value.split(',')
247
+ else return []
248
+ const seen = new Set()
249
+ const resolved = []
250
+ for (const item of items.slice(0, MAX_REMINDER_OFFSETS)) {
251
+ try {
252
+ const parsed = parseReminderOffset(item)
253
+ if (seen.has(parsed.offset)) continue
254
+ seen.add(parsed.offset)
255
+ resolved.push(parsed.offset)
256
+ } catch {
257
+ // A single malformed ledger value must not suppress every reminder.
258
+ }
259
+ }
260
+ return resolved
261
+ }
262
+
263
+ /** Human label used inside a VALARM DESCRIPTION. */
264
+ export function describeReminderOffset(value) {
265
+ const parsed = parseReminderOffset(value)
266
+ if (parsed.timeOfDay) {
267
+ const time = `${pad2(parsed.timeOfDay.hour)}:${pad2(parsed.timeOfDay.minute)}`
268
+ if (parsed.days === 0) return `当天 ${time}`
269
+ return `${parsed.sign < 0 ? '提前' : '延后'} ${parsed.days} 天 ${time}`
270
+ }
271
+ if (parsed.days === 0 && parsed.hours === 0 && parsed.minutes === 0) return '到期时'
272
+ const when = parsed.sign < 0 ? '提前' : '延后'
273
+ if (parsed.days) return `${when} ${parsed.days} 天`
274
+ if (parsed.hours) return `${when} ${parsed.hours} 小时`
275
+ return `${when} ${parsed.minutes} 分钟`
276
+ }
277
+
278
+ /**
279
+ * Absolute instant of one alarm: the due instant shifted by `offset`.
280
+ * All wall-clock arithmetic uses Asia/Shanghai (UTC+8, no DST since 1991).
281
+ */
282
+ export function reminderAlarmTime(dueAt, offset) {
283
+ const due = requireDate(dueAt, 'due date')
284
+ const parsed = parseReminderOffset(offset)
285
+ if (parsed.timeOfDay) {
286
+ const wall = new Date(due.getTime() + SHANGHAI_OFFSET_MS)
287
+ const shifted = new Date(
288
+ Date.UTC(
289
+ wall.getUTCFullYear(),
290
+ wall.getUTCMonth(),
291
+ wall.getUTCDate() + parsed.sign * parsed.days,
292
+ parsed.timeOfDay.hour,
293
+ parsed.timeOfDay.minute,
294
+ 0,
295
+ 0,
296
+ ),
297
+ )
298
+ const date = new Date(shifted.getTime() - SHANGHAI_OFFSET_MS)
299
+ if (Number.isNaN(date.getTime())) throw new RangeError(`invalid reminder offset: ${String(offset)}`)
300
+ return date
301
+ }
302
+ const deltaMs = parsed.sign * (parsed.days * 24 * 60 + parsed.hours * 60 + parsed.minutes) * 60_000
303
+ const date = new Date(due.getTime() + deltaMs)
304
+ if (Number.isNaN(date.getTime())) throw new RangeError(`invalid reminder offset: ${String(offset)}`)
305
+ return date
306
+ }
307
+
308
+ /**
309
+ * Build the VALARM instants for a due date. Duplicate instants collapse so the
310
+ * same calendar reminder is never emitted twice; output is chronological.
311
+ *
312
+ * @returns {Array<{ offset: string, at: Date, label: string }>}
313
+ */
314
+ export function reminderAlarms(dueAt, offsets) {
315
+ const normalized = resolveReminderOffsets(offsets)
316
+ const seen = new Set()
317
+ const alarms = []
318
+ for (const offset of normalized) {
319
+ const at = reminderAlarmTime(dueAt, offset)
320
+ const key = String(at.getTime())
321
+ if (seen.has(key)) continue
322
+ seen.add(key)
323
+ alarms.push({ offset, at, label: describeReminderOffset(offset) })
324
+ }
325
+ return alarms.sort((left, right) => left.at.getTime() - right.at.getTime() || left.offset.localeCompare(right.offset))
326
+ }
327
+
328
+ function rule(id, description, test) {
329
+ return Object.freeze({ id, description, test })
330
+ }
331
+
332
+ /**
333
+ * Rule ids required by the E1 contract:
334
+ * due-1d, due-today-09, due-today-18, overdue-daily, snooze-wake.
335
+ * `upcoming` is an additional advance rule so the `upcoming` bucket is
336
+ * reachable; it is the only rule added on top of the required list.
337
+ */
338
+ export const SNOOZE_WAKE_RULE = rule(
339
+ 'snooze-wake',
340
+ 'Fire once the stored snooze has expired.',
341
+ (context) => context.snoozeExpired === true,
342
+ )
343
+
344
+ export const DEFAULT_RULES = Object.freeze([
345
+ rule('due-1d', 'Remind one local day before the due date.', (context) => context.bucket === 'due-1d'),
346
+ rule(
347
+ 'due-today-09',
348
+ 'Remind on the due day from 09:00 local time.',
349
+ (context) => context.bucket === 'due-today' && context.minutesOfDay >= 9 * 60,
350
+ ),
351
+ rule(
352
+ 'due-today-18',
353
+ 'Remind on the due day from 18:00 local time.',
354
+ (context) => context.bucket === 'due-today' && context.minutesOfDay >= 18 * 60,
355
+ ),
356
+ rule('overdue-daily', 'Remind every local day while the commitment is overdue.', (context) => context.bucket === 'overdue'),
357
+ rule('upcoming', 'Advance reminder for commitments due later in the horizon.', (context) => context.bucket === 'upcoming'),
358
+ SNOOZE_WAKE_RULE,
359
+ ])
360
+
361
+ export const ALL_RULES = DEFAULT_RULES
362
+
363
+ const RULES_BY_ID = new Map(DEFAULT_RULES.map((entry) => [entry.id, entry]))
364
+
365
+ function resolveRule(candidate) {
366
+ if (typeof candidate === 'string') {
367
+ const known = RULES_BY_ID.get(candidate)
368
+ if (!known) throw new TypeError(`unknown reminder rule: ${candidate}`)
369
+ return known
370
+ }
371
+ if (!candidate || typeof candidate !== 'object' || typeof candidate.id !== 'string') {
372
+ throw new TypeError('reminder rules must be rule ids or { id, test } objects')
373
+ }
374
+ return candidate
375
+ }
376
+
377
+ function evaluateRule(def, context) {
378
+ let outcome
379
+ if (typeof def.test === 'function') outcome = def.test(context)
380
+ else if (typeof def.when === 'function') outcome = def.when(context)
381
+ else {
382
+ const known = RULES_BY_ID.get(def.id)
383
+ outcome = known && typeof known.test === 'function' ? known.test(context) : false
384
+ }
385
+ if (!outcome) return null
386
+ if (outcome === true) outcome = {}
387
+ if (typeof outcome !== 'object') return null
388
+ const bucket = outcome.bucket ?? def.bucket ?? context.bucket
389
+ const level = outcome.level ?? def.level ?? context.level
390
+ if (!BUCKETS.has(bucket)) throw new TypeError(`reminder rule ${def.id} produced unknown bucket: ${String(bucket)}`)
391
+ if (!LEVELS.has(level)) throw new TypeError(`reminder rule ${def.id} produced unknown level: ${String(level)}`)
392
+ return { bucket, level, ruleId: def.id }
393
+ }
394
+
395
+ function levelFor(bucket, due, now, allowL3) {
396
+ if (bucket === 'overdue') {
397
+ return allowL3 && now.getTime() - due.getTime() > DAY_MS ? 'L3' : 'L2'
398
+ }
399
+ if (bucket === 'due-today') return 'L2'
400
+ return 'L1'
401
+ }
402
+
403
+ function bucketFor(dayOffset) {
404
+ if (dayOffset < 0) return 'overdue'
405
+ if (dayOffset === 0) return 'due-today'
406
+ if (dayOffset === 1) return 'due-1d'
407
+ return 'upcoming'
408
+ }
409
+
410
+ /** Read a snooze deadline from injected state first, then commitment fields. */
411
+ function readSnoozeUntil(commitment, options, ledger) {
412
+ const sources = []
413
+ const injected = options.snoozedUntil
414
+ if (injected instanceof Map) {
415
+ sources.push(injected.get(commitment.id))
416
+ } else if (typeof injected === 'function') {
417
+ sources.push(injected(commitment))
418
+ } else if (injected && typeof injected === 'object') {
419
+ sources.push(injected[commitment.id])
420
+ sources.push(injected[`snooze:${commitment.id}`])
421
+ }
422
+ for (const key of ['snoozedUntil', 'snoozeUntil', 'snoozeAt']) sources.push(commitment[key])
423
+ const meta = commitment.meta
424
+ if (meta && typeof meta === 'object') {
425
+ for (const key of ['snoozedUntil', 'snoozeUntil', `snooze:${commitment.id}`]) sources.push(meta[key])
426
+ if (typeof meta.get === 'function') sources.push(meta.get(`snooze:${commitment.id}`))
427
+ }
428
+ // Optional duck-typed store hook; never required, never SQLite-specific.
429
+ if (ledger && typeof ledger.getMeta === 'function') {
430
+ try {
431
+ sources.push(ledger.getMeta(`snooze:${commitment.id}`))
432
+ } catch {
433
+ // A read-only or closed store must not break planning.
434
+ }
435
+ }
436
+ for (const source of sources) {
437
+ if (source == null) continue
438
+ const date = toDate(source)
439
+ if (date) return date
440
+ }
441
+ return null
442
+ }
443
+
444
+ /**
445
+ * Resolve reminder offsets for one commitment. Priority: injected per-id state
446
+ * (Map/object/function, mirroring snoozes), the commitment field itself, any
447
+ * commitment meta hook, a duck-typed ledger `getMeta`, then the caller's global
448
+ * default. Invalid entries are skipped so one bad ledger row cannot hide every
449
+ * reminder.
450
+ */
451
+ function readReminderOffsets(commitment, options, ledger) {
452
+ const meta = commitment.meta
453
+ const injected = options.reminderOffsets
454
+ const sources = []
455
+ if (injected instanceof Map) {
456
+ sources.push(injected.get(commitment.id))
457
+ sources.push(injected.get(`reminderOffsets:${commitment.id}`))
458
+ } else if (typeof injected === 'function') {
459
+ sources.push(injected(commitment))
460
+ } else if (injected && typeof injected === 'object') {
461
+ sources.push(injected[commitment.id])
462
+ sources.push(injected[`reminderOffsets:${commitment.id}`])
463
+ }
464
+ sources.push(commitment.reminderOffsets)
465
+ if (meta && typeof meta === 'object') {
466
+ sources.push(meta.reminderOffsets)
467
+ sources.push(meta[`reminderOffsets:${commitment.id}`])
468
+ if (typeof meta.get === 'function') sources.push(meta.get(`reminderOffsets:${commitment.id}`))
469
+ }
470
+ // Optional duck-typed store hook; never required, never SQLite-specific.
471
+ if (ledger && typeof ledger.getMeta === 'function') {
472
+ try {
473
+ sources.push(ledger.getMeta(`reminderOffsets:${commitment.id}`))
474
+ } catch {
475
+ // A read-only or closed store must not break planning.
476
+ }
477
+ }
478
+ for (const source of sources) {
479
+ const resolved = resolveReminderOffsets(source)
480
+ if (resolved.length) return resolved
481
+ }
482
+ return resolveReminderOffsets(options.defaultReminderOffsets)
483
+ }
484
+
485
+ function outputDueAt(value) {
486
+ if (typeof value === 'string') return value
487
+ const date = toDate(value)
488
+ return date ? date.toISOString() : String(value)
489
+ }
490
+
491
+ /**
492
+ * Build the reminders that are due at `now`.
493
+ *
494
+ * @param {{ listCommitments: () => Array<object> }} ledger Any object with
495
+ * `listCommitments()`; the core `Ledger` works, and no SQLite is involved.
496
+ * @param {object} [options]
497
+ * @param {Date|string|number} [options.now] Injected current instant.
498
+ * @param {number} [options.horizonDays=7] Future horizon in local days.
499
+ * @param {boolean} [options.allowL3=false] Enable L3 for severely overdue items.
500
+ * @param {Array<object|string>} [options.rules] Rule descriptors or ids.
501
+ * @param {Map|object|Function} [options.snoozedUntil] Per-commitment snooze
502
+ * deadlines, keyed by commitment id; future deadlines suppress reminders.
503
+ * @param {Map|object|Function} [options.reminderOffsets] Injected
504
+ * per-commitment offsets (same keying as `snoozedUntil`). Injected values
505
+ * are checked before the commitment's own `reminderOffsets` field.
506
+ * @param {string[]} [options.defaultReminderOffsets] Global offsets applied
507
+ * when a commitment has neither its own nor an injected list.
508
+ * @returns {Array<{ commitmentId: string, action: string, dueAt: string,
509
+ * bucket: 'overdue'|'due-today'|'due-1d'|'upcoming',
510
+ * level: 'L1'|'L2'|'L3', ruleId: string, reminderOffsets?: string[] }>}
511
+ */
512
+ export function buildReminders(ledger, options = {}) {
513
+ if (!ledger || typeof ledger.listCommitments !== 'function') {
514
+ throw new TypeError('buildReminders requires a ledger with listCommitments()')
515
+ }
516
+ const opts = options ?? {}
517
+ const now = requireNow(opts.now)
518
+ const horizonDays = Number.isFinite(opts.horizonDays) && opts.horizonDays >= 0 ? opts.horizonDays : DEFAULT_HORIZON_DAYS
519
+ const allowL3 = opts.allowL3 === true
520
+ const rules = (opts.rules ?? DEFAULT_RULES).map(resolveRule)
521
+ const commitments = ledger.listCommitments()
522
+ if (!Array.isArray(commitments)) throw new TypeError('ledger.listCommitments() must return an array')
523
+
524
+ const today = localDay(now)
525
+ const todayIndex = localDayIndex(today)
526
+ const minutesOfDay = localMinutesOfDay(now)
527
+ const seen = new Set()
528
+ const reminders = []
529
+
530
+ for (const commitment of commitments) {
531
+ if (!commitment || typeof commitment !== 'object') continue
532
+ if (!commitment.id) continue
533
+ if (commitment.status === 'done' || commitment.status === 'dropped') continue
534
+ if (commitment.dueAt == null || commitment.dueAt === '') continue
535
+ const due = toDate(commitment.dueAt)
536
+ if (!due) continue
537
+
538
+ const snoozeUntil = readSnoozeUntil(commitment, opts, ledger)
539
+ // An active snooze hides the commitment; once it expires the commitment
540
+ // becomes visible again and the snooze-wake rule fires.
541
+ if (snoozeUntil && snoozeUntil.getTime() > now.getTime()) continue
542
+ const snoozeExpired = Boolean(snoozeUntil)
543
+ const reminderOffsets = readReminderOffsets(commitment, opts, ledger)
544
+
545
+ const dueDay = localDay(due)
546
+ const dayOffset = localDayIndex(dueDay) - todayIndex
547
+ if (dayOffset > horizonDays) continue
548
+
549
+ const bucket = bucketFor(dayOffset)
550
+ const level = levelFor(bucket, due, now, allowL3)
551
+ const context = {
552
+ commitment,
553
+ due,
554
+ now,
555
+ bucket,
556
+ level,
557
+ dayOffset,
558
+ dueDay,
559
+ localDay: today,
560
+ minutesOfDay,
561
+ snoozeUntil,
562
+ snoozeExpired,
563
+ }
564
+
565
+ for (const def of rules) {
566
+ const result = evaluateRule(def, context)
567
+ if (!result) continue
568
+ const key = `${commitment.id}|${result.bucket}|${result.ruleId}|${today}`
569
+ if (seen.has(key)) continue
570
+ seen.add(key)
571
+ reminders.push({
572
+ commitmentId: commitment.id,
573
+ action: commitment.action ?? '',
574
+ dueAt: outputDueAt(commitment.dueAt),
575
+ bucket: result.bucket,
576
+ level: result.level,
577
+ ruleId: result.ruleId,
578
+ // Only present when customised: pre-0.2.0 reminder objects keep their
579
+ // exact shape and toIcs falls back to the legacy relative alarms.
580
+ ...(reminderOffsets.length ? { reminderOffsets } : {}),
581
+ })
582
+ }
583
+ }
584
+
585
+ const dueTime = (reminder) => toDate(reminder.dueAt)?.getTime() ?? 0
586
+ reminders.sort(
587
+ (left, right) =>
588
+ dueTime(left) - dueTime(right) ||
589
+ left.commitmentId.localeCompare(right.commitmentId) ||
590
+ left.ruleId.localeCompare(right.ruleId),
591
+ )
592
+ return reminders
593
+ }
594
+
595
+ /**
596
+ * Render reminders as an RFC5545 calendar.
597
+ *
598
+ * Only the commitment title, due instant and stable UID are exported — never
599
+ * the creditor, matter, evidence or any other ledger field.
600
+ *
601
+ * @param {Array<object>} reminders Output of {@link buildReminders}.
602
+ * @param {object} [options]
603
+ * @param {Date|string|number} [options.now] DTSTAMP instant.
604
+ * @param {string} [options.uidPrefix='advisers']
605
+ * @param {string[]} [options.reminderOffsets] Fallback custom offsets for
606
+ * reminders that do not carry their own `reminderOffsets`.
607
+ * @returns {string} CRLF-terminated iCalendar text.
608
+ */
609
+ const legacyAlarmLines = (title) => [
610
+ 'BEGIN:VALARM',
611
+ 'TRIGGER:-P1D',
612
+ 'ACTION:DISPLAY',
613
+ `DESCRIPTION:${escapeIcsText(`提醒:${title}(1 天前)`)}`,
614
+ 'END:VALARM',
615
+ 'BEGIN:VALARM',
616
+ 'TRIGGER:-PT1H',
617
+ 'ACTION:DISPLAY',
618
+ `DESCRIPTION:${escapeIcsText(`提醒:${title}(1 小时前)`)}`,
619
+ 'END:VALARM',
620
+ ]
621
+
622
+ /**
623
+ * VALARM lines for one event. Custom offsets become **absolute** DATE-TIME
624
+ * triggers computed in Asia/Shanghai (RFC5545 requires VALUE=DATE-TIME when
625
+ * TRIGGER is absolute) and one VALARM is emitted per rule. With no offsets the
626
+ * pre-0.2.0 relative defaults (-P1D, -PT1H) are preserved byte-for-byte.
627
+ */
628
+ function alarmLines(reminder, due, title, options) {
629
+ const configured = reminder.reminderOffsets ?? options.reminderOffsets
630
+ const alarms = reminderAlarms(due, configured)
631
+ if (!alarms.length) return legacyAlarmLines(title)
632
+ return alarms.flatMap((alarm) => [
633
+ 'BEGIN:VALARM',
634
+ `TRIGGER;VALUE=DATE-TIME:${formatIcsDate(alarm.at)}`,
635
+ 'ACTION:DISPLAY',
636
+ `DESCRIPTION:${escapeIcsText(`提醒:${title}(${alarm.label})`)}`,
637
+ 'END:VALARM',
638
+ ])
639
+ }
640
+
641
+ export function toIcs(reminders, options = {}) {
642
+ if (!Array.isArray(reminders)) throw new TypeError('toIcs requires an array of reminders')
643
+ const opts = options ?? {}
644
+ const now = requireNow(opts.now)
645
+ const rawPrefix = opts.uidPrefix == null ? '' : String(opts.uidPrefix)
646
+ const uidPrefix = (rawPrefix || 'advisers').replace(/[\r\n]/g, '')
647
+
648
+ const lines = [
649
+ 'BEGIN:VCALENDAR',
650
+ 'VERSION:2.0',
651
+ 'PRODID:-//Advisers//E1 Reminders//EN',
652
+ 'CALSCALE:GREGORIAN',
653
+ ]
654
+ const seenUids = new Set()
655
+
656
+ for (const reminder of reminders) {
657
+ if (!reminder || typeof reminder !== 'object') {
658
+ throw new TypeError('toIcs received a non-object reminder')
659
+ }
660
+ if (reminder.commitmentId == null || reminder.dueAt == null) {
661
+ throw new TypeError('toIcs reminders require commitmentId and dueAt')
662
+ }
663
+ const due = toDate(reminder.dueAt)
664
+ if (!due) throw new RangeError(`invalid reminder dueAt: ${String(reminder.dueAt)}`)
665
+ const dueAt = outputDueAt(reminder.dueAt)
666
+ // A commitment can collect several nudges on the same day (e.g. 09:00 and
667
+ // 18:00); the calendar carries one stable event per commitment instant.
668
+ const uid = `${uidPrefix}-${String(reminder.commitmentId)}-${dueAt}`.replace(/[\r\n]/g, '')
669
+ if (seenUids.has(uid)) continue
670
+ seenUids.add(uid)
671
+
672
+ const title = String(reminder.action ?? '')
673
+ const localDue = formatLocalDateTime(due)
674
+ lines.push(
675
+ 'BEGIN:VEVENT',
676
+ `UID:${uid}`,
677
+ `DTSTAMP:${formatIcsDate(now)}`,
678
+ `DTSTART:${formatIcsDate(due)}`,
679
+ `SUMMARY:${escapeIcsText(title)}`,
680
+ `DESCRIPTION:${escapeIcsText(`到期:${localDue}(${TIME_ZONE})`)}`,
681
+ ...alarmLines(reminder, due, title, opts),
682
+ 'END:VEVENT',
683
+ )
684
+ }
685
+
686
+ lines.push('END:VCALENDAR')
687
+ return `${lines.join('\r\n')}\r\n`
688
+ }
689
+
690
+ export { DAY_MS, SHANGHAI_OFFSET_MS }