advisers 0.2.2 → 0.3.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 (70) hide show
  1. package/LICENSE +0 -0
  2. package/NOTICE +0 -0
  3. package/README-zh.md +11 -7
  4. package/README.md +16 -8
  5. package/THIRD-PARTY-NOTICES.md +1 -1
  6. package/bin/advisers.js +6347 -542
  7. package/index.js +1 -1
  8. package/lib/agent.js +529 -80
  9. package/lib/attachments.js +0 -0
  10. package/lib/audit-anchor.js +683 -0
  11. package/lib/backup.js +1345 -0
  12. package/lib/capture.js +0 -0
  13. package/lib/context-window.js +0 -0
  14. package/lib/digest.js +0 -0
  15. package/lib/doc-review.js +0 -0
  16. package/lib/egress.js +0 -0
  17. package/lib/error-codes.js +1373 -0
  18. package/lib/evidence.js +352 -43
  19. package/lib/fs-safe.js +347 -0
  20. package/lib/ical.js +0 -0
  21. package/lib/imap.js +6 -2
  22. package/lib/importers.js +0 -0
  23. package/lib/learning.js +0 -0
  24. package/lib/ledger-read.js +608 -0
  25. package/lib/mcp-server.js +331 -50
  26. package/lib/model.js +73 -1
  27. package/lib/node-warning-filter.js +15 -0
  28. package/lib/notify.js +13 -3
  29. package/lib/nudge.js +0 -0
  30. package/lib/ocr.js +29 -9
  31. package/lib/pdf.js +0 -0
  32. package/lib/pet-brief-store.js +0 -0
  33. package/lib/pet-brief.js +126 -64
  34. package/lib/receipt-verify.js +213 -15
  35. package/lib/relative-date.js +0 -0
  36. package/lib/remind.js +91 -36
  37. package/lib/research.js +0 -0
  38. package/lib/review.js +0 -0
  39. package/lib/routine.js +0 -0
  40. package/lib/safety/classifier.js +55 -2
  41. package/lib/safety/explain.js +0 -0
  42. package/lib/safety/index.js +0 -0
  43. package/lib/safety/redact.js +0 -0
  44. package/lib/safety/rules.js +28 -0
  45. package/lib/scheduler.js +0 -0
  46. package/lib/source.js +0 -0
  47. package/lib/sqlite.js +2302 -55
  48. package/lib/sync.js +398 -71
  49. package/lib/text-safe.js +229 -0
  50. package/lib/timestamp.js +29 -9
  51. package/lib/tos/index.js +1 -1
  52. package/lib/tos/manifest.json +6 -6
  53. package/lib/tos/privacy.zh-CN.md +12 -9
  54. package/lib/tos/safety.zh-CN.md +4 -3
  55. package/lib/tos/summary.zh-CN.md +3 -3
  56. package/lib/tos/terms.zh-CN.md +8 -6
  57. package/lib/tui/color.js +164 -0
  58. package/lib/tui/index.js +33 -0
  59. package/lib/tui/json.js +124 -0
  60. package/lib/tui/labels.js +50 -0
  61. package/lib/tui/policy.js +108 -0
  62. package/lib/tui/render.js +371 -0
  63. package/lib/tui/sanitize.js +142 -0
  64. package/lib/tui/text-file.js +116 -0
  65. package/lib/tui/width.js +577 -0
  66. package/lib/ui.js +0 -0
  67. package/lib/undo.js +0 -0
  68. package/lib/untrusted.js +186 -0
  69. package/lib/vault.js +0 -0
  70. package/package.json +6 -5
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Suppress the one-time `node:sqlite is experimental` warning on Node 22.
3
+ *
4
+ * The warning is a runtime implementation detail, not part of the CLI
5
+ * contract; without this filter a plain `advisers status --json` writes it to
6
+ * stderr and breaks JSON-purity gates (and scripts that parse stderr).
7
+ * Only this exact warning is filtered; all other warnings pass through.
8
+ */
9
+ const originalEmitWarning = process.emitWarning.bind(process)
10
+
11
+ process.emitWarning = (warning, ...args) => {
12
+ const text = typeof warning === 'string' ? warning : String(warning?.message ?? '')
13
+ if (/SQLite is an experimental feature/i.test(text)) return
14
+ return originalEmitWarning(warning, ...args)
15
+ }
package/lib/notify.js CHANGED
@@ -10,6 +10,10 @@
10
10
  import { existsSync } from 'node:fs'
