advisers 0.2.0-preview.71 → 0.2.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.
package/lib/pet-brief.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Pet Brief producer — read-only, redacted, expiring projection from the
3
- * Advisers ledger to Famling / Pearl (contract v0.1, docs/PET-BRIEF.md).
3
+ * Advisers ledger to desktop-pet consumers (contract v0.2, docs/PET-BRIEF-PRODUCER.md).
4
4
  *
5
5
  * Pure functions: no network, no model call, no ledger writes. The caller
6
6
  * supplies the ledger (loaded read-only by the CLI) and an injectable `now`.
@@ -10,13 +10,24 @@
10
10
  * - facts below 0.7 confidence are dropped before output;
11
11
  * - person/client names are masked to `某客户` by default and never echoed back;
12
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.
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.
14
16
  */
15
17
  import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from 'node:fs'
16
18
  import { basename, dirname, join } from 'node:path'
17
19
  import { localDay } from './remind.js'
18
-
19
- export const PET_BRIEF_SCHEMA_VERSION = 1
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'
20
31
  export const PET_BRIEF_SOURCE = 'advisers'
21
32
  export const PET_BRIEF_TTL_MS = 5 * 60_000
22
33
  export const PET_BRIEF_MAX_ITEMS = 10
@@ -25,6 +36,16 @@ export const PET_BRIEF_MAX_SUGGESTED_LINES = 3
25
36
  export const PET_BRIEF_MAX_LINE_LENGTH = 40
26
37
  export const PET_BRIEF_MOODS = ['calm', 'focused', 'concerned', 'pleased']
27
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
+
28
49
  /** Contract §2.2. Matched case-insensitively with `_`/`-`/spaces removed. */
29
50
  export const PET_BRIEF_FORBIDDEN_KEYS = [
30
51
  'reasoning', 'cot', 'chainofthought', 'rawprompt', 'systemprompt',
@@ -33,7 +54,7 @@ export const PET_BRIEF_FORBIDDEN_KEYS = [
33
54
  ]
34
55
 
35
56
  const ROOT_KEYS = [
36
- 'schemaVersion', 'generatedAt', 'expiresAt', 'source', 'counts',
57
+ 'schemaVersion', 'generatedAt', 'expiresAt', 'source', 'displayPolicy', 'counts',
37
58
  'today', 'commitments', 'risks', 'facts', 'mood', 'suggestedLines', 'redactions',
38
59
  ]
39
60
  const ITEM_KEYS = {
@@ -145,7 +166,8 @@ const RISK_RANK = { low: 1, medium: 2, high: 3 }
145
166
  * @param {number} [options.ttlMs]
146
167
  * @param {number} [options.maxItems]
147
168
  * @param {number} [options.minConfidence]
148
- * @returns {object} contract v0.1 brief (no writes, no network).
169
+ * @param {'public'|'private'|'none'} [options.displayPolicy='private'] who may see the brief
170
+ * @returns {object} contract v0.2 brief (no writes, no network).
149
171
  */
150
172
  export function buildPetBrief(ledger, options = {}) {
151
173
  if (!ledger || typeof ledger.listCommitments !== 'function') throw new TypeError('buildPetBrief requires a ledger')
@@ -153,6 +175,12 @@ export function buildPetBrief(ledger, options = {}) {
153
175
  const ttlMs = Number.isFinite(options.ttlMs) ? options.ttlMs : PET_BRIEF_TTL_MS
154
176
  const maxItems = Number.isFinite(options.maxItems) ? options.maxItems : PET_BRIEF_MAX_ITEMS
155
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
+ }
156
184
  const limit = Math.max(1, Math.min(PET_BRIEF_MAX_ITEMS, Math.trunc(maxItems)))
157
185
  const today = localDay(new Date(nowMs).toISOString())
158
186
 
@@ -271,6 +299,11 @@ export function buildPetBrief(ledger, options = {}) {
271
299
  }
272
300
  const riskItems = risks
273
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
+ })
274
307
  .sort((a, b) => RISK_RANK[b.level] - RISK_RANK[a.level] || b.confidence - a.confidence || cmp(a.id, b.id))
275
308
  .slice(0, limit)
276
309
 
@@ -300,7 +333,12 @@ export function buildPetBrief(ledger, options = {}) {
300
333
  const lines = []
301
334
  const pushLine = (line) => {
302
335
  const text = clip(oneLine(line), PET_BRIEF_MAX_LINE_LENGTH)
303
- if (text && !lines.includes(text) && lines.length < PET_BRIEF_MAX_SUGGESTED_LINES) lines.push(text)
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)
304
342
  }
305
343
  const topRisk = riskItems[0]
306
344
  if (topRisk) pushLine(`${topRisk.summary}。`)
@@ -319,6 +357,8 @@ export function buildPetBrief(ledger, options = {}) {
319
357
  redactions.push('不含模型推理、系统提示或原始提示词')
320
358
  const excludedSecrecy = allMatters.filter((matter) => matterSecrecy(matter) >= 2).length
321
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))
322
362
  if (!redactions.some((note) => note.startsWith('联系人')) && !redactions.some((note) => note.includes('客户名'))) {
323
363
  redactions.push('联系人/客户名默认不进入 brief')
324
364
  }
