advisers 0.3.1 → 0.4.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.
- package/README-zh.md +13 -15
- package/README.md +32 -22
- package/THIRD-PARTY-NOTICES.md +1 -1
- package/bin/advisers.js +2769 -183
- package/index.js +1 -1
- package/lib/brief-archive.js +267 -0
- package/lib/client-pack.js +1016 -0
- package/lib/consent.js +390 -0
- package/lib/credentials.js +195 -0
- package/lib/customer-read.js +524 -0
- package/lib/error-codes.js +516 -7
- package/lib/evidence.js +928 -120
- package/lib/kb-extract.js +626 -0
- package/lib/kb-facts.js +429 -0
- package/lib/kb-pages.js +1084 -0
- package/lib/kb.js +1036 -0
- package/lib/ledger-read.js +109 -1
- package/lib/mail-errors.js +46 -0
- package/lib/mail-extract.js +351 -0
- package/lib/mail-imap.js +446 -0
- package/lib/mail-import.js +176 -0
- package/lib/mail-parse.js +223 -0
- package/lib/mail-store.js +731 -0
- package/lib/mail.js +506 -0
- package/lib/mcp-server.js +397 -11
- package/lib/notify.js +265 -7
- package/lib/policy/decision.js +315 -0
- package/lib/policy/egress.js +268 -0
- package/lib/policy/errors.js +71 -0
- package/lib/policy/index.js +99 -0
- package/lib/policy/rules.js +468 -0
- package/lib/policy/surfaces.js +141 -0
- package/lib/receipt-verify.js +283 -26
- package/lib/receivables.js +1653 -0
- package/lib/scheduler.js +453 -9
- package/lib/shell.js +1406 -0
- package/lib/source.js +98 -3
- package/lib/sqlite.js +501 -49
- package/lib/tos/index.js +2 -2
- package/lib/tos/manifest.json +6 -6
- package/lib/tos/privacy.zh-CN.md +33 -20
- package/lib/tos/safety.zh-CN.md +7 -6
- package/lib/tos/summary.zh-CN.md +3 -2
- package/lib/tos/terms.zh-CN.md +31 -16
- package/lib/tui/labels.js +1 -1
- package/lib/tui/render.js +1 -1
- package/lib/urgency.js +467 -0
- package/package.json +4 -4
package/lib/urgency.js
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proactive 0.4 — deterministic urgency v1.
|
|
3
|
+
*
|
|
4
|
+
* Pure module: no SQLite, no network, no filesystem, no model. When `now` is
|
|
5
|
+
* injected the output is a pure function of (items, now, timezone): the same
|
|
6
|
+
* input always produces byte-identical JSON. Scores are an explainable
|
|
7
|
+
* ordering aid, never a priority verdict: `score` is exactly the sum of the
|
|
8
|
+
* named `terms`, each term carries its own Chinese explanation, and `whyNow`
|
|
9
|
+
* is the joined explanation (capped at 200 code points).
|
|
10
|
+
*
|
|
11
|
+
* The `max 3` rule lives only in human priority views (`selectTopUrgent`, default
|
|
12
|
+
* MAX_HUMAN_TOP = 3). Urgency is derived at read time and never enters
|
|
13
|
+
* `dataSha256` (that hash covers the source brief data only). Bump
|
|
14
|
+
* MODEL_VERSION when any weight or threshold in this file changes.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** Frozen model version for the v1 term table. */
|
|
18
|
+
export const MODEL_VERSION = 1
|
|
19
|
+
/** Local-day reference used by every reminder/agenda view (no host-TZ reads). */
|
|
20
|
+
export const DEFAULT_TIMEZONE = 'Asia/Shanghai'
|
|
21
|
+
/** Human priority views show at most this many entries. */
|
|
22
|
+
export const MAX_HUMAN_TOP = 3
|
|
23
|
+
/** Score bands, low to critical (stable contract for callers). */
|
|
24
|
+
export const URGENCY_LEVELS = Object.freeze(['low', 'medium', 'high', 'critical'])
|
|
25
|
+
/** Canonical term order (also the deterministic tie-break for topFactors). */
|
|
26
|
+
export const TERM_IDS = Object.freeze(['overdue', 'due_today', 'due_near', 'third', 'mine', 'remind_offsets', 'age', 'timed'])
|
|
27
|
+
|
|
28
|
+
const DAY_MS = 86400000
|
|
29
|
+
/** Asia/Shanghai has been UTC+8 without DST since 1991 (same constant as remind.js). */
|
|
30
|
+
const SHANGHAI_OFFSET_MS = 8 * 3600000
|
|
31
|
+
const MAX_WHY_NOW_CHARS = 200
|
|
32
|
+
const MAX_DAYS_LOOKAHEAD = 7
|
|
33
|
+
|
|
34
|
+
const DATE_ONLY_RE = /^(\d{4})-(\d{2})-(\d{2})$/
|
|
35
|
+
const LOCAL_DATE_TIME_RE = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/
|
|
36
|
+
|
|
37
|
+
const EXCLUDED_STATUSES = new Set(['done', 'dropped', 'snoozed'])
|
|
38
|
+
const TZ_DAY_FORMATTERS = new Map()
|
|
39
|
+
const TZ_PARTS_FORMATTERS = new Map()
|
|
40
|
+
|
|
41
|
+
const clampScore = (value) => Math.max(0, Math.min(100, value))
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Map a 0..100 score to its band. Exported so the CLI and tests agree with the
|
|
45
|
+
* term table instead of duplicating thresholds.
|
|
46
|
+
* @param {number} score
|
|
47
|
+
* @returns {'low'|'medium'|'high'|'critical'}
|
|
48
|
+
*/
|
|
49
|
+
export function levelForScore(score) {
|
|
50
|
+
const value = Number.isFinite(score) ? clampScore(score) : 0
|
|
51
|
+
if (value < 25) return 'low'
|
|
52
|
+
if (value < 50) return 'medium'
|
|
53
|
+
if (value < 75) return 'high'
|
|
54
|
+
return 'critical'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function resolveTimezone(timezone) {
|
|
58
|
+
const text = timezone === undefined || timezone === null || timezone === '' ? DEFAULT_TIMEZONE : String(timezone).trim()
|
|
59
|
+
if (!text) throw new RangeError('invalid timezone: empty value')
|
|
60
|
+
if (text !== DEFAULT_TIMEZONE && !TZ_DAY_FORMATTERS.has(text)) {
|
|
61
|
+
try {
|
|
62
|
+
TZ_DAY_FORMATTERS.set(text, new Intl.DateTimeFormat('en-US', { timeZone: text, year: 'numeric', month: '2-digit', day: '2-digit' }))
|
|
63
|
+
TZ_PARTS_FORMATTERS.set(text, new Intl.DateTimeFormat('en-US', {
|
|
64
|
+
timeZone: text, year: 'numeric', month: '2-digit', day: '2-digit',
|
|
65
|
+
hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
|
|
66
|
+
}))
|
|
67
|
+
} catch {
|
|
68
|
+
throw new RangeError('invalid timezone: ' + String(timezone))
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return text
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function toDate(value) {
|
|
75
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : new Date(value.getTime())
|
|
76
|
+
if (typeof value === 'number') return Number.isFinite(value) ? new Date(value) : null
|
|
77
|
+
if (typeof value !== 'string') return null
|
|
78
|
+
const text = value.trim()
|
|
79
|
+
if (!text) return null
|
|
80
|
+
const ms = Date.parse(text)
|
|
81
|
+
return Number.isNaN(ms) ? null : new Date(ms)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function resolveNow(value) {
|
|
85
|
+
if (value === undefined || value === null) return new Date()
|
|
86
|
+
const date = toDate(value)
|
|
87
|
+
if (!date) throw new RangeError('invalid now: ' + String(value))
|
|
88
|
+
return date
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function pad2(value) {
|
|
92
|
+
return String(value).padStart(2, '0')
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function dayString(year, month, day) {
|
|
96
|
+
return String(year).padStart(4, '0') + '-' + pad2(month) + '-' + pad2(day)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function validCalendarDay(year, month, day) {
|
|
100
|
+
if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day)) return false
|
|
101
|
+
if (year < 1000 || year > 9999 || month < 1 || month > 12 || day < 1 || day > 31) return false
|
|
102
|
+
const probe = new Date(Date.UTC(year, month - 1, day))
|
|
103
|
+
return probe.getUTCFullYear() === year && probe.getUTCMonth() === month - 1 && probe.getUTCDate() === day
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function localDayIndex(day) {
|
|
107
|
+
const parts = String(day).split('-').map(Number)
|
|
108
|
+
return Math.round(Date.UTC(parts[0], parts[1] - 1, parts[2]) / DAY_MS)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Local calendar day (YYYY-MM-DD) of an instant in `timezone`. */
|
|
112
|
+
export function localDayOfInstant(ms, timezone = DEFAULT_TIMEZONE) {
|
|
113
|
+
const tz = resolveTimezone(timezone)
|
|
114
|
+
if (tz === DEFAULT_TIMEZONE) {
|
|
115
|
+
const wall = new Date(ms + SHANGHAI_OFFSET_MS)
|
|
116
|
+
return dayString(wall.getUTCFullYear(), wall.getUTCMonth() + 1, wall.getUTCDate())
|
|
117
|
+
}
|
|
118
|
+
const parts = TZ_DAY_FORMATTERS.get(tz).formatToParts(new Date(ms))
|
|
119
|
+
const pick = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0)
|
|
120
|
+
return dayString(pick('year'), pick('month'), pick('day'))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function zoneOffsetMs(instantMs, timezone) {
|
|
124
|
+
if (timezone === DEFAULT_TIMEZONE) return SHANGHAI_OFFSET_MS
|
|
125
|
+
const parts = TZ_PARTS_FORMATTERS.get(timezone).formatToParts(new Date(instantMs))
|
|
126
|
+
const pick = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0)
|
|
127
|
+
const wholeSecond = Math.floor(instantMs / 1000) * 1000
|
|
128
|
+
return Date.UTC(pick('year'), pick('month') - 1, pick('day'), pick('hour'), pick('minute'), pick('second')) - wholeSecond
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Convert a wall-clock reading in `timezone` to an absolute instant (ms). */
|
|
132
|
+
function zonedWallMs(year, month, day, hour, minute, second, millisecond, timezone) {
|
|
133
|
+
const wallUtc = Date.UTC(year, month - 1, day, hour, minute, second, millisecond)
|
|
134
|
+
if (!Number.isFinite(wallUtc)) return null
|
|
135
|
+
if (timezone === DEFAULT_TIMEZONE) return wallUtc - SHANGHAI_OFFSET_MS
|
|
136
|
+
let instant = wallUtc
|
|
137
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
138
|
+
const next = wallUtc - zoneOffsetMs(instant, timezone)
|
|
139
|
+
if (next === instant) break
|
|
140
|
+
instant = next
|
|
141
|
+
}
|
|
142
|
+
return instant
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function parseClock(match) {
|
|
146
|
+
const [, year, month, day, hour, minute, second = '0', fraction = '0'] = match
|
|
147
|
+
const y = Number(year)
|
|
148
|
+
const mo = Number(month)
|
|
149
|
+
const d = Number(day)
|
|
150
|
+
const h = Number(hour)
|
|
151
|
+
const mi = Number(minute)
|
|
152
|
+
const s = Number(second)
|
|
153
|
+
const ms = Number(fraction.padEnd(3, '0'))
|
|
154
|
+
if (!validCalendarDay(y, mo, d)) return null
|
|
155
|
+
if (h > 23 || mi > 59 || s > 59) return null
|
|
156
|
+
return { y, mo, d, h, mi, s, ms }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Resolve a due value to an absolute instant. Mirrors the agenda view:
|
|
161
|
+
* - `YYYY-MM-DD` means end of that local day (23:59:59.999);
|
|
162
|
+
* - an ISO/wall-clock string without a zone is read in `timezone`;
|
|
163
|
+
* - a value with a zone is its absolute instant.
|
|
164
|
+
* Returns `{ ms, dateOnly }` or null for dirty data (never throws).
|
|
165
|
+
*/
|
|
166
|
+
export function parseDueValue(value, timezone = DEFAULT_TIMEZONE) {
|
|
167
|
+
const tz = resolveTimezone(timezone)
|
|
168
|
+
if (value instanceof Date || typeof value === 'number') {
|
|
169
|
+
const date = toDate(value)
|
|
170
|
+
return date ? { ms: date.getTime(), dateOnly: false } : null
|
|
171
|
+
}
|
|
172
|
+
if (typeof value !== 'string') return null
|
|
173
|
+
const text = value.trim()
|
|
174
|
+
if (!text) return null
|
|
175
|
+
const dateOnly = DATE_ONLY_RE.exec(text)
|
|
176
|
+
if (dateOnly) {
|
|
177
|
+
const clock = parseClock(['', dateOnly[1], dateOnly[2], dateOnly[3], '00', '00'])
|
|
178
|
+
if (!clock) return null
|
|
179
|
+
const ms = zonedWallMs(clock.y, clock.mo, clock.d, 23, 59, 59, 999, tz)
|
|
180
|
+
return Number.isFinite(ms) ? { ms, dateOnly: true } : null
|
|
181
|
+
}
|
|
182
|
+
const wallClock = LOCAL_DATE_TIME_RE.exec(text)
|
|
183
|
+
if (wallClock) {
|
|
184
|
+
const clock = parseClock(wallClock)
|
|
185
|
+
if (!clock) return null
|
|
186
|
+
const ms = zonedWallMs(clock.y, clock.mo, clock.d, clock.h, clock.mi, clock.s, clock.ms, tz)
|
|
187
|
+
return Number.isFinite(ms) ? { ms, dateOnly: false } : null
|
|
188
|
+
}
|
|
189
|
+
const parsed = Date.parse(text)
|
|
190
|
+
return Number.isFinite(parsed) ? { ms: parsed, dateOnly: false } : null
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function term(id, contribution, explain) {
|
|
194
|
+
return { id, contribution, explain }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Keep `whyNow` deterministic and bounded: join explanations, then cap at 200
|
|
199
|
+
* Unicode code points (never split a surrogate pair).
|
|
200
|
+
*
|
|
201
|
+
* @param {Array<{explain?: string}>|{terms?: Array<{explain?: string}>}} terms
|
|
202
|
+
* @returns {string}
|
|
203
|
+
*/
|
|
204
|
+
export function describeWhyNow(terms) {
|
|
205
|
+
const list = Array.isArray(terms) ? terms : (terms && Array.isArray(terms.terms) ? terms.terms : [])
|
|
206
|
+
const text = list
|
|
207
|
+
.filter((entry) => entry && typeof entry.explain === 'string' && entry.explain)
|
|
208
|
+
.map((entry) => entry.explain)
|
|
209
|
+
.join(' · ')
|
|
210
|
+
return Array.from(text).slice(0, MAX_WHY_NOW_CHARS).join('')
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function neutralScore({ id = null, excluded = false, degraded = null } = {}) {
|
|
214
|
+
return {
|
|
215
|
+
id,
|
|
216
|
+
modelVersion: MODEL_VERSION,
|
|
217
|
+
score: 0,
|
|
218
|
+
level: 'low',
|
|
219
|
+
terms: [],
|
|
220
|
+
topFactors: [],
|
|
221
|
+
whyNow: '',
|
|
222
|
+
dueAt: null,
|
|
223
|
+
excluded,
|
|
224
|
+
degraded,
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function normalizeItem(item, timezone, records) {
|
|
229
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) return null
|
|
230
|
+
const rawId = item.id ?? item.commitmentId ?? null
|
|
231
|
+
const id = rawId === null || rawId === undefined ? null : String(rawId)
|
|
232
|
+
// Derived views (agenda/morning items) drop ledger-only fields; an optional
|
|
233
|
+
// `records` lookup restores debtor/createdAt/offsets without changing the
|
|
234
|
+
// item's JSON shape. Item-level fields always win.
|
|
235
|
+
const record = lookupRecord(records, id)
|
|
236
|
+
const status = typeof item.status === 'string' ? item.status : (typeof record?.status === 'string' ? record.status : null)
|
|
237
|
+
const dueValue = item.at ?? item.dueAt ?? item.due ?? record?.dueAt ?? null
|
|
238
|
+
const due = parseDueValue(dueValue, timezone)
|
|
239
|
+
const forcedAllDay = item.allDay === true ? true : item.allDay === false ? false : null
|
|
240
|
+
const dateOnly = forcedAllDay === null ? Boolean(due && due.dateOnly) : forcedAllDay
|
|
241
|
+
const debtor = typeof item.debtor === 'string'
|
|
242
|
+
? item.debtor
|
|
243
|
+
: (item.meta && typeof item.meta.debtor === 'string'
|
|
244
|
+
? item.meta.debtor
|
|
245
|
+
: (typeof record?.debtor === 'string' ? record.debtor : null))
|
|
246
|
+
const rawCreatedAt = item.createdAt ?? item.created_at ?? item.created ?? record?.createdAt ?? record?.created_at ?? null
|
|
247
|
+
const createdAt = parseDueValue(rawCreatedAt, timezone)
|
|
248
|
+
const offsets = Array.isArray(item.reminderOffsets)
|
|
249
|
+
? item.reminderOffsets
|
|
250
|
+
: Array.isArray(item.reminder_offsets)
|
|
251
|
+
? item.reminder_offsets
|
|
252
|
+
: (Array.isArray(record?.reminderOffsets) ? record.reminderOffsets : [])
|
|
253
|
+
return {
|
|
254
|
+
id,
|
|
255
|
+
status,
|
|
256
|
+
due,
|
|
257
|
+
dateOnly,
|
|
258
|
+
debtor,
|
|
259
|
+
createdAt,
|
|
260
|
+
reminderOffsetsCount: offsets.length,
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function scoreNormalized(normalized, context) {
|
|
265
|
+
if (!normalized) return neutralScore({ degraded: 'urgency_failed' })
|
|
266
|
+
if (EXCLUDED_STATUSES.has(normalized.status)) return neutralScore({ id: normalized.id, excluded: true })
|
|
267
|
+
if (!normalized.due) return neutralScore({ id: normalized.id, degraded: 'urgency_failed' })
|
|
268
|
+
const { timezone, nowMs, todayIndex } = context
|
|
269
|
+
const dueMs = normalized.due.ms
|
|
270
|
+
const dueDay = localDayOfInstant(dueMs, timezone)
|
|
271
|
+
const dueIndex = localDayIndex(dueDay)
|
|
272
|
+
const dayOffset = dueIndex - todayIndex
|
|
273
|
+
const terms = []
|
|
274
|
+
if (dueMs < nowMs) {
|
|
275
|
+
const overdueDays = Math.max(0, todayIndex - dueIndex)
|
|
276
|
+
terms.push(term('overdue', Math.min(50, 30 + 2 * overdueDays), overdueDays > 0 ? '逾期 ' + overdueDays + ' 天' : '今天已到期'))
|
|
277
|
+
} else if (dayOffset === 0) {
|
|
278
|
+
terms.push(term('due_today', 30, '今天到期'))
|
|
279
|
+
} else if (dayOffset >= 1 && dayOffset <= MAX_DAYS_LOOKAHEAD) {
|
|
280
|
+
terms.push(term('due_near', Math.max(0, Math.min(21, 24 - 3 * dayOffset)), dayOffset + ' 天后到期'))
|
|
281
|
+
}
|
|
282
|
+
if (normalized.debtor === 'third' || normalized.debtor?.startsWith('third:')) {
|
|
283
|
+
terms.push(term('third', 10, '可向对方催办'))
|
|
284
|
+
} else if (normalized.debtor === 'user' || normalized.debtor === 'agent') {
|
|
285
|
+
terms.push(term('mine', 6, '你答应对方'))
|
|
286
|
+
}
|
|
287
|
+
if (normalized.reminderOffsetsCount > 0) {
|
|
288
|
+
terms.push(term('remind_offsets', Math.min(6, 2 * normalized.reminderOffsetsCount), '已设置 ' + normalized.reminderOffsetsCount + ' 个提醒'))
|
|
289
|
+
}
|
|
290
|
+
if (normalized.createdAt) {
|
|
291
|
+
const createdIndex = localDayIndex(localDayOfInstant(normalized.createdAt.ms, timezone))
|
|
292
|
+
const ageDays = Math.max(0, todayIndex - createdIndex)
|
|
293
|
+
if (ageDays > 14) terms.push(term('age', Math.min(6, 1 + Math.floor((ageDays - 14) / 7)), '承诺已创建 ' + ageDays + ' 天'))
|
|
294
|
+
}
|
|
295
|
+
if (!normalized.dateOnly) terms.push(term('timed', 2, '有具体时刻'))
|
|
296
|
+
const rawScore = terms.reduce((sum, entry) => sum + entry.contribution, 0)
|
|
297
|
+
const score = clampScore(rawScore)
|
|
298
|
+
const topFactors = terms
|
|
299
|
+
.slice()
|
|
300
|
+
.sort((left, right) => right.contribution - left.contribution || TERM_IDS.indexOf(left.id) - TERM_IDS.indexOf(right.id))
|
|
301
|
+
.map((entry) => entry.id)
|
|
302
|
+
return {
|
|
303
|
+
id: normalized.id,
|
|
304
|
+
modelVersion: MODEL_VERSION,
|
|
305
|
+
score,
|
|
306
|
+
level: levelForScore(score),
|
|
307
|
+
terms,
|
|
308
|
+
topFactors,
|
|
309
|
+
whyNow: describeWhyNow(terms),
|
|
310
|
+
dueAt: new Date(dueMs).toISOString(),
|
|
311
|
+
excluded: false,
|
|
312
|
+
degraded: null,
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function normalizeRecords(records) {
|
|
317
|
+
if (records === undefined || records === null) return null
|
|
318
|
+
if (records instanceof Map || typeof records === 'function') return records
|
|
319
|
+
if (typeof records === 'object' && !Array.isArray(records)) return records
|
|
320
|
+
throw new TypeError('records must be a Map, an object keyed by id, or a function')
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function lookupRecord(records, id) {
|
|
324
|
+
if (!records || id === null || id === undefined) return null
|
|
325
|
+
const key = String(id)
|
|
326
|
+
let record = null
|
|
327
|
+
if (records instanceof Map) record = records.get(key) ?? records.get(id) ?? null
|
|
328
|
+
else if (typeof records === 'function') record = records(key) ?? records(id) ?? null
|
|
329
|
+
else record = records[key] ?? null
|
|
330
|
+
return record && typeof record === 'object' && !Array.isArray(record) ? record : null
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function buildContext({ now, timezone, records } = {}) {
|
|
334
|
+
const nowDate = resolveNow(now)
|
|
335
|
+
const tz = resolveTimezone(timezone)
|
|
336
|
+
const nowMs = nowDate.getTime()
|
|
337
|
+
const today = localDayOfInstant(nowMs, tz)
|
|
338
|
+
return { now: nowDate, nowMs, timezone: tz, today, todayIndex: localDayIndex(today), records: normalizeRecords(records) }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Score one item (an agenda commitment item, a reminder row, or a raw
|
|
343
|
+
* commitment). Never throws for dirty data: an unparseable/missing due date
|
|
344
|
+
* returns a zero score with `degraded: 'urgency_failed'` instead.
|
|
345
|
+
*
|
|
346
|
+
* @param {object} item
|
|
347
|
+
* @param {{now?: Date|string|number, timezone?: string,
|
|
348
|
+
* records?: Map<string, object>|object|Function}} [options] Optional
|
|
349
|
+
* ledger-record lookup used to fill debtor/createdAt/reminderOffsets for
|
|
350
|
+
* derived views (agenda/morning items) that do not carry those fields.
|
|
351
|
+
* @returns {{ id: string|null, modelVersion: number, score: number,
|
|
352
|
+
* level: 'low'|'medium'|'high'|'critical',
|
|
353
|
+
* terms: Array<{id: string, contribution: number, explain: string}>,
|
|
354
|
+
* topFactors: string[], whyNow: string, dueAt: string|null,
|
|
355
|
+
* excluded: boolean, degraded: null|'urgency_failed' }}
|
|
356
|
+
*/
|
|
357
|
+
export function scoreUrgency(item, options = {}) {
|
|
358
|
+
const context = buildContext(options)
|
|
359
|
+
return scoreNormalized(normalizeItem(item, context.timezone, context.records), context)
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Compute urgency for a list of items. The result is 1:1 with `items` (same
|
|
364
|
+
* order and length), so callers can zip it back without matching ids.
|
|
365
|
+
*
|
|
366
|
+
* @param {{items: Array<object>, now?: Date|string|number, timezone?: string,
|
|
367
|
+
* records?: Map<string, object>|object|Function}} options
|
|
368
|
+
* @returns {Array<object>} one score object per input item
|
|
369
|
+
*/
|
|
370
|
+
export function computeUrgency(options = {}) {
|
|
371
|
+
const opts = options ?? {}
|
|
372
|
+
if (!Array.isArray(opts.items)) throw new TypeError('computeUrgency requires items[]')
|
|
373
|
+
const context = buildContext(opts)
|
|
374
|
+
return opts.items.map((item) => scoreNormalized(normalizeItem(item, context.timezone, context.records), context))
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Return copies of `items` with an additive `urgency` field attached. The
|
|
379
|
+
* input array/objects are never mutated.
|
|
380
|
+
*
|
|
381
|
+
* @param {Array<object>} items
|
|
382
|
+
* @param {{now?: Date|string|number, timezone?: string,
|
|
383
|
+
* records?: Map<string, object>|object|Function}} [options]
|
|
384
|
+
* @returns {Array<object>}
|
|
385
|
+
*/
|
|
386
|
+
export function attachUrgency(items, options = {}) {
|
|
387
|
+
if (!Array.isArray(items)) throw new TypeError('attachUrgency requires items[]')
|
|
388
|
+
const scores = computeUrgency({ ...(options ?? {}), items })
|
|
389
|
+
return items.map((item, index) => ({
|
|
390
|
+
...(item && typeof item === 'object' && !Array.isArray(item) ? item : {}),
|
|
391
|
+
urgency: scores[index],
|
|
392
|
+
}))
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function compareNullable(left, right) {
|
|
396
|
+
if (left === right) return 0
|
|
397
|
+
if (left === null || left === undefined) return 1
|
|
398
|
+
if (right === null || right === undefined) return -1
|
|
399
|
+
return left < right ? -1 : 1
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Human priority view: at most `limit` entries, ordered score desc -> dueAt
|
|
404
|
+
* asc -> id asc. Accepts entries whose `urgency` was attached by
|
|
405
|
+
* {@link attachUrgency} (or bare score objects). Shallow copies are returned;
|
|
406
|
+
* `excluded` scores are skipped. This is a presentation helper only — it never
|
|
407
|
+
* changes hashes, ledgers or payloads.
|
|
408
|
+
*
|
|
409
|
+
* @param {Array<object>} items
|
|
410
|
+
* @param {{limit?: number}} [options]
|
|
411
|
+
* @returns {Array<object>}
|
|
412
|
+
*/
|
|
413
|
+
export function selectTopUrgent(items, options = {}) {
|
|
414
|
+
if (!Array.isArray(items)) throw new TypeError('selectTopUrgent requires items[]')
|
|
415
|
+
const limit = options?.limit ?? MAX_HUMAN_TOP
|
|
416
|
+
if (!Number.isInteger(limit) || limit < 1) throw new RangeError('limit must be a positive integer')
|
|
417
|
+
const ranked = []
|
|
418
|
+
items.forEach((item, index) => {
|
|
419
|
+
if (!item || typeof item !== 'object') return
|
|
420
|
+
const urgency = item.urgency && typeof item.urgency === 'object'
|
|
421
|
+
? item.urgency
|
|
422
|
+
: (item.modelVersion !== undefined && item.score !== undefined ? item : null)
|
|
423
|
+
if (!urgency || urgency.excluded === true) return
|
|
424
|
+
ranked.push({
|
|
425
|
+
index,
|
|
426
|
+
item,
|
|
427
|
+
score: Number.isFinite(urgency.score) ? urgency.score : 0,
|
|
428
|
+
dueAt: typeof urgency.dueAt === 'string' ? urgency.dueAt : null,
|
|
429
|
+
id: urgency.id == null ? null : String(urgency.id),
|
|
430
|
+
})
|
|
431
|
+
})
|
|
432
|
+
ranked.sort((left, right) =>
|
|
433
|
+
right.score - left.score ||
|
|
434
|
+
compareNullable(left.dueAt, right.dueAt) ||
|
|
435
|
+
compareNullable(left.id, right.id) ||
|
|
436
|
+
left.index - right.index,
|
|
437
|
+
)
|
|
438
|
+
return ranked.slice(0, limit).map((entry) => ({ ...entry.item }))
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Additive `remind --json` payload helper for the CLI integration: keeps the
|
|
443
|
+
* existing `now`/`reminders` keys and adds `ok`/`command`/`timezone` plus the
|
|
444
|
+
* optional per-row `urgency`. `now` is echoed from the injected instant so a
|
|
445
|
+
* fixed `--now` run is byte-reproducible.
|
|
446
|
+
*
|
|
447
|
+
* @param {Array<object>} reminders output of buildReminders()
|
|
448
|
+
* @param {{now?: Date|string|number, timezone?: string, includeUrgency?: boolean,
|
|
449
|
+
* records?: Map<string, object>|object|Function}} [options]
|
|
450
|
+
* @returns {{ok: true, command: 'remind', now: string, timezone: string, reminders: Array<object>}}
|
|
451
|
+
*/
|
|
452
|
+
export function buildRemindPayload(reminders, options = {}) {
|
|
453
|
+
if (!Array.isArray(reminders)) throw new TypeError('buildRemindPayload requires reminders[]')
|
|
454
|
+
const opts = options ?? {}
|
|
455
|
+
const nowDate = resolveNow(opts.now)
|
|
456
|
+
const timezone = resolveTimezone(opts.timezone)
|
|
457
|
+
const decorated = opts.includeUrgency === false
|
|
458
|
+
? reminders.map((reminder) => ({ ...reminder }))
|
|
459
|
+
: attachUrgency(reminders, { now: nowDate, timezone, records: opts.records })
|
|
460
|
+
return {
|
|
461
|
+
ok: true,
|
|
462
|
+
command: 'remind',
|
|
463
|
+
now: nowDate.toISOString(),
|
|
464
|
+
timezone,
|
|
465
|
+
reminders: decorated,
|
|
466
|
+
}
|
|
467
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "advisers",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "A staff of AI advisers: a cordis-native personal secretary runtime with scoped memory, commitments, and reviewable routines.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cordis",
|
|
@@ -36,8 +36,8 @@
|
|
|
36
36
|
],
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@pdf-lib/fontkit": "^1.1.1",
|
|
39
|
-
"advisers-core": "0.
|
|
40
|
-
"advisers-policy-strict": "0.
|
|
39
|
+
"advisers-core": "0.4.0",
|
|
40
|
+
"advisers-policy-strict": "0.4.0",
|
|
41
41
|
"jszip": "^3.10.2",
|
|
42
42
|
"pdf-lib": "^1.17.1",
|
|
43
43
|
"pdfjs-dist": "^6.5.438"
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"test": "node --experimental-strip-types --test test/*.test.js"
|
|
62
62
|
},
|
|
63
63
|
"peerDependencies": {
|
|
64
|
-
"advisers-office": "0.
|
|
64
|
+
"advisers-office": "0.4.0"
|
|
65
65
|
},
|
|
66
66
|
"peerDependenciesMeta": {
|
|
67
67
|
"advisers-office": {
|