11
11
  import { spawn } from 'node:child_process'
12
12
  import { localDay } from './remind.js'
13
+ // 0.3.0 Wave 3 (docs/TUI.md §4): webhook/notifier failure detail is remote text
14
+ // and reaches stderr through bin's `webhook 未发送:` line. Sanitise at the library
15
+ // boundary so no caller can leak ANSI/C1/bidi or a second log line.
16
+ import { sanitizeConsoleText } from './text-safe.js'
13
17
 
14
18
  /**
15
19
  * Environment for the notification subprocess: an explicit allowlist.
@@ -43,7 +47,9 @@ function run(cmd, args, timeoutMs = 5000) {
43
47
  let err = ''
44
48
  child.stderr.on('data', (b) => { err += b.toString('utf8') })
45
49
  child.on('error', reject)
46
- child.on('close', (code) => code === 0 ? resolve() : reject(new Error(`${cmd} exited ${code}: ${err.trim().slice(0, 200)}`)))
50
+ // A local notifier's stderr is untrusted text (it may include the reminder
51
+ // title the caller passed); keep it to one sanitised line.
52
+ child.on('close', (code) => code === 0 ? resolve() : reject(new Error(`${cmd} exited ${code}: ${sanitizeConsoleText(err.trim(), { max: 200 })}`)))
47
53
  })
48
54
  }
49
55
 
@@ -109,9 +115,13 @@ function resolveWebhookTarget(options) {
109
115
  }
110
116
  }
111
117
 
118
+ /**
119
+ * One sanitised console line for a remote failure detail (webhook response body,
120
+ * fetch/abort message). ANSI/OSC/C1/bidi and line breaks are removed before the
121
+ * value can reach stderr, and the result is capped at `limit` code points.
122
+ */
112
123
  function truncateDetail(value, limit = 200) {
113
- const text = typeof value === 'string' ? value : String(value ?? '')
114
- return text.length > limit ? text.slice(0, limit) : text
124
+ return sanitizeConsoleText(value, { max: limit })
115
125
  }
116
126
 
117
127
  /**
package/lib/nudge.js CHANGED
File without changes
package/lib/ocr.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * silently treated as empty/valid text.
9
9
  */
10
10
  import { spawn } from 'node:child_process'
11
- import { statSync } from 'node:fs'
11
+ import { realpathSync, statSync } from 'node:fs'
12
12
  import { resolve, isAbsolute, relative } from 'node:path'
13
13
 