@@ -330,6 +370,7 @@ export function buildPetBrief(ledger, options = {}) {
330
370
  generatedAt,
331
371
  expiresAt,
332
372
  source: PET_BRIEF_SOURCE,
373
+ displayPolicy,
333
374
  counts: {
334
375
  today: todayItems.length,
335
376
  commitments: commitmentItems.length,
@@ -376,7 +417,7 @@ function checkForbiddenKeys(value, path, errors) {
376
417
  function checkUnknownKeys(value, allowed, path, errors) {
377
418
  if (!isPlainObject(value)) return
378
419
  for (const key of Object.keys(value)) {
379
- if (!allowed.includes(key)) errors.push(issue('E_UNKNOWN_FIELD', `${path}.${key}`, `field is not in contract v0.1: ${key}`))
420
+ if (!allowed.includes(key)) errors.push(issue('E_UNKNOWN_FIELD', `${path}.${key}`, `field is not in contract v0.2: ${key}`))
380
421
  }
381
422
  }
382
423
 
@@ -402,34 +443,56 @@ function checkConfidence(value, path, errors) {
402
443
  }
403
444
 
404
445
  /**
405
- * Validate a brief against contract v0.1 (schema + freshness + forbidden data).
446
+ * Validate a brief against contract v0.2 (schema + freshness + forbidden data).
406
447
  * Used by `advisers pet-brief --check` and by tests; the consumer re-validates.
407
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
+ *
408
455
  * @param {unknown|string} value parsed brief, or raw JSON text
409
456
  * @param {object} [options]
410
457
  * @param {number|string|Date} [options.now]
411
458
  * @param {boolean} [options.allowExpired] skip the freshness gate (schema check only)
412
- * @returns {{ok: boolean, errors: Array<{code: string, path: string, message: string}>, brief?: object}}
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}}
413
462
  */
414
463
  export function validatePetBrief(value, options = {}) {
415
464
  const errors = []
465
+ const warnings = []
416
466
  let brief = value
417
467
  if (typeof value === 'string') {
418
468
  try {
419
469
  brief = JSON.parse(value)
420
470
  } catch (error) {
421
- return { ok: false, errors: [issue('E_MALFORMED_JSON', '$', `invalid JSON: ${error.message}`)], brief: undefined }
471
+ return { ok: false, errors: [issue('E_MALFORMED_JSON', '$', `invalid JSON: ${error.message}`)], warnings: [], brief: undefined }
422
472
  }
423
473
  }
424
474
  if (!isPlainObject(brief)) {
425
- return { ok: false, errors: [issue('E_TYPE', '$', 'brief must be a JSON object')], brief: undefined }
475
+ return { ok: false, errors: [issue('E_TYPE', '$', 'brief must be a JSON object')], warnings: [], brief: undefined }
426
476
  }
427
477
 
428
478
  checkForbiddenKeys(brief, '$', errors)
429
479
  checkUnknownKeys(brief, ROOT_KEYS, '$', errors)
430
480
 
431
- if (brief.schemaVersion !== PET_BRIEF_SCHEMA_VERSION) {
432
- errors.push(issue('E_SCHEMA_VERSION', '$.schemaVersion', `unsupported schemaVersion (expected ${PET_BRIEF_SCHEMA_VERSION})`))
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'))
433
496
  }
434
497
  if (brief.source !== PET_BRIEF_SOURCE) errors.push(issue('E_SOURCE', '$.source', 'source must be "advisers"'))
435
498
 
@@ -531,7 +594,7 @@ export function validatePetBrief(value, options = {}) {
531
594
  })
532
595
  }
533
596
 
534
- return { ok: errors.length === 0, errors, brief }
597
+ return { ok: errors.length === 0, errors, warnings, brief }
535
598
  }
536
599
 
537
600
  function parseIsoWithZone(value, path, errors) {