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
@@ -0,0 +1,644 @@
1
+ /**
2
+ * Pet Brief producer — read-only, redacted, expiring projection from the
3
+ * Advisers ledger to desktop-pet consumers (contract v0.2, docs/PET-BRIEF-PRODUCER.md).
4
+ *
5
+ * Pure functions: no network, no model call, no ledger writes. The caller
6
+ * supplies the ledger (loaded read-only by the CLI) and an injectable `now`.
7
+ *
8
+ * Privacy rules implemented here (see docs/PET-BRIEF-PRODUCER.md):
9
+ * - matters with secrecy >= 2 are excluded entirely (not even counted in arrays);
10
+ * - facts below 0.7 confidence are dropped before output;
11
+ * - person/client names are masked to `某客户` by default and never echoed back;
12
+ * - no reasoning, prompts, secrets, document bodies, or emotional fields;
13
+ * - every suggested line is built from a field that is present in the brief;
14
+ * - `displayPolicy` states who may see the brief (public/private/none); it
15
+ * defaults to `private` and is never `public` unless explicitly requested.
16
+ */
17
+ import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from 'node:fs'
18
+ import { basename, dirname, join } from 'node:path'
19
+ import { localDay } from './remind.js'
20
+ import { classify } from './safety/index.js'
21
+
22
+ export const PET_BRIEF_SCHEMA_VERSION = 2
23
+ /** v0.1 briefs (contract before `displayPolicy`) are still accepted with warnings. */
24
+ export const PET_BRIEF_LEGACY_SCHEMA_VERSION = 1
25
+ /** Schema versions `validatePetBrief` can read (v0.1 = legacy, warnings only). */
26
+ export const PET_BRIEF_SCHEMA_VERSIONS = [PET_BRIEF_LEGACY_SCHEMA_VERSION, PET_BRIEF_SCHEMA_VERSION]
27
+ /** Contract v0.2 display policy: who may see brief-derived content. */
28
+ export const PET_BRIEF_DISPLAY_POLICIES = ['public', 'private', 'none']
29
+ /** Safe default: never `public` unless the user explicitly opts in. */
30
+ export const PET_BRIEF_DEFAULT_DISPLAY_POLICY = 'private'
31
+ export const PET_BRIEF_SOURCE = 'advisers'
32
+ export const PET_BRIEF_TTL_MS = 5 * 60_000
33
+ export const PET_BRIEF_MAX_ITEMS = 10
34
+ export const PET_BRIEF_MIN_CONFIDENCE = 0.7
35
+ export const PET_BRIEF_MAX_SUGGESTED_LINES = 3
36
+ export const PET_BRIEF_MAX_LINE_LENGTH = 40
37
+ export const PET_BRIEF_MOODS = ['calm', 'focused', 'concerned', 'pleased']
38
+
39
+ // Content-safety wiring (docs/CONTENT-SAFETY.md section 8): suggested lines and
40
+ // risk summaries are classified with the pet-brief surface. A block-level line
41
+ // is dropped entirely (fail-closed, no schema change: counts are derived from
42
+ // the arrays) and only a generic note is added to redactions - never the text.
43
+ const PET_BRIEF_SURFACE = 'pet-brief'
44
+
45
+ function isBlockedLine(text, hmacKey) {
46
+ return classify(text, { surface: PET_BRIEF_SURFACE, hmacKey }).action === 'block'
47
+ }
48
+
49
+ /** Contract §2.2. Matched case-insensitively with `_`/`-`/spaces removed. */
50
+ export const PET_BRIEF_FORBIDDEN_KEYS = [
51
+ 'reasoning', 'cot', 'chainofthought', 'rawprompt', 'systemprompt',
52
+ 'clientsecret', 'apikey', 'token', 'password',
53
+ 'affection', 'love', 'missedyou', 'streak', 'guilt',
54
+ ]
55
+
56
+ const ROOT_KEYS = [
57
+ 'schemaVersion', 'generatedAt', 'expiresAt', 'source', 'displayPolicy', 'counts',
58
+ 'today', 'commitments', 'risks', 'facts', 'mood', 'suggestedLines', 'redactions',
59
+ ]
60
+ const ITEM_KEYS = {
61
+ today: ['id', 'title', 'status'],
62
+ commitments: ['id', 'matter', 'who', 'what', 'due', 'risk', 'confidence'],
63
+ risks: ['id', 'level', 'summary', 'evidence', 'confidence'],
64
+ facts: ['id', 'subject', 'predicate', 'value', 'confidence'],
65
+ }
66
+ const ISO_WITH_ZONE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/
67
+ const RISK_LEVEL = ['low', 'medium', 'high']
68
+ const TODAY_STATUS = ['open', 'doing', 'done']
69
+
70
+ /** Creditors/subjects that are roles or groups, not personal names. */
71
+ const GENERIC_WHO = new Set([
72
+ '团队', '客户', '某客户', '客户方', '公司', '部门', '领导', '同事', '同学', '老师',
73
+ '家人', '朋友', '对方', '某人', '自己', '用户', '老板', '甲方', '乙方', '供应商',
74
+ '伙伴', '项目组', '全员', '大家', 'hr', '财务', '法务', '行政', '运营', '销售',
75
+ ])
76
+ const NAME_SUFFIX = '(?:工|总|老师|经理|总监|主任|医生|律师|先生|女士|姐|哥|叔|阿姨|经理)'
77
+ const VERB_NAME = new RegExp(`(给|向|找|和|与|跟|回复|联系|问|让|等|约|催)([\\u4e00-\\u9fa5]{1,2}${NAME_SUFFIX})`, 'g')
78
+
79
+ function toMillis(value) {
80
+ if (value === undefined || value === null) return Date.now()
81
+ if (value instanceof Date) return value.getTime()
82
+ if (typeof value === 'number') return value
83
+ const parsed = Date.parse(String(value))
84
+ return Number.isFinite(parsed) ? parsed : Date.now()
85
+ }
86
+
87
+ function cmp(a, b) {
88
+ return a < b ? -1 : a > b ? 1 : 0
89
+ }
90
+
91
+ /** Clip by Unicode code points so a sentence never exceeds the contract limit. */
92
+ function clip(value, max) {
93
+ const points = Array.from(String(value ?? ''))
94
+ return points.length <= max ? points.join('') : points.slice(0, max).join('')
95
+ }
96
+
97
+ function oneLine(value) {
98
+ return String(value ?? '').replace(/\s+/g, ' ').trim()
99
+ }
100
+
101
+ function looksLikePersonName(value) {
102
+ const text = oneLine(value)
103
+ if (!text || GENERIC_WHO.has(text.toLowerCase())) return false
104
+ if (new RegExp(`^[\\u4e00-\\u9fa5]{1,4}${NAME_SUFFIX}$`, 'u').test(text)) return true
105
+ if (/^[\u4e00-\u9fa5]{2,3}$/u.test(text)) return true
106
+ if (/^[A-Z][a-z]{1,10}\s+[A-Z][a-z]{1,10}$/.test(text)) return true
107
+ return false
108
+ }
109
+
110
+ /**
111
+ * Deterministic name redactor. Collects likely person names from the ledger
112
+ * first, then masks exact matches plus common "<verb><surname><role>" forms in
113
+ * titles/actions. `masked` is a count of replacements (for `redactions`).
114
+ */
115
+ function createRedactor(rawNames) {
116
+ const names = [...new Set((rawNames ?? []).map(oneLine).filter((name) => looksLikePersonName(name)))]
117
+ .sort((a, b) => b.length - a.length || cmp(a, b))
118
+ let masked = 0
119
+ const redact = (value) => {
120
+ let text = oneLine(value)
121
+ if (!text) return text
122
+ for (const name of names) {
123
+ if (!text.includes(name)) continue
124
+ masked += text.split(name).length - 1
125
+ text = text.split(name).join('某客户')
126
+ }
127
+ text = text.replace(VERB_NAME, (_match, verb) => {
128
+ masked += 1
129
+ return `${verb}某客户`
130
+ })
131
+ return text
132
+ }
133
+ return { redact, masked: () => masked }
134
+ }
135
+
136
+ function matterSecrecy(matter) {
137
+ if (!matter) return Number.POSITIVE_INFINITY
138
+ const level = Number(matter.secrecy ?? 0)
139
+ return Number.isFinite(level) ? level : Number.POSITIVE_INFINITY
140
+ }
141
+
142
+ function isPublicMatter(matter) {
143
+ return Boolean(matter) && matter.status === 'active' && matterSecrecy(matter) < 2
144
+ }
145
+
146
+ function confidenceOfCommitment(commitment) {
147
+ return Array.isArray(commitment.evidence) && commitment.evidence.length > 0 ? 0.95 : 0.75
148
+ }
149
+
150
+ function riskOfDue(dueMs, nowMs, today) {
151
+ if (dueMs < nowMs) return 'high'
152
+ const day = localDay(new Date(dueMs).toISOString())
153
+ if (day === today) return 'high'
154
+ if (dueMs <= nowMs + 3 * 86_400_000) return 'medium'
155
+ return 'low'
156
+ }
157
+
158
+ const RISK_RANK = { low: 1, medium: 2, high: 3 }
159
+
160
+ /**
161
+ * Build the brief document. Deterministic for the same ledger + now.
162
+ *
163
+ * @param {object} ledger Advisers core `Ledger` (listMatters/listCommitments/listFacts).
164
+ * @param {object} [options]
165
+ * @param {number|string|Date} [options.now]
166
+ * @param {number} [options.ttlMs]
167
+ * @param {number} [options.maxItems]
168
+ * @param {number} [options.minConfidence]
169
+ * @param {'public'|'private'|'none'} [options.displayPolicy='private'] who may see the brief
170
+ * @returns {object} contract v0.2 brief (no writes, no network).
171
+ */
172
+ export function buildPetBrief(ledger, options = {}) {
173
+ if (!ledger || typeof ledger.listCommitments !== 'function') throw new TypeError('buildPetBrief requires a ledger')
174
+ const nowMs = toMillis(options.now)
175
+ const ttlMs = Number.isFinite(options.ttlMs) ? options.ttlMs : PET_BRIEF_TTL_MS
176
+ const maxItems = Number.isFinite(options.maxItems) ? options.maxItems : PET_BRIEF_MAX_ITEMS
177
+ const minConfidence = Number.isFinite(options.minConfidence) ? options.minConfidence : PET_BRIEF_MIN_CONFIDENCE
178
+ const displayPolicy = options.displayPolicy ?? PET_BRIEF_DEFAULT_DISPLAY_POLICY
179
+ const hmacKey = options.hmacKey
180
+ const dropped = { risks: 0, lines: 0 }
181
+ if (!PET_BRIEF_DISPLAY_POLICIES.includes(displayPolicy)) {
182
+ throw new TypeError(`displayPolicy must be one of ${PET_BRIEF_DISPLAY_POLICIES.join('|')}`)
183
+ }
184
+ const limit = Math.max(1, Math.min(PET_BRIEF_MAX_ITEMS, Math.trunc(maxItems)))
185
+ const today = localDay(new Date(nowMs).toISOString())
186
+
187
+ const allMatters = [
188
+ ...(ledger.listMatters('active') ?? []),
189
+ ...(ledger.listMatters('paused') ?? []),
190
+ ...(ledger.listMatters('archived') ?? []),
191
+ ]
192
+ const matterById = new Map(allMatters.map((matter) => [matter.id, matter]))
193
+ const activeMatters = allMatters.filter((matter) => isPublicMatter(matter))
194
+ const publicMatterIds = new Set(activeMatters.map((matter) => matter.id))
195
+
196
+ const allCommitments = ledger.listCommitments() ?? []
197
+ const openCommitments = allCommitments.filter((commitment) => commitment.status === 'open')
198
+ const rawNames = [
199
+ ...allCommitments.map((commitment) => commitment.creditor),
200
+ ...(ledger.listFacts() ?? []).map((fact) => fact.subject),
201
+ ...allMatters.flatMap((matter) => matter.participants ?? []),
202
+ ]
203
+ const redactor = createRedactor(rawNames)
204
+ const redacted = (value) => redactor.redact(value)
205
+
206
+ // Public open commitments: matter must be active with secrecy < 2.
207
+ const publicOpen = openCommitments.filter((commitment) => publicMatterIds.has(commitment.matterId))
208
+ const dueMsOf = (commitment) => {
209
+ if (!commitment.dueAt) return null
210
+ const ms = Date.parse(commitment.dueAt)
211
+ return Number.isFinite(ms) ? ms : null
212
+ }
213
+
214
+ // --- today: active public matters, urgency first, deterministic tie-break.
215
+ const urgency = new Map()
216
+ for (const commitment of publicOpen) {
217
+ const ms = dueMsOf(commitment)
218
+ if (ms === null) continue
219
+ const day = localDay(new Date(ms).toISOString())
220
+ if (day !== today && ms >= nowMs) continue
221
+ urgency.set(commitment.matterId, (urgency.get(commitment.matterId) ?? 0) + 1)
222
+ }
223
+ const todayItems = [...activeMatters]
224
+ .sort((a, b) => (urgency.get(b.id) ?? 0) - (urgency.get(a.id) ?? 0) || cmp(String(b.updatedAt ?? ''), String(a.updatedAt ?? '')) || cmp(a.id, b.id))
225
+ .slice(0, limit)
226
+ .map((matter) => ({
227
+ id: clip(matter.id, 64),
228
+ title: clip(redacted(matter.title), 80),
229
+ status: urgency.has(matter.id) ? 'doing' : 'open',
230
+ }))
231
+
232
+ // --- commitments: open, due-dated, public; risk ordered then due date.
233
+ const dueCommitments = publicOpen
234
+ .map((commitment) => ({ commitment, dueMs: dueMsOf(commitment) }))
235
+ .filter((row) => row.dueMs !== null)
236
+ .map((row) => ({ ...row, risk: riskOfDue(row.dueMs, nowMs, today), confidence: confidenceOfCommitment(row.commitment) }))
237
+ .sort((a, b) => RISK_RANK[b.risk] - RISK_RANK[a.risk] || a.dueMs - b.dueMs || cmp(a.commitment.id, b.commitment.id))
238
+ .slice(0, limit)
239
+ const commitmentItems = dueCommitments.map(({ commitment, dueMs, risk, confidence }) => ({
240
+ id: clip(commitment.id, 64),
241
+ matter: clip(commitment.matterId, 64),
242
+ who: clip(redacted(commitment.creditor), 40),
243
+ what: clip(redacted(commitment.action), 80),
244
+ due: clip(localDay(new Date(dueMs).toISOString()) ?? clip(commitment.dueAt, 32), 32),
245
+ risk,
246
+ confidence,
247
+ }))
248
+
249
+ // --- risks: deterministic derivation from the same public commitments.
250
+ const risks = []
251
+ for (const { commitment, dueMs, risk } of dueCommitments) {
252
+ const who = clip(redacted(commitment.creditor), 12)
253
+ const what = clip(redacted(commitment.action), 24)
254
+ if (risk === 'high') {
255
+ const summary = dueMs < nowMs ? `${who}的${what}已逾期` : `${who}的${what}今天到期`
256
+ risks.push({
257
+ id: clip(`risk_${commitment.id}`, 64),
258
+ level: 'high',
259
+ summary: clip(summary, 80),
260
+ evidence: clip(commitment.id, 64),
261
+ confidence: dueMs < nowMs ? 0.95 : 0.9,
262
+ })
263
+ } else if (risk === 'medium') {
264
+ risks.push({
265
+ id: clip(`risk_${commitment.id}`, 64),
266
+ level: 'medium',
267
+ summary: clip(`${who}的${what}即将到期`, 80),
268
+ evidence: clip(commitment.id, 64),
269
+ confidence: 0.72,
270
+ })
271
+ }
272
+ }
273
+ for (const commitment of publicOpen.filter((row) => !row.dueAt && isPublicMatter(matterById.get(row.matterId)))) {
274
+ const who = clip(redacted(commitment.creditor), 12)
275
+ const what = clip(redacted(commitment.action), 24)
276
+ risks.push({
277
+ id: clip(`risk_${commitment.id}`, 64),
278
+ level: 'medium',
279
+ summary: clip(`${who}的${what}还没有截止时间`, 80),
280
+ evidence: clip(commitment.id, 64),
281
+ confidence: 0.75,
282
+ })
283
+ }
284
+ const byDay = new Map()
285
+ for (const { commitment, dueMs } of dueCommitments) {
286
+ const day = localDay(new Date(dueMs).toISOString())
287
+ if (!day || day < today) continue
288
+ byDay.set(day, [...(byDay.get(day) ?? []), commitment])
289
+ }
290
+ for (const [day, list] of [...byDay.entries()].sort((a, b) => cmp(a[0], b[0]))) {
291
+ if (list.length < 2) continue
292
+ risks.push({
293
+ id: clip(`risk_cluster_${day.replaceAll('-', '')}`, 64),
294
+ level: 'medium',
295
+ summary: clip(`${day} 有 ${list.length} 个截止`, 80),
296
+ evidence: clip(list[0].id, 64),
297
+ confidence: 0.72,
298
+ })
299
+ }
300
+ const riskItems = risks
301
+ .filter((risk) => risk.confidence >= minConfidence)
302
+ .filter((risk) => {
303
+ if (!isBlockedLine(risk.summary, hmacKey)) return true
304
+ dropped.risks += 1
305
+ return false
306
+ })
307
+ .sort((a, b) => RISK_RANK[b.level] - RISK_RANK[a.level] || b.confidence - a.confidence || cmp(a.id, b.id))
308
+ .slice(0, limit)
309
+
310
+ // --- facts: confirmed ledger facts, confidence >= 0.7, public matters only.
311
+ const factItems = (ledger.listFacts() ?? [])
312
+ .filter((fact) => Number(fact.confidence) >= minConfidence)
313
+ .filter((fact) => {
314
+ if (!fact.matterId) return true
315
+ return publicMatterIds.has(fact.matterId)
316
+ })
317
+ .sort((a, b) => Number(b.confidence) - Number(a.confidence) || cmp(a.id, b.id))
318
+ .slice(0, limit)
319
+ .map((fact) => ({
320
+ id: clip(fact.id, 64),
321
+ subject: clip(redacted(fact.subject), 40),
322
+ predicate: clip(oneLine(fact.predicate), 40),
323
+ value: clip(redacted(fact.object), 80),
324
+ confidence: Number(fact.confidence),
325
+ }))
326
+
327
+ // --- mood: workload only, never affection.
328
+ let mood = 'calm'
329
+ if (riskItems.some((risk) => risk.level === 'high')) mood = 'concerned'
330
+ else if (commitmentItems.length > 0 || riskItems.length > 0 || todayItems.some((item) => item.status === 'doing')) mood = 'focused'
331
+
332
+ // --- suggested lines: <=3, <=40 chars, every line reuses a brief field.
333
+ const lines = []
334
+ const pushLine = (line) => {
335
+ const text = clip(oneLine(line), PET_BRIEF_MAX_LINE_LENGTH)
336
+ if (!text || lines.includes(text) || lines.length >= PET_BRIEF_MAX_SUGGESTED_LINES) return
337
+ if (isBlockedLine(text, hmacKey)) {
338
+ dropped.lines += 1
339
+ return
340
+ }
341
+ lines.push(text)
342
+ }
343
+ const topRisk = riskItems[0]
344
+ if (topRisk) pushLine(`${topRisk.summary}。`)
345
+ const topCommitment = commitmentItems.find((item) => item.id !== topRisk?.evidence) ?? commitmentItems[0]
346
+ if (topCommitment) {
347
+ if (topCommitment.due < today) pushLine(`${topCommitment.who}的${topCommitment.what}已经逾期。`)
348
+ else pushLine(`${topCommitment.who}的${topCommitment.what},${topCommitment.due === today ? '今天' : topCommitment.due}到期。`)
349
+ }
350
+ const topFact = factItems[0]
351
+ if (topFact) pushLine(`${topFact.subject}:${topFact.value}`)
352
+
353
+ // --- redactions: human-readable log, never a secret.
354
+ const redactions = []
355
+ if (redactor.masked() > 0) redactions.push(clip(`联系人/客户名已脱敏为“某客户”(${redactor.masked()} 处)`, 80))
356
+ redactions.push('不含文档正文、邮件正文、聊天记录')
357
+ redactions.push('不含模型推理、系统提示或原始提示词')
358
+ const excludedSecrecy = allMatters.filter((matter) => matterSecrecy(matter) >= 2).length
359
+ if (excludedSecrecy > 0) redactions.push(clip(`已排除保密等级≥2 的事项(${excludedSecrecy} 个)`, 80))
360
+ const droppedTotal = dropped.risks + dropped.lines
361
+ if (droppedTotal > 0) redactions.push(clip(`已丢弃 ${droppedTotal} 条不安全内容(不展示原文)`, 80))
362
+ if (!redactions.some((note) => note.startsWith('联系人')) && !redactions.some((note) => note.includes('客户名'))) {
363
+ redactions.push('联系人/客户名默认不进入 brief')
364
+ }
365
+
366
+ const generatedAt = new Date(nowMs).toISOString()
367
+ const expiresAt = new Date(nowMs + ttlMs).toISOString()
368
+ return {
369
+ schemaVersion: PET_BRIEF_SCHEMA_VERSION,
370
+ generatedAt,
371
+ expiresAt,
372
+ source: PET_BRIEF_SOURCE,
373
+ displayPolicy,
374
+ counts: {
375
+ today: todayItems.length,
376
+ commitments: commitmentItems.length,
377
+ risks: riskItems.length,
378
+ facts: factItems.length,
379
+ },
380
+ today: todayItems,
381
+ commitments: commitmentItems,
382
+ risks: riskItems,
383
+ facts: factItems,
384
+ mood,
385
+ suggestedLines: lines.slice(0, PET_BRIEF_MAX_SUGGESTED_LINES),
386
+ redactions: redactions.slice(0, 10),
387
+ }
388
+ }
389
+
390
+ function normalizedKey(key) {
391
+ return String(key).toLowerCase().replace(/[_\-\s]/g, '')
392
+ }
393
+
394
+ function isPlainObject(value) {
395
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
396
+ }
397
+
398
+ function issue(code, path, message) {
399
+ return { code, path, message }
400
+ }
401
+
402
+ function checkForbiddenKeys(value, path, errors) {
403
+ if (Array.isArray(value)) {
404
+ value.forEach((entry, index) => checkForbiddenKeys(entry, `${path}[${index}]`, errors))
405
+ return
406
+ }
407
+ if (!isPlainObject(value)) return
408
+ for (const [key, entry] of Object.entries(value)) {
409
+ const normalized = normalizedKey(key)
410
+ if (PET_BRIEF_FORBIDDEN_KEYS.includes(normalized) || PET_BRIEF_FORBIDDEN_KEYS.some((forbidden) => normalized.endsWith(forbidden))) {
411
+ errors.push(issue('E_FORBIDDEN_FIELD', `${path}.${key}`, `forbidden contract field: ${key}`))
412
+ }
413
+ checkForbiddenKeys(entry, `${path}.${key}`, errors)
414
+ }
415
+ }
416
+
417
+ function checkUnknownKeys(value, allowed, path, errors) {
418
+ if (!isPlainObject(value)) return
419
+ for (const key of Object.keys(value)) {
420
+ if (!allowed.includes(key)) errors.push(issue('E_UNKNOWN_FIELD', `${path}.${key}`, `field is not in contract v0.2: ${key}`))
421
+ }
422
+ }
423
+
424
+ function checkString(value, { path, errors, min = 1, max = 80, field }) {
425
+ if (typeof value !== 'string') {
426
+ errors.push(issue('E_TYPE', path, `${field ?? 'value'} must be a string`))
427
+ return false
428
+ }
429
+ const length = Array.from(value).length
430
+ if (length < min || length > max) {
431
+ errors.push(issue('E_LENGTH', path, `${field ?? 'value'} length ${length} outside ${min}..${max}`))
432
+ return false
433
+ }
434
+ return true
435
+ }
436
+
437
+ function checkConfidence(value, path, errors) {
438
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
439
+ errors.push(issue('E_CONFIDENCE', path, 'confidence must be a number in 0..1'))
440
+ return false
441
+ }
442
+ return true
443
+ }
444
+
445
+ /**
446
+ * Validate a brief against contract v0.2 (schema + freshness + forbidden data).
447
+ * Used by `advisers pet-brief --check` and by tests; the consumer re-validates.
448
+ *
449
+ * Backward compatibility: contract v0.1 briefs (`schemaVersion: 1`, no
450
+ * `displayPolicy`) are accepted by default with a `W_LEGACY_SCHEMA_VERSION`
451
+ * warning and a `W_MISSING_DISPLAY_POLICY` warning; missing `displayPolicy`
452
+ * always means the safe default `private` and never fails the check unless the
453
+ * caller opts into `requireDisplayPolicy`. Unknown versions still fail closed.
454
+ *
455
+ * @param {unknown|string} value parsed brief, or raw JSON text
456
+ * @param {object} [options]
457
+ * @param {number|string|Date} [options.now]
458
+ * @param {boolean} [options.allowExpired] skip the freshness gate (schema check only)
459
+ * @param {boolean} [options.acceptLegacy=true] accept v0.1 briefs with warnings; false fails closed
460
+ * @param {boolean} [options.requireDisplayPolicy=false] make a missing displayPolicy an error
461
+ * @returns {{ok: boolean, errors: Array<{code: string, path: string, message: string}>, warnings: Array<{code: string, path: string, message: string}>, brief?: object}}
462
+ */
463
+ export function validatePetBrief(value, options = {}) {
464
+ const errors = []
465
+ const warnings = []
466
+ let brief = value
467
+ if (typeof value === 'string') {
468
+ try {
469
+ brief = JSON.parse(value)
470
+ } catch (error) {
471
+ return { ok: false, errors: [issue('E_MALFORMED_JSON', '$', `invalid JSON: ${error.message}`)], warnings: [], brief: undefined }
472
+ }
473
+ }
474
+ if (!isPlainObject(brief)) {
475
+ return { ok: false, errors: [issue('E_TYPE', '$', 'brief must be a JSON object')], warnings: [], brief: undefined }
476
+ }
477
+
478
+ checkForbiddenKeys(brief, '$', errors)
479
+ checkUnknownKeys(brief, ROOT_KEYS, '$', errors)
480
+
481
+ if (brief.schemaVersion === PET_BRIEF_LEGACY_SCHEMA_VERSION) {
482
+ if (options.acceptLegacy === false) {
483
+ errors.push(issue('E_SCHEMA_VERSION', '$.schemaVersion', 'schemaVersion 1 is legacy (contract v0.1) and acceptance is disabled'))
484
+ } else {
485
+ warnings.push(issue('W_LEGACY_SCHEMA_VERSION', '$.schemaVersion', 'brief uses legacy schemaVersion 1 (contract v0.1); accepted, missing displayPolicy means "private"'))
486
+ }
487
+ } else if (brief.schemaVersion !== PET_BRIEF_SCHEMA_VERSION) {
488
+ errors.push(issue('E_SCHEMA_VERSION', '$.schemaVersion', `unsupported schemaVersion (expected 2, legacy 1 allowed with warnings)`))
489
+ }
490
+ if (brief.displayPolicy === undefined) {
491
+ const message = 'displayPolicy is missing; consumers must treat it as "private" (legacy v0.1 brief)'
492
+ if (options.requireDisplayPolicy === true) errors.push(issue('E_DISPLAY_POLICY', '$.displayPolicy', message))
493
+ else warnings.push(issue('W_MISSING_DISPLAY_POLICY', '$.displayPolicy', message))
494
+ } else if (!PET_BRIEF_DISPLAY_POLICIES.includes(brief.displayPolicy)) {
495
+ errors.push(issue('E_ENUM', '$.displayPolicy', 'displayPolicy must be public|private|none'))
496
+ }
497
+ if (brief.source !== PET_BRIEF_SOURCE) errors.push(issue('E_SOURCE', '$.source', 'source must be "advisers"'))
498
+
499
+ const generatedMs = parseIsoWithZone(brief.generatedAt, '$.generatedAt', errors)
500
+ const expiresMs = parseIsoWithZone(brief.expiresAt, '$.expiresAt', errors)
501
+ if (generatedMs !== null && expiresMs !== null) {
502
+ if (expiresMs <= generatedMs) errors.push(issue('E_TIME_ORDER', '$.expiresAt', 'expiresAt must be after generatedAt'))
503
+ else if (!options.allowExpired && toMillis(options.now) >= expiresMs) errors.push(issue('E_EXPIRED', '$.expiresAt', 'brief is expired'))
504
+ }
505
+
506
+ const arrays = ['today', 'commitments', 'risks', 'facts']
507
+ for (const name of arrays) {
508
+ if (!Array.isArray(brief[name])) continue
509
+ if (brief[name].length > PET_BRIEF_MAX_ITEMS) errors.push(issue('E_MAX_ITEMS', `$.${name}`, `${name} exceeds ${PET_BRIEF_MAX_ITEMS} items`))
510
+ const seen = new Set()
511
+ brief[name].forEach((item, index) => {
512
+ const path = `$.${name}[${index}]`
513
+ if (!isPlainObject(item)) {
514
+ errors.push(issue('E_TYPE', path, 'item must be an object'))
515
+ return
516
+ }
517
+ checkUnknownKeys(item, ITEM_KEYS[name], path, errors)
518
+ if (typeof item.id !== 'string' || !item.id) errors.push(issue('E_ID', `${path}.id`, 'id is required'))
519
+ else {
520
+ checkString(item.id, { path: `${path}.id`, errors, max: 64, field: 'id' })
521
+ if (seen.has(item.id)) errors.push(issue('E_DUP_ID', `${path}.id`, `duplicate id within ${name}: ${item.id}`))
522
+ seen.add(item.id)
523
+ }
524
+ })
525
+ }
526
+
527
+ if (!Array.isArray(brief.today)) errors.push(issue('E_TYPE', '$.today', 'today must be an array'))
528
+ else brief.today.forEach((item, index) => {
529
+ if (!isPlainObject(item)) return
530
+ checkString(item.title, { path: `$.today[${index}].title`, errors, max: 80, field: 'title' })
531
+ if (!TODAY_STATUS.includes(item.status)) errors.push(issue('E_ENUM', `$.today[${index}].status`, 'status must be open|doing|done'))
532
+ })
533
+
534
+ if (!Array.isArray(brief.commitments)) errors.push(issue('E_TYPE', '$.commitments', 'commitments must be an array'))
535
+ else brief.commitments.forEach((item, index) => {
536
+ if (!isPlainObject(item)) return
537
+ const path = `$.commitments[${index}]`
538
+ checkString(item.matter, { path: `${path}.matter`, errors, max: 64, field: 'matter' })
539
+ checkString(item.who, { path: `${path}.who`, errors, max: 40, field: 'who' })
540
+ checkString(item.what, { path: `${path}.what`, errors, max: 80, field: 'what' })
541
+ checkString(item.due, { path: `${path}.due`, errors, max: 32, field: 'due' })
542
+ if (!RISK_LEVEL.includes(item.risk)) errors.push(issue('E_ENUM', `${path}.risk`, 'risk must be low|medium|high'))
543
+ checkConfidence(item.confidence, `${path}.confidence`, errors)
544
+ })
545
+
546
+ if (!Array.isArray(brief.risks)) errors.push(issue('E_TYPE', '$.risks', 'risks must be an array'))
547
+ else brief.risks.forEach((item, index) => {
548
+ if (!isPlainObject(item)) return
549
+ const path = `$.risks[${index}]`
550
+ if (!RISK_LEVEL.includes(item.level)) errors.push(issue('E_ENUM', `${path}.level`, 'level must be low|medium|high'))
551
+ checkString(item.summary, { path: `${path}.summary`, errors, max: 80, field: 'summary' })
552
+ checkString(item.evidence, { path: `${path}.evidence`, errors, max: 64, field: 'evidence' })
553
+ checkConfidence(item.confidence, `${path}.confidence`, errors)
554
+ })
555
+
556
+ if (!Array.isArray(brief.facts)) errors.push(issue('E_TYPE', '$.facts', 'facts must be an array'))
557
+ else brief.facts.forEach((item, index) => {
558
+ if (!isPlainObject(item)) return
559
+ const path = `$.facts[${index}]`
560
+ checkString(item.subject, { path: `${path}.subject`, errors, max: 40, field: 'subject' })
561
+ checkString(item.predicate, { path: `${path}.predicate`, errors, max: 40, field: 'predicate' })
562
+ checkString(item.value, { path: `${path}.value`, errors, max: 80, field: 'value' })
563
+ checkConfidence(item.confidence, `${path}.confidence`, errors)
564
+ })
565
+
566
+ if (!isPlainObject(brief.counts)) {
567
+ errors.push(issue('E_TYPE', '$.counts', 'counts must be an object'))
568
+ } else {
569
+ checkUnknownKeys(brief.counts, arrays, '$.counts', errors)
570
+ for (const name of arrays) {
571
+ if (!Number.isInteger(brief.counts[name]) || brief.counts[name] < 0 || brief.counts[name] > PET_BRIEF_MAX_ITEMS) {
572
+ errors.push(issue('E_COUNTS', `$.counts.${name}`, `${name} count must be an integer in 0..${PET_BRIEF_MAX_ITEMS}`))
573
+ } else if (Array.isArray(brief[name]) && brief.counts[name] !== brief[name].length) {
574
+ errors.push(issue('E_COUNTS', `$.counts.${name}`, `${name} count does not match array length`))
575
+ }
576
+ }
577
+ }
578
+
579
+ if (!PET_BRIEF_MOODS.includes(brief.mood)) errors.push(issue('E_ENUM', '$.mood', 'mood must be calm|focused|concerned|pleased'))
580
+
581
+ if (!Array.isArray(brief.suggestedLines)) errors.push(issue('E_TYPE', '$.suggestedLines', 'suggestedLines must be an array'))
582
+ else {
583
+ if (brief.suggestedLines.length > PET_BRIEF_MAX_SUGGESTED_LINES) errors.push(issue('E_MAX_LINES', '$.suggestedLines', `suggestedLines exceeds ${PET_BRIEF_MAX_SUGGESTED_LINES}`))
584
+ brief.suggestedLines.forEach((line, index) => {
585
+ checkString(line, { path: `$.suggestedLines[${index}]`, errors, max: PET_BRIEF_MAX_LINE_LENGTH, field: 'suggested line' })
586
+ })
587
+ }
588
+
589
+ if (!Array.isArray(brief.redactions)) errors.push(issue('E_TYPE', '$.redactions', 'redactions must be an array'))
590
+ else {
591
+ if (brief.redactions.length > 10) errors.push(issue('E_MAX_ITEMS', '$.redactions', 'redactions exceeds 10'))
592
+ brief.redactions.forEach((note, index) => {
593
+ checkString(note, { path: `$.redactions[${index}]`, errors, max: 80, field: 'redaction note' })
594
+ })
595
+ }
596
+
597
+ return { ok: errors.length === 0, errors, warnings, brief }
598
+ }
599
+
600
+ function parseIsoWithZone(value, path, errors) {
601
+ if (typeof value !== 'string' || !ISO_WITH_ZONE.test(value)) {
602
+ errors.push(issue('E_TIME_FORMAT', path, 'timestamp must be ISO 8601 with a timezone'))
603
+ return null
604
+ }
605
+ const ms = Date.parse(value)
606
+ if (!Number.isFinite(ms)) {
607
+ errors.push(issue('E_TIME_FORMAT', path, 'timestamp is not a valid instant'))
608
+ return null
609
+ }
610
+ return ms
611
+ }
612
+
613
+ /**
614
+ * Atomically write a brief: temp file in the same directory, fsync, rename,
615
+ * then chmod 600. Atomic rename means a reader never sees a half-written file.
616
+ *
617
+ * @param {string} filePath destination path
618
+ * @param {object} brief brief object
619
+ * @returns {string} the written path
620
+ */
621
+ export function writePetBriefAtomic(filePath, brief) {
622
+ const target = String(filePath)
623
+ const dir = dirname(target)
624
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
625
+ const data = `${JSON.stringify(brief, null, 2)}\n`
626
+ const tmp = join(dir, `.${basename(target)}.${process.pid}.${Date.now().toString(36)}.tmp`)
627
+ let fd
628
+ try {
629
+ fd = openSync(tmp, 'wx', 0o600)
630
+ writeSync(fd, data)
631
+ fsyncSync(fd)
632
+ closeSync(fd)
633
+ fd = undefined
634
+ renameSync(tmp, target)
635
+ chmodSync(target, 0o600)
636
+ return target
637
+ } catch (error) {
638
+ if (fd !== undefined) {
639
+ try { closeSync(fd) } catch {}
640
+ }
641
+ try { unlinkSync(tmp) } catch {}
642
+ throw error
643
+ }
644
+ }