14
14
  /**
@@ -43,16 +43,36 @@ export function ocrConfigured() {
43
43
  return Boolean(process.env.ADVISERS_OCR_CMD)
44
44
  }
45
45
 
46
- export function assertOcrPath(file, cwd = process.cwd()) {
47
- const abs = resolve(cwd, file)
48
- const rel = relative(resolve(cwd), abs)
49
- if (rel.startsWith('..') || isAbsolute(rel)) throw new Error(`OCR file escapes workspace: ${file}`)
50
- const info = statSync(abs)
51
- if (!info.isFile()) throw new Error(`not a file: ${file}`)
52
- if (info.size > 10 * 1024 * 1024) throw new Error('OCR file is larger than 10 MB')
53
- return abs
46
+ function resolveContainedFile(file, cwd, label) {
47
+ if (typeof file !== 'string' || !file) throw new Error(label + ' path is required')
48
+ const rootLexical = resolve(cwd)
49
+ let root
50
+ try {
51
+ root = realpathSync(rootLexical)
52
+ } catch {
53
+ throw new Error(label + ' workspace does not exist: ' + cwd)
54
+ }
55
+ const abs = resolve(rootLexical, file)
56
+ const lexicalRel = relative(rootLexical, abs)
57
+ if (lexicalRel.startsWith('..') || isAbsolute(lexicalRel)) throw new Error(label + ' file escapes workspace: ' + file)
58
+ let real
59
+ try {
60
+ real = realpathSync(abs)
61
+ } catch (error) {
62
+ if (error && error.code === 'ENOENT') throw new Error(label + ' file not found: ' + file)
63
+ throw error
64
+ }
65
+ const realRel = relative(root, real)
66
+ if (realRel.startsWith('..') || isAbsolute(realRel)) throw new Error(label + ' file escapes workspace through a symlink: ' + file)
67
+ const info = statSync(real)
68
+ if (!info.isFile()) throw new Error('not a file: ' + file)
69
+ if (info.size > 10 * 1024 * 1024) throw new Error(label + ' file is larger than 10 MB')
70
+ return real
54
71
  }
55
72
 
73
+ export function assertOcrPath(file, cwd = process.cwd()) {
74
+ return resolveContainedFile(file, cwd, 'OCR')
75
+ }
56
76
  export async function runLocalOcr(file, { cmd = process.env.ADVISERS_OCR_CMD, timeoutMs = MAX_OCR_MS, cwd = process.cwd() } = {}) {
57
77
  if (!cmd) throw new Error('OCR is not configured; set ADVISERS_OCR_CMD to a local OCR executable (no cloud OCR is used)')
58
78
  const abs = assertOcrPath(file, cwd)
package/lib/pdf.js CHANGED
File without changes
File without changes
package/lib/pet-brief.js CHANGED
@@ -14,9 +14,8 @@
14
14
  * - `displayPolicy` states who may see the brief (public/private/none); it
15
15
  * defaults to `private` and is never `public` unless explicitly requested.
16
16
  */
17
- import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from 'node:fs'
18
- import { basename, dirname, join } from 'node:path'
19
17
  import { localDay } from './remind.js'
18
+ import { atomicWriteFileSync } from './fs-safe.js'
20
19
  import { classify } from './safety/index.js'
21
20
 
22
21
  export const PET_BRIEF_SCHEMA_VERSION = 2
@@ -113,7 +112,13 @@ function looksLikePersonName(value) {
113
112
  * titles/actions. `masked` is a count of replacements (for `redactions`).
114
113
  */
115
114
  function createRedactor(rawNames) {
116
- const names = [...new Set((rawNames ?? []).map(oneLine).filter((name) => looksLikePersonName(name)))]
115
+ // 0.3.0 P0-T2: dedupe the raw candidate strings before oneLine/regex work.
116
+ // The caller passes every commitment creditor + every listFacts() subject
117
+ // (233k strings at a 200k ledger, a few hundred distinct names); the old
118
+ // order ran oneLine + looksLikePersonName on all 233k rows. Deduping first
119
+ // is output-equivalent (the final Set still collapses oneLine collisions)
120
+ // and cuts the redactor setup by ~10x.
121
+ const names = [...new Set([...new Set(rawNames ?? [])].map(oneLine).filter((name) => looksLikePersonName(name)))]
117
122
  .sort((a, b) => b.length - a.length || cmp(a, b))
118
123
  let masked = 0
119
124
  const redact = (value) => {
@@ -144,12 +149,16 @@ function isPublicMatter(matter) {
144
149
  }
145
150
 
146
151
  function confidenceOfCommitment(commitment) {
152
+ // 0.3.0 P0-T2: a narrow projection answers "has evidence" in SQL so the
153
+ // pet-brief read path does not ship 66k evidence JSON strings to JS.
154
+ // Ledger rows (no hasEvidence field) keep the original array check.
155
+ if (commitment.hasEvidence !== undefined) return commitment.hasEvidence ? 0.95 : 0.75
147
156
  return Array.isArray(commitment.evidence) && commitment.evidence.length > 0 ? 0.95 : 0.75
148
157
  }
149
158
 
150
- function riskOfDue(dueMs, nowMs, today) {
159
+ function riskOfDue(dueMs, nowMs, today, dueDay) {
151
160
  if (dueMs < nowMs) return 'high'
152
- const day = localDay(new Date(dueMs).toISOString())
161
+ const day = dueDay ?? localDay(new Date(dueMs).toISOString())
153
162
  if (day === today) return 'high'
154
163
  if (dueMs <= nowMs + 3 * 86_400_000) return 'medium'
155
164
  return 'low'
@@ -167,6 +176,10 @@ const RISK_RANK = { low: 1, medium: 2, high: 3 }
167
176
  * @param {number} [options.maxItems]
168
177
  * @param {number} [options.minConfidence]
169
178
  * @param {'public'|'private'|'none'} [options.displayPolicy='private'] who may see the brief
179
+ * @param {string[]} [options.nameCandidates] Complete redactor name candidate set
180
+ * (all commitment creditors + all listFacts() subjects). Read paths that pass
181
+ * a narrow projection supply it so the redactor does not have to scan the
182
+ * full ledger; when omitted the ledger-derived set is used (unchanged).
170
183
  * @returns {object} contract v0.2 brief (no writes, no network).
171
184
  */
172
185
  export function buildPetBrief(ledger, options = {}) {
@@ -195,30 +208,80 @@ export function buildPetBrief(ledger, options = {}) {
195
208
 
196
209
  const allCommitments = ledger.listCommitments() ?? []
197
210
  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
- ]
211
+ // 0.3.0 P0-T2: the redactor only needs strings that can match brief output.
212
+ // A caller that hands in a narrow projection supplies the complete candidate
213
+ // set (every commitment creditor + every listFacts() subject) so this view
214
+ // never scans the full ledger for names (233k strings at a 200k ledger).
215
+ const suppliedNames = Array.isArray(options.nameCandidates) ? options.nameCandidates : null
216
+ const rawNames = suppliedNames
217
+ ? [...suppliedNames, ...allMatters.flatMap((matter) => matter.participants ?? [])]
218
+ : [
219
+ ...allCommitments.map((commitment) => commitment.creditor),
220
+ ...(ledger.listFacts() ?? []).map((fact) => fact.subject),
221
+ ...allMatters.flatMap((matter) => matter.participants ?? []),
222
+ ]
203
223
  const redactor = createRedactor(rawNames)
204
224
  const redacted = (value) => redactor.redact(value)
205
225
 
206
226
  // Public open commitments: matter must be active with secrecy < 2.
207
227
  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
228
+ // 0.2.3 P1a/B3: never drop a commitment silently. A public active matter (in
229
+ // particular a NON-default matter created with `matter add`) is projected by
230
+ // the arrays below; anything that cannot be projected is counted and disclosed
231
+ // in `redactions` instead of making counts quietly smaller.
232
+ const excludedOpen = { secrecy: 0, inactive: 0, dangling: 0 }
233
+ for (const commitment of openCommitments) {
234
+ if (publicMatterIds.has(commitment.matterId)) continue
235
+ const matter = matterById.get(commitment.matterId)
236
+ if (!matter) excludedOpen.dangling += 1
237
+ else if (matterSecrecy(matter) >= 2) excludedOpen.secrecy += 1
238
+ else excludedOpen.inactive += 1
239
+ }
240
+ // 0.3.0 P0-T2: parse each distinct dueAt string once (a 200k ledger has a
241
+ // few hundred distinct due dates, not ~67k), and keep only the top `limit`
242
+ // due commitments under the historical comparator instead of sorting all
243
+ // of them -- the caller only ever reads that slice.
244
+ const dueCache = new Map()
245
+ const dueInfoOf = (commitment) => {
246
+ const value = commitment.dueAt
247
+ if (!value) return null
248
+ const key = typeof value === 'string' ? value : String(value)
249
+ let info = dueCache.get(key)
250
+ if (info === undefined) {
251
+ const ms = Date.parse(value)
252
+ info = Number.isFinite(ms) ? { ms, day: localDay(new Date(ms).toISOString()) } : null
253
+ dueCache.set(key, info)
254
+ }
255
+ return info
212
256
  }
257
+ // Comparator of an already-kept entry against a new candidate, matching the
258
+ // historical sort: risk rank desc, dueMs asc, id asc.
259
+ const entryBeforeCandidate = (entry, risk, dueMs, id) =>
260
+ RISK_RANK[risk] - RISK_RANK[entry.risk] || entry.dueMs - dueMs || cmp(entry.commitment.id, id)
213
261
 
214
262
  // --- today: active public matters, urgency first, deterministic tie-break.
215
263
  const urgency = new Map()
264
+ const dueTop = []
216
265
  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)
266
+ const info = dueInfoOf(commitment)
267
+ if (info === null) continue
268
+ if (info.day === today || info.ms < nowMs) urgency.set(commitment.matterId, (urgency.get(commitment.matterId) ?? 0) + 1)
269
+ const risk = riskOfDue(info.ms, nowMs, today, info.day)
270
+ // Bounded insertion keeps the same stable order as the old sort: equal
271
+ // keys keep ledger order, only `limit` rows are ever held, and the
272
+ // confidence/evidence check runs only for rows that enter the top-N.
273
+ let index = dueTop.length
274
+ while (index > 0 && entryBeforeCandidate(dueTop[index - 1], risk, info.ms, commitment.id) > 0) index -= 1
275
+ if (index < limit) {
276
+ dueTop.splice(index, 0, {
277
+ commitment,
278
+ dueMs: info.ms,
279
+ dueDay: info.day,
280
+ risk,
281
+ confidence: confidenceOfCommitment(commitment),
282
+ })
283
+ if (dueTop.length > limit) dueTop.pop()
284
+ }
222
285
  }
223
286
  const todayItems = [...activeMatters]
224
287
  .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))
@@ -230,25 +293,19 @@ export function buildPetBrief(ledger, options = {}) {
230
293
  }))
231
294
 
232
295
  // --- 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 }) => ({
296
+ const commitmentItems = dueTop.map(({ commitment, dueDay, risk, confidence }) => ({
240
297
  id: clip(commitment.id, 64),
241
298
  matter: clip(commitment.matterId, 64),
242
299
  who: clip(redacted(commitment.creditor), 40),
243
300
  what: clip(redacted(commitment.action), 80),
244
- due: clip(localDay(new Date(dueMs).toISOString()) ?? clip(commitment.dueAt, 32), 32),
301
+ due: clip(dueDay ?? clip(commitment.dueAt, 32), 32),
245
302
  risk,
246
303
  confidence,
247
304
  }))
248
305
 
249
306
  // --- risks: deterministic derivation from the same public commitments.
250
307
  const risks = []
251
- for (const { commitment, dueMs, risk } of dueCommitments) {
308
+ for (const { commitment, dueMs, risk } of dueTop) {
252
309
  const who = clip(redacted(commitment.creditor), 12)
253
310
  const what = clip(redacted(commitment.action), 24)
254
311
  if (risk === 'high') {
@@ -270,20 +327,38 @@ export function buildPetBrief(ledger, options = {}) {
270
327
  })
271
328
  }
272
329
  }
273
- for (const commitment of publicOpen.filter((row) => !row.dueAt && isPublicMatter(matterById.get(row.matterId)))) {
330
+ // Undated public commitments each produce a medium risk. Only `limit` can
331
+ // ever be shown, so the loop keeps the smallest ids (the historical
332
+ // tie-break) instead of building and sorting one object per row; the
333
+ // per-summary safety check still runs for every candidate so the dropped
334
+ // count stays exact.
335
+ const noDueRisks = []
336
+ for (const commitment of publicOpen) {
337
+ if (commitment.dueAt) continue
338
+ if (!isPublicMatter(matterById.get(commitment.matterId))) continue
274
339
  const who = clip(redacted(commitment.creditor), 12)
275
340
  const what = clip(redacted(commitment.action), 24)
276
- risks.push({
277
- id: clip(`risk_${commitment.id}`, 64),
341
+ // The redaction runs before the confidence filter so the reported
342
+ // "masked N names" count matches the pre-0.3.0 whole-list behaviour.
343
+ const summary = clip(`${who}的${what}还没有截止时间`, 80)
344
+ if (0.75 < minConfidence) continue
345
+ if (isBlockedLine(summary, hmacKey)) { dropped.risks += 1; continue }
346
+ const id = clip(`risk_${commitment.id}`, 64)
347
+ let index = noDueRisks.length
348
+ while (index > 0 && cmp(id, noDueRisks[index - 1].id) < 0) index -= 1
349
+ if (index >= limit) continue
350
+ noDueRisks.splice(index, 0, {
351
+ id,
278
352
  level: 'medium',
279
- summary: clip(`${who}的${what}还没有截止时间`, 80),
353
+ summary,
280
354
  evidence: clip(commitment.id, 64),
281
355
  confidence: 0.75,
282
356
  })
357
+ if (noDueRisks.length > limit) noDueRisks.pop()
283
358
  }
284
359
  const byDay = new Map()
285
- for (const { commitment, dueMs } of dueCommitments) {
286
- const day = localDay(new Date(dueMs).toISOString())
360
+ for (const { commitment, dueDay } of dueTop) {
361
+ const day = dueDay
287
362
  if (!day || day < today) continue
288
363
  byDay.set(day, [...(byDay.get(day) ?? []), commitment])
289
364
  }
@@ -297,13 +372,12 @@ export function buildPetBrief(ledger, options = {}) {
297
372
  confidence: 0.72,
298
373
  })
299
374
  }
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
- })
375
+ for (const risk of risks) {
376
+ if (risk.confidence < minConfidence) continue
377
+ if (isBlockedLine(risk.summary, hmacKey)) { dropped.risks += 1; continue }
378
+ noDueRisks.push(risk)
379
+ }
380
+ const riskItems = noDueRisks
307
381
  .sort((a, b) => RISK_RANK[b.level] - RISK_RANK[a.level] || b.confidence - a.confidence || cmp(a.id, b.id))
308
382
  .slice(0, limit)
309
383
 
@@ -357,6 +431,9 @@ export function buildPetBrief(ledger, options = {}) {
357
431
  redactions.push('不含模型推理、系统提示或原始提示词')
358
432
  const excludedSecrecy = allMatters.filter((matter) => matterSecrecy(matter) >= 2).length
359
433
  if (excludedSecrecy > 0) redactions.push(clip(`已排除保密等级≥2 的事项(${excludedSecrecy} 个)`, 80))
434
+ if (excludedOpen.secrecy > 0) redactions.push(clip(`已排除保密事项下的承诺(${excludedOpen.secrecy} 条)`, 80))
435
+ if (excludedOpen.inactive > 0) redactions.push(clip(`已排除已归档/暂停事项的承诺(${excludedOpen.inactive} 条)`, 80))
436
+ if (excludedOpen.dangling > 0) redactions.push(clip(`已排除无法归属的承诺(${excludedOpen.dangling} 条,matter 不存在)`, 80))
360
437
  const droppedTotal = dropped.risks + dropped.lines
361
438
  if (droppedTotal > 0) redactions.push(clip(`已丢弃 ${droppedTotal} 条不安全内容(不展示原文)`, 80))
362
439
  if (!redactions.some((note) => note.startsWith('联系人')) && !redactions.some((note) => note.includes('客户名'))) {
@@ -611,8 +688,12 @@ function parseIsoWithZone(value, path, errors) {
611
688
  }
612
689
 
613
690
  /**
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.
691
+ * Atomically write a brief.
692
+ *
693
+ * 0.2.3 Wave 1: delegates to lib/fs-safe.js so the write uses the short-write
694
+ * loop, fsync, size verification and an atomic same-directory rename. A short
695
+ * write/ENOSPC can no longer install a truncated brief (robustness audit P1-2),
696
+ * and a failed write removes its temp file instead of leaving it behind.
616
697
  *
617
698
  * @param {string} filePath destination path
618
699
  * @param {object} brief brief object
@@ -620,25 +701,6 @@ function parseIsoWithZone(value, path, errors) {
620
701
  */
621
702
  export function writePetBriefAtomic(filePath, brief) {
622
703
  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
- }
704
+ atomicWriteFileSync(target, `${JSON.stringify(brief, null, 2)}\n`, { mode: 0o600 })
705
+ return target
644
706
  }