advisers 0.2.0 → 0.2.2

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/bin/advisers.js CHANGED
@@ -3,45 +3,20 @@ import { spawnSync } from 'node:child_process'
3
3
  import { chmodSync, closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'
4
4
  import { homedir, hostname } from 'node:os'
5
5
  import { createHash, randomBytes, randomUUID } from 'node:crypto'
6
- import { basename, dirname, extname, join } from 'node:path'
6
+ import { basename, dirname, extname, isAbsolute, join } from 'node:path'
7
7
  let SqliteStore
8
+ let acquireInstanceLock
9
+ let instanceLockPath
8
10
  try {
9
- ({ SqliteStore } = await import('../lib/sqlite.js'))
11
+ ({ SqliteStore, acquireInstanceLock, instanceLockPath } = await import('../lib/sqlite.js'))
10
12
  } catch (error) {
11
13
  if (String(error?.message || error).includes('node:sqlite')) {
12
- console.error(`Advisers needs Node >= 22.13 (node:sqlite). You have ${process.version}. Install Node 24 or use nvm-windows.`)
14
+ console.error(`Advisers needs Node >= 22.16 (node:sqlite). You have ${process.version}. Install Node 24 or use nvm-windows.`)
13
15
  process.exit(1)
14
16
  }
15
17
  throw error
16
18
  }
17
- import { runAgent } from '../lib/agent.js'
18
- import { chatCompletion } from '../lib/model.js'
19
- import { applyPreferenceDecay, buildRoutineCandidate, correctionStatement } from '../lib/learning.js'
20
- import { checkRoutine } from '../lib/routine.js'
21
- import { backupBeforeWrite, diffLatest, listBackups, undoLatest } from '../lib/undo.js'
22
- import { lintReview, materializeReview, reviewRun } from '../lib/review.js'
23
- import { classifyNudgeOutcome } from '../lib/nudge.js'
24
- import { buildDigest } from '../lib/digest.js'
25
- import { captureCandidates } from '../lib/capture.js'
26
19
  import { egressDeniedReason } from '../lib/egress.js'
27
- import { research as runResearch } from '../lib/research.js'
28
- import { reviewDocument } from '../lib/doc-review.js'
29
- import { buildHistory, buildOpening, buildPins, continuityProbes, ensurePins, fitHistory, shouldSummarize, summarizeTurns } from '../lib/context-window.js'
30
- import {
31
- PET_BRIEF_DEFAULT_DISPLAY_POLICY,
32
- PET_BRIEF_DISPLAY_POLICIES,
33
- PET_BRIEF_MAX_ITEMS,
34
- PET_BRIEF_MAX_LINE_LENGTH,
35
- PET_BRIEF_MAX_SUGGESTED_LINES,
36
- PET_BRIEF_MOODS,
37
- PET_BRIEF_SCHEMA_VERSION,
38
- PET_BRIEF_SOURCE,
39
- buildPetBrief,
40
- validatePetBrief,
41
- writePetBriefAtomic,
42
- } from '../lib/pet-brief.js'
43
- import { fetchImapMessages } from '../lib/imap.js'
44
- import { createReadOnlyServer } from '../lib/ui.js'
45
20
 
46
21
  /**
47
22
  * P1-1: lazy-load the heavy / rarely used libraries.
@@ -73,6 +48,26 @@ const loadTimestamp = lazyModule(() => import('../lib/timestamp.js'))
73
48
  const loadVault = lazyModule(() => import('../lib/vault.js'))
74
49
  const loadTos = lazyModule(() => import('../lib/tos/index.js'))
75
50
  const loadMcpServer = lazyModule(() => import('../lib/mcp-server.js'))
51
+ const loadSafety = lazyModule(() => import('../lib/safety/index.js'))
52
+ // P2-4 (0.2.1): every command used to pay for the full static import graph,
53
+ // including the model/agent stack, safety classifier, Pet Brief, UI server,
54
+ // IMAP client and review helpers (~63-75ms of compiled JS). They are only
55
+ // needed by a subset of commands, so each one is a memoized dynamic import.
56
+ const loadAgent = lazyModule(() => import('../lib/agent.js'))
57
+ const loadModel = lazyModule(() => import('../lib/model.js'))
58
+ const loadLearning = lazyModule(() => import('../lib/learning.js'))
59
+ const loadRoutine = lazyModule(() => import('../lib/routine.js'))
60
+ const loadUndo = lazyModule(() => import('../lib/undo.js'))
61
+ const loadReview = lazyModule(() => import('../lib/review.js'))
62
+ const loadNudge = lazyModule(() => import('../lib/nudge.js'))
63
+ const loadDigest = lazyModule(() => import('../lib/digest.js'))
64
+ const loadCapture = lazyModule(() => import('../lib/capture.js'))
65
+ const loadResearch = lazyModule(() => import('../lib/research.js'))
66
+ const loadDocReview = lazyModule(() => import('../lib/doc-review.js'))
67
+ const loadContextWindow = lazyModule(() => import('../lib/context-window.js'))
68
+ const loadPetBrief = lazyModule(() => import('../lib/pet-brief.js'))
69
+ const loadImap = lazyModule(() => import('../lib/imap.js'))
70
+ const loadUi = lazyModule(() => import('../lib/ui.js'))
76
71
 
77
72
  let core
78
73
  if (process.env.ADVISERS_CORE_LOCAL === '1') {
@@ -98,6 +93,73 @@ const DB = join(HOME, 'state.db')
98
93
  let mode = process.env.ADVISERS_STORE === 'json' ? 'json' : 'sqlite'
99
94
  let activeStore
100
95
 
96
+ /**
97
+ * 0.2.1 robustness audit P0-1: one SQLite writer per HOME.
98
+ *
99
+ * Every process that opens state.db first takes ~/.advisers/instance.lock
100
+ * (O_EXCL create). A second ordinary command waits (ADVISERS_LOCK_TIMEOUT_MS,
101
+ * default 10s) and then exits E_DB_LOCKED instead of saving from a stale
102
+ * snapshot; long-lived holders (ui/mcp/bridge) keep the lock while they run.
103
+ * The lock is released on exit and on SIGINT/SIGTERM. Read-only commands never
104
+ * open the store, so --version/help create no home and no lock.
105
+ */
106
+ let instanceLock = null
107
+ let storeExitHooksInstalled = false
108
+ const LOCK_PATH = instanceLockPath(HOME)
109
+
110
+ function lockCommandLabel() {
111
+ return process.argv
112
+ .slice(2)
113
+ .filter((value) => !/^--accept-tos(?:=|$)/.test(value))
114
+ .join(' ')
115
+ .slice(0, 160)
116
+ }
117
+
118
+ function releaseInstanceLock() {
119
+ const lock = instanceLock
120
+ instanceLock = null
121
+ try { lock?.release() } catch {}
122
+ }
123
+
124
+ function installStoreExitHooks() {
125
+ if (storeExitHooksInstalled) return
126
+ storeExitHooksInstalled = true
127
+ process.on('exit', releaseInstanceLock)
128
+ for (const signal of ['SIGINT', 'SIGTERM']) {
129
+ process.on(signal, () => {
130
+ releaseInstanceLock()
131
+ // With no other listener the signal should still terminate the process,
132
+ // with the conventional exit code; otherwise the command's own handler
133
+ // (ui/bridge) finishes its cleanup and exits normally.
134
+ if (process.listenerCount(signal) <= 1) process.exit(signal === 'SIGINT' ? 130 : 143)
135
+ })
136
+ }
137
+ }
138
+
139
+ /** Take the HOME instance lock once per process (SQLite store mode only). */
140
+ function ensureInstanceLock() {
141
+ if (mode !== 'sqlite') return null
142
+ if (instanceLock?.held) return instanceLock
143
+ installStoreExitHooks()
144
+ instanceLock = acquireInstanceLock({ home: HOME, command: lockCommandLabel() })
145
+ return instanceLock
146
+ }
147
+
148
+ /** Human-readable hint for E_DB_LOCKED/E_DB_CORRUPT; null for other errors. */
149
+ function storeFailureHint(error) {
150
+ if (error?.code === 'E_DB_LOCKED') {
151
+ return `advisers: ${error.message}\n` +
152
+ 'No changes were made and the JSON store was not used as a fallback. ' +
153
+ 'Wait for the other process or stop the long-running server, then retry.'
154
+ }
155
+ if (error?.code === 'E_DB_CORRUPT') {
156
+ return `advisers: ${error.message}\n` +
157
+ `Back up ${DB} before touching it (do not delete it), then run \`advisers doctor\`; ` +
158
+ 'the database was not rebuilt and no fallback store was created.'
159
+ }
160
+ return null
161
+ }
162
+
101
163
  /**
102
164
  * P0-1: one shared ICU formatter instead of `new Intl.DateTimeFormat` per
103
165
  * commitment. The old today()/tick() code built a fresh formatter for every
@@ -175,28 +237,128 @@ function saveJson(ledger) {
175
237
  writeFileSync(STATE, JSON.stringify(ledger.toJSON(), null, 2) + '\n')
176
238
  }
177
239
 
240
+ /** Sealed vault detection: vault bytes exist but the plaintext database does not. */
241
+ function vaultSealedPath() {
242
+ if (mode !== 'sqlite') return null
243
+ const sealed = `${DB}.vault`
244
+ return !existsSync(DB) && existsSync(sealed) ? sealed : null
245
+ }
246
+
247
+ /**
248
+ * Robustness audit P1-1: after `vault seal --remove` every ordinary command used
249
+ * to create a brand-new empty state.db (and doctor/backup reported on the empty
250
+ * database). Fail fast with a stable code instead; the vault commands and
251
+ * `evidence verify` never reach this path.
252
+ */
253
+ function vaultSealedError(sealed) {
254
+ const error = new Error(
255
+ `E_VAULT_SEALED: the database is sealed at ${sealed}; no plaintext database exists. ` +
256
+ 'Run `ADVISERS_VAULT_PASSPHRASE=... advisers vault unseal` (or `advisers vault status`); no empty database was created.',
257
+ )
258
+ error.code = 'E_VAULT_SEALED'
259
+ return error
260
+ }
261
+
262
+ /** Robustness audit P2-1: SQLite creates -wal/-shm with the process umask (often 0644). */
263
+ function secureDbSidecars() {
264
+ for (const file of [DB, `${DB}-wal`, `${DB}-shm`]) {
265
+ try { if (existsSync(file)) chmodSync(file, 0o600) } catch {}
266
+ }
267
+ }
268
+
178
269
  function openStore({ checkIntegrity = false } = {}) {
179
270
  if (!activeStore) {
271
+ const sealed = vaultSealedPath()
272
+ if (sealed) throw vaultSealedError(sealed)
180
273
  ensureHome()
274
+ // P0-1: take the single-writer lock before SQLite sees state.db. The sealed
275
+ // check above runs first so a sealed HOME creates neither a database nor a
276
+ // lock file. E_DB_LOCKED / E_DB_CORRUPT propagate to the caller.
277
+ ensureInstanceLock()
181
278
  activeStore = new SqliteStore(DB, { checkIntegrity })
182
- try { chmodSync(DB, 0o600) } catch {}
279
+ secureDbSidecars()
183
280
  } else if (checkIntegrity) {
184
281
  activeStore.assertIntegrity()
185
282
  }
186
283
  return activeStore
187
284
  }
188
285
 
189
- function loadLedger() {
286
+ /**
287
+ * P1-2 (0.2.2): per-table partial snapshot loaders.
288
+ *
289
+ * Every ledger command used to pay for the full 9-table store.load() -- 488ms
290
+ * at a 50k-row ledger and 1.2s at 100k in the 2026-11-17 performance audit
291
+ * round 2 -- even when it read one table or no rows at all. A read command now
292
+ * passes only the tables it uses (e.g. today/who load open commitments only)
293
+ * and the store records which rows were read so a later save() (tick waking a
294
+ * snoozed commitment) never deletes rows of tables that were not loaded.
295
+ */
296
+ const LEDGER_PART_LOADERS = {
297
+ matters: (store, options) => store.loadMatters(options),
298
+ facts: (store, options) => store.loadFacts(options),
299
+ commitments: (store, options) => store.loadCommitments(options),
300
+ preferences: (store, options) => store.loadPreferences(options),
301
+ links: (store, options) => store.loadLinks(options),
302
+ updates: (store, options) => store.loadUpdates(options),
303
+ routines: (store, options) => store.loadRoutines(options),
304
+ routinePatches: (store, options) => store.loadRoutinePatches(options),
305
+ routes: (store) => store.loadRoutes(),
306
+ }
307
+
308
+ /**
309
+ * Open the SQLite store for a ledger read, after honouring the legacy
310
+ * state.json -> SQLite migration and the sealed-vault/corrupt-DB fail-fast
311
+ * paths. Exits the process (with the documented hints) instead of ever
312
+ * silently falling back to the JSON store.
313
+ */
314
+ function openLedgerStore() {
190
315
  ensureHome()
191
- if (mode === 'json') return loadJson()
316
+ const sealed = vaultSealedPath()
317
+ if (sealed) throw vaultSealedError(sealed)
192
318
  try {
193
319
  if (!existsSync(DB) && existsSync(STATE)) {
194
320
  const ledger = loadJson()
195
321
  openStore().save(ledger.toJSON())
196
- return ledger
197
322
  }
198
- return Ledger.fromJSON(openStore().load(), LOCAL_PORTS)
323
+ return openStore()
324
+ } catch (error) {
325
+ const hint = storeFailureHint(error)
326
+ if (hint) {
327
+ console.error(hint)
328
+ process.exit(1)
329
+ }
330
+ console.error(`sqlite unavailable: ${error.message}`)
331
+ console.error('Run `advisers doctor`; refusing to silently switch to JSON (would split the ledger).')
332
+ process.exit(1)
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Load the ledger. No arguments: the full snapshot (write commands and
338
+ * anything that may save keep using this). With a table map such as
339
+ * `{ commitments: { status: 'open' } }` only those tables are read, mapped by
340
+ * the same row mappers, and the returned Ledger treats every omitted table as
341
+ * empty (Ledger.fromParts).
342
+ */
343
+ function loadLedger(parts = null) {
344
+ ensureHome()
345
+ if (mode === 'json') return loadJson()
346
+ const store = openLedgerStore()
347
+ try {
348
+ if (!parts) return Ledger.fromJSON(store.load(), LOCAL_PORTS)
349
+ const snapshot = { version: 1 }
350
+ for (const [table, options] of Object.entries(parts)) {
351
+ const loader = LEDGER_PART_LOADERS[table]
352
+ if (!loader) throw new Error(`unknown ledger table for partial load: ${table}`)
353
+ snapshot[table] = loader(store, options ?? {})
354
+ }
355
+ return Ledger.fromParts(snapshot, LOCAL_PORTS)
199
356
  } catch (error) {
357
+ const hint = storeFailureHint(error)
358
+ if (hint) {
359
+ console.error(hint)
360
+ process.exit(1)
361
+ }
200
362
  console.error(`sqlite unavailable: ${error.message}`)
201
363
  console.error('Run `advisers doctor`; refusing to silently switch to JSON (would split the ledger).')
202
364
  process.exit(1)
@@ -207,6 +369,11 @@ function exitStoreWriteFailure(error) {
207
369
  // P0-2: never fall back to state.json. The SQLite database is the only ledger
208
370
  // once it exists, so a JSON fallback would silently split the book (and the
209
371
  // command would still exit 0). Fail loudly instead.
372
+ const hint = storeFailureHint(error)
373
+ if (hint) {
374
+ console.error(hint)
375
+ process.exit(1)
376
+ }
210
377
  console.error(`advisers: could not write the ledger to ${DB}: ${error.message}`)
211
378
  console.error('Nothing was written to state.json; the SQLite database is the only ledger, so this command did not apply.')
212
379
  console.error('Retry the command; if it keeps failing run `advisers doctor` (or `advisers audit --check-db`).')
@@ -325,7 +492,7 @@ function runtimeFor(ledger) {
325
492
  }
326
493
 
327
494
  async function backupCliFile(path) {
328
- try { await backupBeforeWrite(path, { cwd: process.cwd(), backupDir: join(HOME, 'undo') }) } catch {}
495
+ try { const { backupBeforeWrite } = await loadUndo(); await backupBeforeWrite(path, { cwd: process.cwd(), backupDir: join(HOME, 'undo') }) } catch {}
329
496
  }
330
497
 
331
498
  function now() {
@@ -362,7 +529,8 @@ function printReceipt() {
362
529
  if (!store) { console.log('receipt requires SQLite store'); return }
363
530
  const delivery = store.listDeliveries(1)[0]
364
531
  if (!delivery) { console.log('还没有交付记录;先运行 `advisers office` / `advisers template`。'); return }
365
- const ledger = loadLedger()
532
+ // P1-2 (0.2.2): only this delivery's matter and its open commitments are read.
533
+ const ledger = loadLedger({ commitments: { status: 'open', matterId: delivery.matterId } })
366
534
  const open = ledger.openCommitments(delivery.matterId)
367
535
  console.log(`回执 ${delivery.id}`)
368
536
  console.log(`时间:${delivery.createdAt}`)
@@ -389,8 +557,9 @@ function printDeliveries() {
389
557
  console.log('no deliveries yet')
390
558
  return
391
559
  }
560
+ // P1-2 (0.2.2): only matter titles are needed for the fallback label.
392
561
  let matters = []
393
- try { matters = loadLedger().listMatters() } catch {}
562
+ try { matters = loadLedger({ matters: {} }).listMatters() } catch {}
394
563
  const title = new Map(matters.map((m) => [m.id, m.title]))
395
564
  for (const row of rows) {
396
565
  console.log(`${row.createdAt.slice(0, 19)} ${row.title ?? title.get(row.matterId) ?? row.matterId} [${row.tool ?? 'tool'}] ${row.validation ?? ''}`)
@@ -436,8 +605,15 @@ function friendlyError(error) {
436
605
  if (/database is locked/.test(message)) return 'database is busy; close other advisers processes and retry'
437
606
  return message
438
607
  }
439
- process.on('uncaughtException', (error) => { console.error(`advisers: ${friendlyError(error)}`); process.exit(1) })
440
- process.on('unhandledRejection', (error) => { console.error(`advisers: ${friendlyError(error)}`); process.exit(1) })
608
+ function reportFatalError(error) {
609
+ // E_DB_LOCKED / E_DB_CORRUPT get backup/doctor/concurrency guidance instead of
610
+ // the generic one-line message (commands that touch the store without going
611
+ // through loadLedger() end up here).
612
+ console.error(storeFailureHint(error) ?? `advisers: ${friendlyError(error)}`)
613
+ process.exit(1)
614
+ }
615
+ process.on('uncaughtException', reportFatalError)
616
+ process.on('unhandledRejection', reportFatalError)
441
617
  /**
442
618
  * TOS gate: `--accept-tos[=<version>]` is a global pre-dispatch flag, so it is
443
619
  * stripped from argv before the command is parsed (it may appear before or after
@@ -521,7 +697,7 @@ Usage:
521
697
  advisers mcp --stdio MCP server(7 工具 + 4 resources;写入口仅 pending 候选/回执校验)
522
698
  advisers evidence show <id> [--json] 承诺/事实/偏好→原文来源
523
699
  advisers deliver [--commit id] [--type confirmation|weekly|statement|ledger] [--format docx|xlsx|pdf] [--out f] 交付物
524
- advisers deliveries --pack [--out dir] 证据包(manifest/README/SHA256SUMS + DOCX 回执)
700
+ advisers deliveries --pack [--out dir] [--ids ...] [--all] 证据包(manifest/README/SHA256SUMS + DOCX 回执;默认上限 2000)
525
701
  advisers deliveries --receipt [--out dir] [--ids ...] [--all] [--recipient "Name <mail>"]
526
702
  交付回执包 v1.1(交付文件副本 + 全文件 SHA-256 + 证据;默认上限 2000)
527
703
  advisers evidence verify <dir> 离线校验回执包(JSON,exit 0/1;不读账本、不联网)
@@ -579,13 +755,32 @@ Environment:
579
755
  ADVISERS_PROGRESS=0 hide [tool] progress lines
580
756
  ADVISERS_ACCEPT_TOS=1 record TOS consent without a TTY (same as --accept-tos)
581
757
  ADVISERS_NOTIFY_WEBHOOK optional outbound webhook for remind --deliver --notify
758
+ ADVISERS_LOCK_TIMEOUT_MS wait for another advisers process to release the
759
+ instance lock (milliseconds; default 10000, 0 = fail immediately)
760
+
761
+ Concurrency:
762
+ One advisers process per ADVISERS_HOME uses the SQLite ledger at a time. The
763
+ CLI takes ~/.advisers/instance.lock before opening state.db; a second process
764
+ waits up to ADVISERS_LOCK_TIMEOUT_MS and then exits with E_DB_LOCKED instead
765
+ of writing from a stale ledger snapshot. ui / mcp / bridge keep the lock while
766
+ they run, so stop them before running other commands (or raise the timeout).
767
+ A stale lock (dead pid, or not refreshed for 1h) is reclaimed; SIGINT/SIGTERM
768
+ and normal exit release the lock. Concurrent commands therefore either run one
769
+ after another or fail explicitly — they never silently overwrite each other.
582
770
 
583
771
  Exit codes:
584
772
  0 success
585
- 1 user/config/runtime error (bad args, missing key, unknown id, failed verification)
773
+ 1 user/config/runtime error (bad args, missing key, unknown id, failed
774
+ verification, E_DB_LOCKED when another process holds the instance lock,
775
+ E_DB_CORRUPT when state.db is 0 bytes/corrupt: back it up and run
776
+ \`advisers doctor\`; damaged databases are never silently rebuilt)
586
777
  3 TOS consent required: non-interactive command blocked by the consent gate.
587
778
  Run \`advisers tos accept\` in a TTY, or pass --accept-tos / ADVISERS_ACCEPT_TOS=1.
588
779
  \`advisers evidence verify <dir>\` is offline/read-only and exempt from the gate.
780
+ Data-rights commands (audit/export/privacy/purge) and \`tos\` are exempt too.
781
+
782
+ Requirements:
783
+ Node >= 22.16 (node:sqlite). Node 22 prints an ExperimentalWarning for SQLite; Node 24 does not.
589
784
  `)
590
785
  }
591
786
 
@@ -861,10 +1056,24 @@ function tick(ledger, asJson = false) {
861
1056
  if (!c.dueAt || Date.parse(c.dueAt) > weekAhead) continue
862
1057
  candidates.push(c)
863
1058
  }
1059
+ // P2-2 (0.2.1): the recent-outcome read is bounded by the candidate set.
1060
+ // Only candidates whose pre-outcome level is L2/L3 can be downgraded by an
1061
+ // ignored run (the `level !== 'L1'` guard below), so those are the only ids
1062
+ // the query needs; the history table is never scanned as a whole.
1063
+ const baseLevelById = new Map()
1064
+ const outcomeIds = []
1065
+ for (const c of candidates) {
1066
+ const dueDay = localDayOf(c.dueAt)
1067
+ const msLeft = Date.parse(c.dueAt) - now
1068
+ let baseLevel = (msLeft < 0 || dueDay === localDay) ? 'L2' : 'L1'
1069
+ if (baseLevel === 'L2' && Date.parse(c.dueAt) < now - 86400_000 && process.env.ADVISERS_ALLOW_L3 === '1') baseLevel = 'L3'
1070
+ baseLevelById.set(c.id, baseLevel)
1071
+ if (baseLevel !== 'L1') outcomeIds.push(c.id)
1072
+ }
864
1073
  // P0-2: replace the per-commitment N+1 queries (listCommitmentNudges +
865
1074
  // countNudges) with three batch reads: recent outcomes per commitment,
866
1075
  // today's level counts and today's existing (commitment, level) keys.
867
- const recentByCommitment = store && candidates.length ? store.recentNudgeOutcomes(3) : new Map()
1076
+ const recentByCommitment = store && outcomeIds.length ? store.recentNudgeOutcomes(3, outcomeIds) : new Map()
868
1077
  const levelCounts = store && candidates.length ? store.countNudgesByDay(localDay) : new Map()
869
1078
  const existingKeys = store && candidates.length ? store.listNudgeLevelKeysByDay(localDay) : new Set()
870
1079
  const pendingKeys = new Set()
@@ -872,10 +1081,7 @@ function tick(ledger, asJson = false) {
872
1081
  let l2Today = levelCounts.get('L2') ?? 0
873
1082
  const nudgeRows = []
874
1083
  for (const c of candidates) {
875
- const dueDay = localDayOf(c.dueAt)
876
- const msLeft = Date.parse(c.dueAt) - now
877
- let level = (msLeft < 0 || dueDay === localDay) ? 'L2' : 'L1'
878
- if (level === 'L2' && Date.parse(c.dueAt) < now - 86400_000 && process.env.ADVISERS_ALLOW_L3 === '1') level = 'L3'
1084
+ let level = baseLevelById.get(c.id)
879
1085
  const recent = recentByCommitment.get(c.id) ?? []
880
1086
  if (recent.length === 3 && recent.every((outcome) => outcome === 'ignored') && level !== 'L1') level = level === 'L3' ? 'L2' : 'L1'
881
1087
  // Budgets keep the historical in-run semantics: a nudge already written by
@@ -938,25 +1144,39 @@ function printPrivacy(args = []) {
938
1144
  const store = dbStore()
939
1145
  let audit = null
940
1146
  try { const v = store?.verifyAudit(); if (v) audit = { ok: v.ok, count: v.count ?? 0 } } catch {}
1147
+ // Privacy audit P2-2: list every actual egress surface from the code base
1148
+ // instead of two hardcoded names, and never expose internal numbering.
1149
+ const egressSurfaces = [
1150
+ 'model provider — chat / brief --deep / review / learn review (only when ADVISERS_API_KEY is set; ADVISERS_BASE_URL)',
1151
+ 'research --web|--url — provider web search/read tool (explicit opt-in; no silent research egress)',
1152
+ 'capture --from-imap — read-only IMAP fetch from the server you configure (TLS by default)',
1153
+ 'remind --deliver --notify — optional outbound webhook or local notifier you configure',
1154
+ 'sync push|pull — the directory you provide; snapshots are AES-256-GCM encrypted before writing',
1155
+ 'bridge — Hermes file gateway: inbox/outbox JSON files are handed to the Hermes process',
1156
+ 'MCP --stdio / DSH host tools / pet-brief — local consumers; the host or reader may forward the data',
1157
+ 'ocr / timestamp — local adapter subprocess you configure (this CLI does not call a cloud OCR/TSA)',
1158
+ ]
941
1159
  const facts = {
942
1160
  home: HOME,
943
1161
  database: DB,
944
1162
  telemetry: 'none',
945
1163
  default_egress: 'none',
946
- explicit_egress: ['research --web|--url', 'model calls (chat/capture/review/brief --deep)'],
947
- provider: { baseUrl: process.env.ADVISERS_BASE_URL ?? 'https://api.deepseek.com', model: process.env.ADVISERS_MODEL ?? 'deepseek-chat' },
948
- secret_matter: 'egress fail-closed (secrecy > 0)',
949
- at_rest_encryption: 'not implemented for general data; secret-matter encryption is E9-T3',
1164
+ explicit_egress: egressSurfaces,
1165
+ provider: { baseUrl: process.env.ADVISERS_BASE_URL ?? 'https://api.deepseek.com', model: process.env.ADVISERS_MODEL ?? 'deepseek-flash' },
1166
+ secret_matter: 'egress fail-closed for secrecy > 0 on the wired model paths (local rule layer)',
1167
+ at_rest_encryption: 'opt-in database vault (advisers vault seal); general data is not encrypted at rest',
950
1168
  audit,
951
1169
  export: 'advisers export --all',
952
1170
  delete: 'advisers purge <matter> --yes',
953
1171
  }
954
1172
  if (asJson) { console.log(JSON.stringify(facts, null, 2)); return }
955
1173
  console.log('privacy · local data facts')
1174
+ console.log('self-attestation(本地自检口径:只读本机文件/环境与纯函数,不是第三方审计;本命令不联网)')
956
1175
  console.log(`home: ${facts.home}`)
957
1176
  console.log(`database: ${facts.database}`)
958
- console.log(`telemetry: ${facts.telemetry}`)
959
- console.log(`egress: ${facts.default_egress} by default; explicit: ${facts.explicit_egress.join(', ')}`)
1177
+ console.log(`telemetry: ${facts.telemetry} (build-time statement; this package contains no telemetry code)`)
1178
+ console.log(`egress: ${facts.default_egress} by default — nothing leaves the machine until you configure/opt in to:`)
1179
+ for (const surface of egressSurfaces) console.log(` - ${surface}`)
960
1180
  console.log(`provider: ${facts.provider.model} @ ${facts.provider.baseUrl}`)
961
1181
  console.log(`secret: ${facts.secret_matter}`)
962
1182
  console.log(`encryption: ${facts.at_rest_encryption}`)
@@ -965,15 +1185,18 @@ function printPrivacy(args = []) {
965
1185
  console.log(`delete: ${facts.delete}`)
966
1186
  if (prove) {
967
1187
  const checks = [
968
- ['home exists', existsSync(HOME)],
969
- ['database exists', existsSync(DB)],
970
- ['audit verified', Boolean(audit?.ok)],
971
- ['telemetry disabled', facts.telemetry === 'none'],
972
- ['no default network egress', facts.default_egress === 'none'],
973
- ['secret matter fail-closed', (() => { try { return Boolean(egressDeniedReason({ secrecy: 1 }, 'prove')) && !egressDeniedReason({ secrecy: 0 }, 'prove') } catch { return false } })()],
1188
+ ['home exists', existsSync(HOME), 'local self-check'],
1189
+ ['database exists', existsSync(DB), 'local self-check'],
1190
+ ['audit verified', Boolean(audit?.ok), 'local self-check: keyed hash chain'],
1191
+ ['telemetry disabled', facts.telemetry === 'none', 'local self-check: build-time statement, not network-verified'],
1192
+ ['no default network egress', facts.default_egress === 'none', 'local self-check: build-time statement, not network-verified'],
1193
+ ['secret matter fail-closed', (() => { try { return Boolean(egressDeniedReason({ secrecy: 1 }, 'prove')) && !egressDeniedReason({ secrecy: 0 }, 'prove') } catch { return false } })(), 'local self-check: egress-gate function; per-path wiring is covered by tests'],
974
1194
  ]
1195
+ console.log('')
1196
+ console.log('self-checks(本地自检:结果只说明本机文件/配置与纯函数检查;不是第三方审计,也不证明运行时无出网)')
975
1197
  let failed = 0
976
- for (const [name, ok] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name}`) }
1198
+ for (const [name, ok, detail] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name} (${detail})`) }
1199
+ console.log('egress gate coverage: chat/model, review, research, brief --deep, learn review, bridge and capture are wired to the local secrecy gate; the other surfaces listed above are self-attested.')
977
1200
  if (failed) process.exitCode = 1
978
1201
  }
979
1202
  }
@@ -995,7 +1218,12 @@ function printLinks() {
995
1218
  * allowlist). The test suite asserts the generated document is deep-equal to
996
1219
  * the canonical snapshot in docs/pet-brief/schema-v0.2.json.
997
1220
  */
998
- function petBriefJsonSchema() {
1221
+ async function petBriefJsonSchema() {
1222
+ const {
1223
+ PET_BRIEF_DEFAULT_DISPLAY_POLICY, PET_BRIEF_DISPLAY_POLICIES, PET_BRIEF_MAX_ITEMS,
1224
+ PET_BRIEF_MAX_LINE_LENGTH, PET_BRIEF_MAX_SUGGESTED_LINES, PET_BRIEF_MOODS,
1225
+ PET_BRIEF_SCHEMA_VERSION, PET_BRIEF_SOURCE,
1226
+ } = await loadPetBrief()
999
1227
  const maxItems = PET_BRIEF_MAX_ITEMS
1000
1228
  const id = { type: 'string', minLength: 1, maxLength: 64 }
1001
1229
  const confidence = { type: 'number', minimum: 0, maximum: 1 }
@@ -1088,6 +1316,11 @@ function petBriefJsonSchema() {
1088
1316
  * legacy/missing-displayPolicy into errors instead).
1089
1317
  */
1090
1318
  async function petBrief(args) {
1319
+ const {
1320
+ PET_BRIEF_DEFAULT_DISPLAY_POLICY, PET_BRIEF_DISPLAY_POLICIES, PET_BRIEF_MAX_ITEMS,
1321
+ PET_BRIEF_MAX_LINE_LENGTH, PET_BRIEF_MAX_SUGGESTED_LINES, PET_BRIEF_MOODS,
1322
+ PET_BRIEF_SCHEMA_VERSION, PET_BRIEF_SOURCE, buildPetBrief, validatePetBrief, writePetBriefAtomic,
1323
+ } = await loadPetBrief()
1091
1324
  const { flags } = parseFlags(args)
1092
1325
  const asJson = args.includes('--json')
1093
1326
  const check = args.includes('--check')
@@ -1104,7 +1337,7 @@ async function petBrief(args) {
1104
1337
  if (inFile !== undefined || outFlag !== undefined || displayPolicyFlag !== undefined || asJson || check) {
1105
1338
  return fail('E_USAGE', '--print-schema cannot be combined with other pet-brief options')
1106
1339
  }
1107
- console.log(JSON.stringify(petBriefJsonSchema(), null, 2))
1340
+ console.log(JSON.stringify(await petBriefJsonSchema(), null, 2))
1108
1341
  return
1109
1342
  }
1110
1343
  if (inFile !== undefined && !check) return fail('E_USAGE', '--in can only be used with --check')
@@ -1129,6 +1362,15 @@ async function petBrief(args) {
1129
1362
  if (!result.ok) process.exitCode = 1
1130
1363
  return
1131
1364
  }
1365
+ // P1-1/P0-1: pet-brief reads state.db read-only, but it still shares the
1366
+ // single-writer HOME. Report a sealed vault with the stable code instead of
1367
+ // "store not found", and take the instance lock so the read cannot race a
1368
+ // seal/unseal/sync-pull replacing the database.
1369
+ if (mode === 'sqlite') {
1370
+ const sealed = vaultSealedPath()
1371
+ if (sealed) return fail('E_VAULT_SEALED', 'the database is sealed at ' + sealed + '; run "ADVISERS_VAULT_PASSPHRASE=... advisers vault unseal" first (no empty database was created)')
1372
+ ensureInstanceLock()
1373
+ }
1132
1374
  const { readLedgerSnapshotReadOnly } = await import('../lib/pet-brief-store.js')
1133
1375
  let snapshot
1134
1376
  try {
@@ -1181,18 +1423,56 @@ function printPreferences() {
1181
1423
  async function doctor() {
1182
1424
  const rows = []
1183
1425
  const check = (name, ok, detail = '') => rows.push({ name, ok, detail })
1184
- check('node', Number(process.versions.node.split('.')[0]) > 22 || (Number(process.versions.node.split('.')[0]) === 22 && Number(process.versions.node.split('.')[1]) >= 13), process.version)
1426
+ const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(Number)
1427
+ check('node', nodeMajor > 22 || (nodeMajor === 22 && nodeMinor >= 16), process.version)
1185
1428
  try { ensureHome(); check('home', existsSync(HOME), HOME) } catch (error) { check('home', false, error.message) }
1186
- try {
1187
- const store = openStore()
1188
- const integrity = store.assertIntegrity()
1189
- check('sqlite', integrity === 'ok', `${DB} (${integrity})`)
1190
- const audit = store.verifyAudit()
1191
- check('audit', audit.ok, audit.ok ? `${audit.count} entries` : `BROKEN at seq ${audit.seq}`)
1192
- check('schema', true, String(store.db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value ?? '?'))
1193
- } catch (error) { check('sqlite', false, error.message) }
1429
+ // Sealed vault (robustness audit P1-1): report the real state instead of
1430
+ // silently creating an empty database and printing all-PASS diagnostics.
1431
+ const sealed = vaultSealedPath()
1432
+ if (sealed) {
1433
+ check('vault', true, `sealed (${sealed}); run ` + '`advisers vault unseal`')
1434
+ check('lock', true, 'not taken (vault sealed)')
1435
+ check('database', true, 'skipped (vault sealed)')
1436
+ check('sqlite', true, 'skipped (vault sealed)')
1437
+ check('audit', true, 'skipped (vault sealed)')
1438
+ check('schema', true, 'skipped (vault sealed)')
1439
+ } else {
1440
+ try {
1441
+ const store = openStore()
1442
+ // P0-1: doctor holds the instance lock while it inspects the store; the
1443
+ // row also exposes the lock path so a stuck holder can be diagnosed.
1444
+ check('lock', true, `${instanceLock?.path ?? LOCK_PATH} (held by pid ${process.pid})`)
1445
+ let dbBytes = 0
1446
+ try { dbBytes = statSync(DB).size } catch {}
1447
+ check('database', dbBytes > 0, dbBytes > 0 ? `${DB} (${dbBytes} bytes)` : `E_DB_CORRUPT: ${DB} is 0 bytes; back it up and restore`)
1448
+ const integrity = store.assertIntegrity()
1449
+ check('sqlite', integrity === 'ok', `${DB} (${integrity})`)
1450
+ const audit = store.verifyAudit()
1451
+ check('audit', audit.ok, audit.ok ? `${audit.count} entries` : `BROKEN at seq ${audit.seq}`)
1452
+ check('schema', true, String(store.db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value ?? '?'))
1453
+ } catch (error) {
1454
+ if (error?.code === 'E_DB_LOCKED') {
1455
+ // Another live process holds the store; this is a real FAIL, not a
1456
+ // reason to silently inspect a stale snapshot.
1457
+ check('lock', false, error.message)
1458
+ check('sqlite', false, 'skipped (another instance holds the instance lock)')
1459
+ } else if (error?.code === 'E_DB_CORRUPT') {
1460
+ check('lock', true, `${instanceLock?.path ?? LOCK_PATH} (held by pid ${process.pid})`)
1461
+ check('database', false, error.message)
1462
+ check('sqlite', false, 'refusing to open a 0-byte/corrupt database (no silent rebuild)')
1463
+ check('audit', false, 'skipped (database damaged)')
1464
+ check('schema', false, 'skipped (database damaged)')
1465
+ } else {
1466
+ check('lock', Boolean(instanceLock?.held), instanceLock?.held ? `${LOCK_PATH} (held by pid ${process.pid})` : 'not taken')
1467
+ check('sqlite', false, error.message)
1468
+ }
1469
+ }
1470
+ }
1471
+ // P2-3 (0.2.1): probe resolvability instead of importing the office barrel
1472
+ // (222-573ms, and only needed to answer "is the peer installed?").
1194
1473
  let officeOk = false
1195
- try { await import('advisers-office'); officeOk = true } catch { try { await import('../../office/dist/index.js'); officeOk = true } catch {} }
1474
+ try { officeOk = Boolean(import.meta.resolve('advisers-office')) } catch {}
1475
+ if (!officeOk) officeOk = existsSync(new URL('../../office/dist/index.js', import.meta.url))
1196
1476
  check('office', officeOk, officeOk ? 'advisers-office resolvable' : 'npm i -g advisers-office@next, or ADVISERS_OFFICE_LOCAL=1 in checkout')
1197
1477
  check('policy', Boolean(StrictPolicyPack), StrictPolicyPack ? 'strict pack loaded' : 'policy pack missing')
1198
1478
  check('model', true, process.env.ADVISERS_API_KEY ? 'API key present (not tested)' : 'optional; ADVISERS_API_KEY not set')
@@ -1214,7 +1494,6 @@ function init() {
1214
1494
  }
1215
1495
 
1216
1496
  function printStatus(asJson = false) {
1217
- const ledger = loadLedger()
1218
1497
  const data = {
1219
1498
  version: VERSION,
1220
1499
  node: process.version,
@@ -1222,19 +1501,32 @@ function printStatus(asJson = false) {
1222
1501
  home: HOME,
1223
1502
  store: mode === 'sqlite' ? { type: 'sqlite', path: DB } : { type: mode, path: STATE },
1224
1503
  model: modelLabel(),
1225
- matters: ledger.listMatters().length,
1226
- prefs: ledger.listPreferences().length,
1227
- routines: ledger.listRoutines().length,
1228
- links: ledger.listLinks().length,
1229
1504
  soul: existsSync(SOUL) ? 'present' : 'not initialized',
1230
1505
  }
1231
- try {
1232
- const store = dbStore()
1233
- data.sessions = store?.listSessions(100).length ?? 0
1234
- data.deliveries = store?.countDeliveries() ?? 0
1235
- const usage = store?.sumModelUsage?.()
1236
- if (usage?.calls) data.modelUsage = usage
1237
- } catch {}
1506
+ if (mode === 'json') {
1507
+ // Legacy JSON store: the snapshot is small, keep the historical behaviour.
1508
+ const ledger = loadLedger()
1509
+ data.matters = ledger.listMatters().length
1510
+ data.prefs = ledger.listPreferences().length
1511
+ data.routines = ledger.listRoutines().length
1512
+ data.links = ledger.listLinks().length
1513
+ data.sessions = 0
1514
+ data.deliveries = 0
1515
+ } else {
1516
+ // P1-2 (0.2.2): COUNT-only status. The old path loaded all 9 tables just to
1517
+ // count four of them (664ms / 352MB RSS at 50k rows in the round-2 audit).
1518
+ // listMatters()/listPreferences()/listRoutines()/listLinks() filter status,
1519
+ // so the counts replicate those filters exactly.
1520
+ const store = openLedgerStore()
1521
+ data.matters = store.countMatters({ status: 'active' })
1522
+ data.prefs = store.countPreferences({ status: 'confirmed' })
1523
+ data.routines = store.countRoutines()
1524
+ data.links = store.countLinks({ excludeRejected: true })
1525
+ data.sessions = store.countSessions()
1526
+ data.deliveries = store.countDeliveries()
1527
+ const usage = store.sumModelUsage()
1528
+ if (usage.calls) data.modelUsage = usage
1529
+ }
1238
1530
  if (asJson) { console.log(JSON.stringify(data, null, 2)); return }
1239
1531
  console.log(`version ${data.version}`)
1240
1532
  console.log(`node ${data.node}`)
@@ -1252,10 +1544,11 @@ function printStatus(asJson = false) {
1252
1544
  console.log(`soul ${data.soul}`)
1253
1545
  }
1254
1546
 
1255
- function loadHistory(conversationId) {
1547
+ async function loadHistory(conversationId) {
1256
1548
  try {
1257
1549
  const store = dbStore()
1258
1550
  if (!store) return { turns: [], summary: '' }
1551
+ const { buildHistory } = await loadContextWindow()
1259
1552
  const turns = store.listTurns(conversationId, 100)
1260
1553
  const summary = store.getSessionSummary(conversationId)
1261
1554
  return buildHistory({ turns, summary: summary?.summary, throughSeq: summary?.throughSeq ?? 0 })
@@ -1273,6 +1566,7 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
1273
1566
  try {
1274
1567
  const store = dbStore()
1275
1568
  if (!store) return
1569
+ const { shouldSummarize, buildPins, summarizeTurns, ensurePins, continuityProbes } = await loadContextWindow()
1276
1570
  const turns = store.listTurns(conversationId, 500)
1277
1571
  const old = store.getSessionSummary(conversationId)
1278
1572
  if (!shouldSummarize(turns, old?.throughSeq ?? 0, 10, 20)) return
@@ -1285,6 +1579,7 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
1285
1579
  if (apiKey && process.env.ADVISERS_LLM_SUMMARY !== '0') {
1286
1580
  try {
1287
1581
  const transcript = fresh.map((t) => `${t.role === 'user' ? '用户' : '助手'}:${t.content}`).join('\n')
1582
+ const { chatCompletion } = await loadModel()
1288
1583
  const response = await chatCompletion({
1289
1584
  apiKey,
1290
1585
  baseUrl: baseUrl || 'https://api.deepseek.com',
@@ -1305,10 +1600,11 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
1305
1600
  } catch {}
1306
1601
  }
1307
1602
 
1308
- function printOpening(conversationId) {
1603
+ async function printOpening(conversationId) {
1309
1604
  try {
1310
1605
  const store = dbStore()
1311
1606
  if (!store) return
1607
+ const { buildOpening } = await loadContextWindow()
1312
1608
  const turns = store.listTurns(conversationId, 20)
1313
1609
  const summary = store.getSessionSummary(conversationId)
1314
1610
  const commitments = loadLedger().openCommitments()
@@ -1316,7 +1612,8 @@ function printOpening(conversationId) {
1316
1612
  } catch {}
1317
1613
  }
1318
1614
 
1319
- function applyNudgeFeedback(text) {
1615
+ async function applyNudgeFeedback(text) {
1616
+ const { classifyNudgeOutcome } = await loadNudge()
1320
1617
  const outcome = classifyNudgeOutcome(text)
1321
1618
  if (!outcome) return
1322
1619
  try {
@@ -1328,7 +1625,75 @@ function applyNudgeFeedback(text) {
1328
1625
  } catch {}
1329
1626
  }
1330
1627
 
1331
- async function runTurn({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [] }) {
1628
+ let safetyModule
1629
+ let lastTurnSafetyBlock = null
1630
+
1631
+ /** Build the structured audit reason for a safety decision (never the original text). */
1632
+ function safetyReasonFor(result, fallbackSurface = 'model.output') {
1633
+ try {
1634
+ return safetyModule.buildAuditReason({
1635
+ rulesetVersion: result?.rulesetVersion,
1636
+ surface: result?.surface ?? fallbackSurface,
1637
+ action: result?.action ?? 'block',
1638
+ code: result?.code ?? 'CONTENT_SAFETY_BLOCKED',
1639
+ ruleIds: result?.ruleIds,
1640
+ evidenceHash: result?.evidenceHash,
1641
+ })
1642
+ } catch {
1643
+ return `code=${result?.code ?? 'CONTENT_SAFETY_BLOCKED'}`
1644
+ }
1645
+ }
1646
+
1647
+ /**
1648
+ * Report a local content-safety block without echoing or persisting the original
1649
+ * text (privacy audit P2 / security audit SEC2-04): user-facing rejection plus a
1650
+ * keyed `actor: 'safety'` audit row so the block is explainable later.
1651
+ */
1652
+ function recordSafetyBlock(result, { action = 'safety.chat', surface = 'model.output' } = {}) {
1653
+ const code = result?.code || 'CONTENT_SAFETY_BLOCKED'
1654
+ const ruleIds = Array.isArray(result?.ruleIds) ? result.ruleIds : []
1655
+ console.error('advisers: 内容安全审核未通过(CONTENT_SAFETY_BLOCKED)')
1656
+ console.error('本次输入未发送到模型,也未写入账本或会话;被拒内容不会保存为标题或会话。')
1657
+ console.error(`本地自检(${surface}):code=${code} rules=${ruleIds.join(',') || '-'};这是本地规则层判定,不是人工审核。`)
1658
+ if (result?.crisis) console.error('如果你或他人正处于危险中,请立即联系当地紧急服务或可信任的人。')
1659
+ try {
1660
+ ensureHome()
1661
+ dbStore()?.appendAudit({ actor: 'safety', action, allowed: false, reason: safetyReasonFor(result, surface) })
1662
+ } catch {}
1663
+ }
1664
+
1665
+ /**
1666
+ * Wrapper around runTurnInner: local content-safety pre-flight BEFORE
1667
+ * runtime.ingest()/upsertSession() (SEC2-04). A blocked input must not create a
1668
+ * matter, a session title or a ledger fact, and must not purge the active matter
1669
+ * pointer later (the old order persisted the raw text as sessions.title).
1670
+ */
1671
+ async function runTurn(options) {
1672
+ lastTurnSafetyBlock = null
1673
+ ensureHome()
1674
+ safetyModule ??= await loadSafety()
1675
+ const text = String(options?.text ?? '')
1676
+ const decision = safetyModule.classify(text, { surface: 'model.output', hmacKey: process.env.ADVISERS_AUDIT_KEY })
1677
+ if (decision.action === 'block') {
1678
+ lastTurnSafetyBlock = decision
1679
+ recordSafetyBlock(decision, { surface: 'chat.input' })
1680
+ return undefined
1681
+ }
1682
+ try {
1683
+ return await runTurnInner(options)
1684
+ } catch (error) {
1685
+ // Context/history/attachments can still trip the model choke point; audit
1686
+ // it as safety rather than letting it look like an unexplained crash.
1687
+ if (error?.name === 'ContentSafetyError') {
1688
+ lastTurnSafetyBlock = error
1689
+ recordSafetyBlock(error, { surface: error.surface || 'model.output' })
1690
+ return undefined
1691
+ }
1692
+ throw error
1693
+ }
1694
+ }
1695
+
1696
+ async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [] }) {
1332
1697
  const result = await runtime.ingest({
1333
1698
  linkId: 'cli',
1334
1699
  accountId: 'local',
@@ -1343,7 +1708,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1343
1708
  console.log(`[ignored: ${result.reason}]`)
1344
1709
  return
1345
1710
  }
1346
- applyNudgeFeedback(text)
1711
+ await applyNudgeFeedback(text)
1347
1712
  const context = runtime.lastContext
1348
1713
  if (!context) throw new Error('runtime did not produce a context')
1349
1714
  const egressDenied = egressDeniedReason(context.matter, 'chat')
@@ -1401,7 +1766,8 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1401
1766
  if (!intent?.questions?.length) console.log('[local] 未配置模型;已记录到当前会话,但没有创建承诺或文件。设置 ADVISERS_API_KEY 后可用自然语言执行;也可用 `advisers office` / `advisers template` 直接生成文件。')
1402
1767
  return intent?.questions?.[0]
1403
1768
  }
1404
- const history = loadHistory(conversationId)
1769
+ const { buildPins, fitHistory } = await loadContextWindow()
1770
+ const history = await loadHistory(conversationId)
1405
1771
  const pins = buildPins({
1406
1772
  preferences: ledger.listPreferences({ matterId: context.matter.id }),
1407
1773
  commitments: ledger.openCommitments(context.matter.id),
@@ -1409,6 +1775,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1409
1775
  const prompt = pins ? `${context.prompt}\n<session-pins>\n${pins}\n</session-pins>` : context.prompt
1410
1776
  const fitted = fitHistory({ system: prompt, summary: history.summary, history: history.turns, current: agentText, maxTokens: Number(process.env.ADVISERS_CONTEXT_TOKENS || 12000) })
1411
1777
  if (fitted.trimmed) console.log(`[compact] 裁剪 ${fitted.trimmed} 轮旧历史`)
1778
+ const { runAgent } = await loadAgent()
1412
1779
  const { reply, artifacts, toolLog } = await runAgent({
1413
1780
  runtime,
1414
1781
  text: agentText,
@@ -1475,6 +1842,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1475
1842
  if (runId && process.env.ADVISERS_LEARNING === 'auto' && apiKey) {
1476
1843
  try {
1477
1844
  const run = dbStore()?.listTaskRuns(50).find((r) => r.id === runId)
1845
+ const { reviewRun, lintReview, materializeReview } = await loadReview()
1478
1846
  const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
1479
1847
  const checked = lintReview(review, { run, routines: ledger.listRoutines() })
1480
1848
  if (checked.ok && checked.review.verdict !== 'NONE') {
@@ -1484,6 +1852,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1484
1852
  }
1485
1853
  } catch {}
1486
1854
  }
1855
+ const { buildRoutineCandidate } = await loadLearning()
1487
1856
  const candidate = buildRoutineCandidate({ text, toolLog, artifacts })
1488
1857
  if (candidate && !ledger.listRoutines().some((r) => r.name === candidate.name)) {
1489
1858
  try {
@@ -1521,6 +1890,7 @@ async function chat(args) {
1521
1890
  const ledger = loadLedger()
1522
1891
  const runtime = runtimeFor(ledger)
1523
1892
  await runTurn({ runtime, ledger, text, conversationId: latestConversationId(), attachments: files })
1893
+ if (lastTurnSafetyBlock) process.exitCode = 1
1524
1894
  saveLedger(ledger)
1525
1895
  }
1526
1896
 
@@ -1540,7 +1910,7 @@ async function repl() {
1540
1910
  }
1541
1911
  try {
1542
1912
  const latest = dbStore()?.listSessions(1)[0]
1543
- printOpening(latest?.conversationId ?? conversationId)
1913
+ await printOpening(latest?.conversationId ?? conversationId)
1544
1914
  } catch {}
1545
1915
  console.log('/help for commands, /quit to leave')
1546
1916
 
@@ -1645,6 +2015,7 @@ async function repl() {
1645
2015
  continue
1646
2016
  }
1647
2017
  if (text === '/decay') {
2018
+ const { applyPreferenceDecay } = await loadLearning()
1648
2019
  const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
1649
2020
  saveLedger(ledger)
1650
2021
  console.log(`[decay] ${changed.length} preference(s) updated`)
@@ -1664,6 +2035,7 @@ async function repl() {
1664
2035
  if (text === '/week') { printWeek(ledger); continue }
1665
2036
  if (text === '/digest' || text === '/digest day' || text === '/digest week') {
1666
2037
  const store = dbStore()
2038
+ const { buildDigest } = await loadDigest()
1667
2039
  console.log(buildDigest({
1668
2040
  period: text.endsWith('week') ? 'week' : 'day',
1669
2041
  turns: store?.listTurns(conversationId, 200) ?? [],
@@ -1673,11 +2045,13 @@ async function repl() {
1673
2045
  continue
1674
2046
  }
1675
2047
  if (text === '/diff') {
2048
+ const { diffLatest } = await loadUndo()
1676
2049
  const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
1677
2050
  console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
1678
2051
  continue
1679
2052
  }
1680
2053
  if (text === '/undo') {
2054
+ const { undoLatest } = await loadUndo()
1681
2055
  const result = await undoLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo'), force: args.includes('--force') })
1682
2056
  console.log(result.ok ? `已回滚:${result.path}` : `撤销失败:${result.error}`)
1683
2057
  continue
@@ -1753,7 +2127,7 @@ async function repl() {
1753
2127
  pendingFiles = []
1754
2128
  console.log(`resumed: ${pick.title} [${pick.conversationId}]`)
1755
2129
  } catch { console.log('history is not available') }
1756
- printOpening(conversationId)
2130
+ await printOpening(conversationId)
1757
2131
  continue
1758
2132
  }
1759
2133
  if (text.startsWith('/brief ')) {
@@ -1763,6 +2137,7 @@ async function repl() {
1763
2137
  continue
1764
2138
  }
1765
2139
  if (text.startsWith('/')) { console.log(`unknown command: ${text}; /help`); continue }
2140
+ const { correctionStatement } = await loadLearning()
1766
2141
  const feedback = correctionStatement(text)
1767
2142
  if (feedback) {
1768
2143
  const result = learnPreference(ledger, feedback, text, { explicit: /^(以后|记住|每次)/.test(text) })
@@ -1869,6 +2244,9 @@ async function importLedger(file, { replace = false } = {}) {
1869
2244
  if (!data || !Array.isArray(data.matters)) { console.error('import file does not contain an Advisers ledger'); process.exitCode = 1; return }
1870
2245
  await requireTosReaccept({ scope: 'import', subject: basename(file), action: 'import --replace' })
1871
2246
  ensureHome()
2247
+ // import replaces the ledger wholesale; serialize it with every other store
2248
+ // user (P0-1) before copying the pre-import backup and writing.
2249
+ ensureInstanceLock()
1872
2250
  try {
1873
2251
  const store = dbStore()
1874
2252
  if (store) copyFileSync(DB, join(HOME, `import-backup-${Date.now()}.db`))
@@ -1883,6 +2261,13 @@ async function importLedger(file, { replace = false } = {}) {
1883
2261
 
1884
2262
  function backup(file) {
1885
2263
  if (!file) { console.error('usage: advisers backup <path.db>'); process.exitCode = 1; return }
2264
+ const sealed = vaultSealedPath()
2265
+ if (sealed) {
2266
+ console.error(`advisers: E_VAULT_SEALED — cannot back up a sealed database (${sealed}).`)
2267
+ console.error('Run `advisers vault unseal` first; the sealed file itself is already an encrypted backup.')
2268
+ process.exitCode = 1
2269
+ return
2270
+ }
1886
2271
  const store = openStore()
1887
2272
  const checkpoint = store.checkpoint()
1888
2273
  if (checkpoint.busy) { console.error('backup failed: database is busy (another advisers process is writing); close it and retry'); process.exitCode = 1; return }
@@ -1907,6 +2292,7 @@ async function brief(text, deep = false) {
1907
2292
  const briefDenied = egressDeniedReason(briefLedger.getMatter(activeMatterId(briefLedger)), 'brief --deep')
1908
2293
  if (briefDenied) { console.error(briefDenied); process.exitCode = 1; return }
1909
2294
  try {
2295
+ const { chatCompletion } = await loadModel()
1910
2296
  const response = await chatCompletion({
1911
2297
  apiKey: process.env.ADVISERS_API_KEY,
1912
2298
  baseUrl: process.env.ADVISERS_BASE_URL,
@@ -1990,6 +2376,7 @@ async function routine(sub, arg, arg2) {
1990
2376
  if (!arg) { console.error('usage: advisers routine check <id>'); process.exitCode = 1; return }
1991
2377
  const routine = ledger.listRoutines().find((r) => r.id === arg)
1992
2378
  if (!routine) { console.error(`unknown routine: ${arg}`); process.exitCode = 1; return }
2379
+ const { checkRoutine } = await loadRoutine()
1993
2380
  const result = checkRoutine(routine)
1994
2381
  for (const item of result.results) console.log(`${item.ok ? 'ok' : 'FAIL'}\t${item.kind}\t${item.entry}`)
1995
2382
  if (!result.ok) process.exitCode = 1
@@ -2054,6 +2441,7 @@ async function routine(sub, arg, arg2) {
2054
2441
  const routine = ledger.listRoutines().find((r) => r.id === pending.routineId)
2055
2442
  if (!routine) { console.error(`unknown routine: ${pending.routineId}`); process.exitCode = 1; return }
2056
2443
  const candidate = { ...routine, ...pending.changes }
2444
+ const { checkRoutine } = await loadRoutine()
2057
2445
  const check = checkRoutine(candidate)
2058
2446
  if (!check.ok) {
2059
2447
  console.error('routine checks failed; patch not applied')
@@ -2152,6 +2540,7 @@ async function documentReview(args) {
2152
2540
  if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
2153
2541
  else { try { mod = await import('advisers-office') } catch { mod = await import('../../office/dist/index.js') } }
2154
2542
  const doc = await mod.readOffice(readFileSync(file))
2543
+ const { reviewDocument } = await loadDocReview()
2155
2544
  const result = await reviewDocument({ text: mod.officeToText(doc, 20_000), request: flags.request, apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
2156
2545
  dbStore()?.appendAudit({ actor: 'local', action: 'doc.review', allowed: !result.findings.some((f) => f.severity === 'blocker'), reason: file })
2157
2546
  console.log(result.summary || '(no summary)')
@@ -2172,7 +2561,20 @@ async function research(args) {
2172
2561
  const matterId = activeMatterId(ledger)
2173
2562
  const denied = egressDeniedReason(ledger.getMatter(matterId), 'research')
2174
2563
  if (denied) { console.error(denied); process.exitCode = 1; return }
2175
- const result = await runResearch({ query, urls, apiKey, baseUrl: process.env.ADVISERS_BASE_URL, deep: Boolean(flags.deep) })
2564
+ // Privacy audit P1-2: the library already redacts upstream bodies, but the CLI
2565
+ // must not print stacks/upstream text either. Print only stable status + code.
2566
+ let result
2567
+ try {
2568
+ const { research: runResearch } = await loadResearch()
2569
+ result = await runResearch({ query, urls, apiKey, baseUrl: process.env.ADVISERS_BASE_URL, deep: Boolean(flags.deep) })
2570
+ } catch (error) {
2571
+ const status = Number.isFinite(Number(error?.status)) ? `HTTP ${Number(error.status)} ` : ''
2572
+ const rawCode = String(error?.code ?? error?.name ?? 'RESEARCH_FAILED').toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 40)
2573
+ console.error(`research failed: ${status}(${rawCode || 'RESEARCH_FAILED'})`)
2574
+ console.error('Upstream response bodies and stack traces are not printed. Check ADVISERS_API_KEY, ADVISERS_BASE_URL and the network, then run `advisers doctor`.')
2575
+ process.exitCode = 1
2576
+ return
2577
+ }
2176
2578
  const store = dbStore()
2177
2579
  store?.addResearchRun({ matterId, query: query || urls[0], answer: result.answer, sources: result.sources, usage: result.usage, stopReason: result.stopReason })
2178
2580
  store?.appendAudit({ actor: 'local', action: 'egress.research', allowed: true, reason: `${urls.length ? 'url' : 'search'}:${result.sources.length}` })
@@ -2210,6 +2612,7 @@ async function buildCaptureSource({ meta, quote, ref, capturedAt }) {
2210
2612
  * @returns {Promise<{count: number, candidates: object[]}>}
2211
2613
  */
2212
2614
  async function proposeCaptureText({ text, source = 'wechat', date, matterId, meta = {}, store, json = false }) {
2615
+ const { captureCandidates } = await loadCapture()
2213
2616
  const result = await captureCandidates({ text, apiKey: process.env.ADVISERS_API_KEY, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL, date, source })
2214
2617
  if (!result.candidates.length) return { count: 0, candidates: [] }
2215
2618
  const conversationId = latestConversationId()
@@ -2373,6 +2776,7 @@ async function captureFromImap(flags) {
2373
2776
  const { parseEml, dedupeKey, toCaptureInput } = await loadImporters()
2374
2777
  let messages
2375
2778
  try {
2779
+ const { fetchImapMessages } = await loadImap()
2376
2780
  messages = await fetchImapMessages({
2377
2781
  host,
2378
2782
  port: Number(process.env.ADVISERS_IMAP_PORT) || (String(process.env.ADVISERS_IMAP_SECURE) === '0' ? 143 : 993),
@@ -2474,9 +2878,20 @@ async function printCalendarToday() {
2474
2878
  }
2475
2879
  }
2476
2880
 
2881
+ /** Host header allowlist for the local read-only UI (DNS-rebinding hardening, SEC2-07). */
2882
+ function isLoopbackHostHeader(host) {
2883
+ if (!host) return false
2884
+ const value = String(host).trim().toLowerCase()
2885
+ const bare = value.startsWith('[')
2886
+ ? value.replace(/^\[([^\]]+)\](?::\d+)?$/, '$1')
2887
+ : value.replace(/:\d+$/, '')
2888
+ return bare === '127.0.0.1' || bare === 'localhost' || bare === '::1'
2889
+ }
2890
+
2477
2891
  async function ui(args) {
2478
2892
  const flags = parseFlags(args).flags
2479
- const port = Number(flags.port) || 17860
2893
+ // --port 0 requests an ephemeral port (used by tests and scripts).
2894
+ const port = typeof flags.port === 'string' && flags.port.trim() !== '' ? Number(flags.port) : 17860
2480
2895
  const ledger = loadLedger()
2481
2896
  const store = dbStore()
2482
2897
  const { buildReminders } = await loadRemind()
@@ -2489,7 +2904,20 @@ async function ui(args) {
2489
2904
  who: () => ({ mine: ledger.openCommitments().filter((c) => c.debtor === 'user' || c.debtor === 'agent'), waiting: ledger.openCommitments().filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:')) }),
2490
2905
  reminders: () => buildReminders(ledger, { now: new Date() }),
2491
2906
  }
2907
+ const { createReadOnlyServer } = await loadUi()
2492
2908
  const app = createReadOnlyServer({ snapshot, port })
2909
+ // SEC2-07: DNS rebinding can point an attacker origin at 127.0.0.1; the
2910
+ // library only checks method=GET, so validate Host before its handler runs.
2911
+ const handlers = app.server.listeners('request').slice()
2912
+ app.server.removeAllListeners('request')
2913
+ app.server.on('request', (req, res) => {
2914
+ if (!isLoopbackHostHeader(req.headers.host)) {
2915
+ res.writeHead(403, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' })
2916
+ res.end(JSON.stringify({ error: 'forbidden host header' }))
2917
+ return
2918
+ }
2919
+ for (const handler of handlers) handler.call(app.server, req, res)
2920
+ })
2493
2921
  const url = await app.listen()
2494
2922
  console.log(`advisers ui (read-only): ${url}`)
2495
2923
  console.log('Ctrl-C to stop; no writes, no telemetry, 127.0.0.1 only.')
@@ -2717,7 +3145,6 @@ async function deliver(args) {
2717
3145
  }
2718
3146
  sections.push({ heading: '校验', paragraphs: [`内容哈希:${sha256Hex(JSON.stringify(commitments.map((c) => ({ id: c.id, action: c.action, dueAt: c.dueAt, evidence: c.evidence }))))}`, '本文件由本地账本生成;哈希用于事后比对,不是第三方存证。'] })
2719
3147
  try {
2720
- const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
2721
3148
  let buffer
2722
3149
  if (format === 'pdf') {
2723
3150
  const { buildSimplePdf } = await loadPdf()
@@ -2727,6 +3154,9 @@ async function deliver(args) {
2727
3154
  await backupCliFile(out)
2728
3155
  writeFileSync(out, buffer)
2729
3156
  } else if (format === 'xlsx') {
3157
+ // P2-3: the office barrel (exceljs + pptxgenjs + read/check) is only paid
3158
+ // on the formats that actually need it; PDF used to import it too.
3159
+ const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
2730
3160
  const rows = commitments.map((c) => ({
2731
3161
  id: c.id, creditor: c.creditor, action: c.action, due: c.dueAt ?? '',
2732
3162
  status: c.status, evidence: (c.evidence ?? []).length,
@@ -2742,6 +3172,7 @@ async function deliver(args) {
2742
3172
  await backupCliFile(out)
2743
3173
  writeFileSync(out, buffer)
2744
3174
  } else {
3175
+ const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
2745
3176
  buffer = await mod.buildDocx({ title: `${label} · Advisers`, sections })
2746
3177
  await mod.validateOffice(buffer, 'docx')
2747
3178
  await backupCliFile(out)
@@ -2784,7 +3215,23 @@ async function mcpServer() {
2784
3215
  version: VERSION,
2785
3216
  audit: (entry) => store?.appendAudit(entry),
2786
3217
  })
2787
- await server.serve(process.stdin, process.stdout)
3218
+ // Robustness audit P2-3: a closed client stdout surfaces as an asynchronous
3219
+ // 'error' event (EPIPE) and used to reach the global uncaughtException handler
3220
+ // as "write EPIPE"/exit 1. The MCP host went away, so exit cleanly (0).
3221
+ const onStdoutError = (error) => {
3222
+ if (error?.code === 'EPIPE') {
3223
+ try { process.stdin.pause() } catch {}
3224
+ process.exit(0)
3225
+ }
3226
+ console.error(`advisers: ${friendlyError(error)}`)
3227
+ process.exit(1)
3228
+ }
3229
+ process.stdout.on('error', onStdoutError)
3230
+ try {
3231
+ await server.serve(process.stdin, process.stdout)
3232
+ } finally {
3233
+ process.stdout.removeListener('error', onStdoutError)
3234
+ }
2788
3235
  }
2789
3236
 
2790
3237
  async function ocrCommand(args) {
@@ -2811,13 +3258,74 @@ function vaultPass() {
2811
3258
  return pass
2812
3259
  }
2813
3260
 
3261
+ /**
3262
+ * Plaintext database copies left behind by unseal/migrate/import/sync and by an
3263
+ * interrupted unseal (robustness audit P1-2). `vault seal --remove` must delete
3264
+ * these too, otherwise the CLI says "plaintext removed" while a readable SQLite
3265
+ * copy (including the before-unseal backup) is still in HOME.
3266
+ */
3267
+ const PLAINTEXT_DB_COPY_RE = /^(?:state\.db\.before-(?:unseal|migrate|sync)-|\.state\.db\.unseal-|import-backup-)/
3268
+ function plaintextDbCopies() {
3269
+ try {
3270
+ return readdirSync(HOME).filter((name) => PLAINTEXT_DB_COPY_RE.test(name)).map((name) => join(HOME, name))
3271
+ } catch {
3272
+ return []
3273
+ }
3274
+ }
3275
+
3276
+ /**
3277
+ * Remove the live plaintext database and every plaintext copy. Failures are
3278
+ * collected (never swallowed) so the caller can report them and exit non-zero.
3279
+ */
3280
+ function removePlaintextDatabase() {
3281
+ const removed = []
3282
+ const failures = []
3283
+ for (const file of [DB, `${DB}-wal`, `${DB}-shm`, ...plaintextDbCopies()]) {
3284
+ try {
3285
+ if (!existsSync(file)) continue
3286
+ rmSync(file)
3287
+ removed.push(file)
3288
+ } catch (error) {
3289
+ failures.push(`${file}: ${error.message}`)
3290
+ }
3291
+ }
3292
+ fsyncDir(HOME)
3293
+ return { removed, failures }
3294
+ }
3295
+
3296
+ /** Print the result of a --remove cleanup; returns true only when nothing failed. */
3297
+ function reportPlaintextCleanup(cleanup, out) {
3298
+ if (cleanup.failures.length) {
3299
+ console.error(`vault seal failed: the sealed file ${out} is in place, but ${cleanup.failures.length} plaintext file(s) could not be removed:`)
3300
+ for (const failure of cleanup.failures) console.error(` ${failure}`)
3301
+ console.error('Close other advisers processes / check file permissions, then rerun `advisers vault seal --remove`.')
3302
+ process.exitCode = 1
3303
+ return false
3304
+ }
3305
+ console.log(`sealed ${DB} -> ${out} (plaintext removed: ${cleanup.removed.length} file(s))`)
3306
+ return true
3307
+ }
3308
+
2814
3309
  async function vaultSeal(args) {
2815
3310
  const { flags } = parseFlags(args)
2816
3311
  ensureHome()
2817
- if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
3312
+ // P1-3: seal mutates/removes state.db, so it takes the same single-writer lock
3313
+ // as ordinary commands; a ui/mcp/bridge server holding the store now makes seal
3314
+ // fail with E_DB_LOCKED instead of silently discarding that process's writes.
3315
+ ensureInstanceLock()
3316
+ const removePlaintext = Boolean(flags.remove) || args.includes('--remove')
3317
+ if (!existsSync(DB)) {
3318
+ const sealed = vaultSealedPath()
3319
+ // Already sealed: --remove still means "purge the leftover plaintext copies".
3320
+ if (sealed && removePlaintext) return reportPlaintextCleanup(removePlaintextDatabase(), sealed)
3321
+ console.error(sealed
3322
+ ? `advisers: E_VAULT_SEALED — no plaintext database at ${DB}; the sealed file ${sealed} is intact.`
3323
+ : `no database at ${DB}`)
3324
+ process.exitCode = 1
3325
+ return
3326
+ }
2818
3327
  const pass = vaultPass(); if (!pass) return
2819
3328
  const { encryptJson, decryptJson } = await loadVault()
2820
- const removePlaintext = Boolean(flags.remove) || args.includes('--remove')
2821
3329
  try {
2822
3330
  const store = new SqliteStore(DB)
2823
3331
  try {
@@ -2841,10 +3349,10 @@ async function vaultSeal(args) {
2841
3349
  const check = decryptJson(JSON.parse(readFileSync(out, 'utf8')), pass)
2842
3350
  if (check.sha256 !== sha) throw new Error('sealed file verification failed')
2843
3351
  if (removePlaintext) {
2844
- for (const f of [DB, `${DB}-wal`, `${DB}-shm`]) { try { if (existsSync(f)) rmSync(f) } catch {} }
2845
- fsyncDir(HOME)
3352
+ if (!reportPlaintextCleanup(removePlaintextDatabase(), out)) return
3353
+ return
2846
3354
  }
2847
- console.log(`sealed ${DB} -> ${out}${removePlaintext ? ' (plaintext removed)' : ' (plaintext kept; pass --remove)'}`)
3355
+ console.log(`sealed ${DB} -> ${out} (plaintext kept; pass --remove)`)
2848
3356
  } catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1 }
2849
3357
  }
2850
3358
 
@@ -2867,6 +3375,9 @@ async function vaultUnseal(args) {
2867
3375
  return
2868
3376
  }
2869
3377
  ensureHome()
3378
+ // P1-3: unseal replaces state.db; hold the single-writer lock for the whole
3379
+ // verify + backup + rename sequence (E_DB_LOCKED while another process runs).
3380
+ ensureInstanceLock()
2870
3381
  // P1-3: never write the payload straight over the live database. Write a
2871
3382
  // same-directory temp file, fsync it, verify the SQLite image, keep the old
2872
3383
  // database (and its WAL) as a backup, then rename atomically.
@@ -2910,6 +3421,8 @@ function vaultStatus() {
2910
3421
  console.log(`database: ${existsSync(DB) ? DB : 'absent'}`)
2911
3422
  console.log(`sealed: ${existsSync(sealed) ? sealed : 'none'}`)
2912
3423
  console.log(`state: ${existsSync(DB) ? 'plaintext at rest' : existsSync(sealed) ? 'encrypted at rest (run vault unseal)' : 'empty'}`)
3424
+ const copies = plaintextDbCopies()
3425
+ if (copies.length) console.log(`plaintext copies: ${copies.length} (run \`advisers vault seal --remove\` to purge them)`)
2913
3426
  }
2914
3427
 
2915
3428
  async function timestampCommand(args) {
@@ -3033,6 +3546,10 @@ async function syncCommand(args) {
3033
3546
  }
3034
3547
  const pass = syncPass(); if (!pass) return
3035
3548
  ensureHome()
3549
+ // P1-3: push checkpoints/copies the live database and pull replaces it, so both
3550
+ // must not run while another process holds the store (or be run by two sync
3551
+ // commands at once). The lock is held for the whole operation.
3552
+ if (sub === 'push' || sub === 'pull') ensureInstanceLock()
3036
3553
  if (sub === 'push') {
3037
3554
  if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
3038
3555
  const device = typeof flags.device === 'string' ? flags.device : hostname()
@@ -3145,17 +3662,33 @@ async function evidencePack(args) {
3145
3662
  facts: ledger.listFacts().map((f) => f.id),
3146
3663
  preferences: ledger.listPreferences({ includeCandidates: false }).map((p) => p.id),
3147
3664
  }
3148
- const { buildEvidencePack, toDocxRows, verifyPack } = await loadEvidence()
3149
- const pack = buildEvidencePack({ store, ledger, ids: targetIds })
3665
+ const { buildEvidencePack, toDocxRows, verifyPack, EvidencePackLimitError } = await loadEvidence()
3666
+ let pack
3667
+ try {
3668
+ // Performance audit P1-1: --all was parsed but never forwarded, so the
3669
+ // documented escape hatch was a no-op and large ledgers always failed.
3670
+ pack = buildEvidencePack({ store, ledger, ids: targetIds, all: flags.all === true })
3671
+ } catch (error) {
3672
+ if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
3673
+ console.error('error: ' + error.message)
3674
+ if (error.hint) console.error('hint: ' + error.hint)
3675
+ process.exitCode = 1
3676
+ return
3677
+ }
3678
+ throw error
3679
+ }
3150
3680
  const out = flags.out ? String(flags.out) : join(HOME, 'evidence', `evidence-${new Date().toISOString().replace(/[:.]/g, '-')}`)
3151
3681
  mkdirSync(out, { recursive: true, mode: 0o700 })
3152
3682
  for (const [name, content] of Object.entries(pack.files)) writeFileSync(join(out, name), content, { mode: 0o600 })
3153
3683
  let receipt
3154
3684
  try {
3155
- const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
3685
+ // P2-3: import the docx/validate submodules, not the office barrel.
3686
+ const docxModule = await importOfficeSubmodule('docx')
3687
+ if (typeof docxModule?.buildDocx !== 'function') throw new Error('advisers-office docx builder is not available')
3688
+ const validateOffice = await loadOfficeOperation('validate', 'validateOffice')
3156
3689
  const rows = toDocxRows(pack, { maxRows: 80 })
3157
- const buffer = await mod.buildDocx({ title: '证据包回执', sections: [{ heading: '证据清单', paragraphs: rows.length ? rows : ['(没有可导出条目)'] }, { heading: '校验', paragraphs: [`manifest.json / README.txt 的 SHA256 见 SHA256SUMS`, `生成时间:${new Date().toISOString()}`, 'SHA256SUMS 只证明包生成后未被修改;不是签名或第三方存证。'] }] })
3158
- await mod.validateOffice(buffer, 'docx')
3690
+ const buffer = await docxModule.buildDocx({ title: '证据包回执', sections: [{ heading: '证据清单', paragraphs: rows.length ? rows : ['(没有可导出条目)'] }, { heading: '校验', paragraphs: [`manifest.json / README.txt 的 SHA256 见 SHA256SUMS`, `生成时间:${new Date().toISOString()}`, 'SHA256SUMS 只证明包生成后未被修改;不是签名或第三方存证。'] }] })
3691
+ await validateOffice(buffer, 'docx')
3159
3692
  writeFileSync(join(out, 'receipt.docx'), buffer)
3160
3693
  receipt = join(out, 'receipt.docx')
3161
3694
  } catch (error) { console.error(`docx receipt skipped: ${error.message}`) }
@@ -3551,6 +4084,76 @@ function link(sub, from, to, type) {
3551
4084
  process.exitCode = 1
3552
4085
  }
3553
4086
 
4087
+ /**
4088
+ * Bridge (Hermes file gateway) hardening — security audit P1-1 / SEC2-09.
4089
+ *
4090
+ * The bridge library owns the wire format; the CLI tightens what it can before
4091
+ * the library sees it: 0700 directories / 0600 files (the library used mkdir and
4092
+ * writeFile defaults), a 1 MiB inbox cap enforced before its unbounded readFile,
4093
+ * and no absolute local attachment paths in the outbox JSON. The library polls
4094
+ * through the instance method, so wrapping pollOnce() covers both the immediate
4095
+ * poll in start() and the interval.
4096
+ */
4097
+ const BRIDGE_INBOX_MAX_BYTES = 1024 * 1024
4098
+
4099
+ function bridgeDirs(bridgeDir, name) {
4100
+ return {
4101
+ inbox: join(bridgeDir, 'inbox', name),
4102
+ outbox: join(bridgeDir, 'outbox', name),
4103
+ status: join(bridgeDir, 'status', name),
4104
+ registry: join(bridgeDir, 'registry'),
4105
+ quarantine: join(bridgeDir, 'quarantine', name),
4106
+ }
4107
+ }
4108
+
4109
+ function secureBridgeTree(bridgeDir, name) {
4110
+ const dirs = bridgeDirs(bridgeDir, name)
4111
+ for (const dir of Object.values(dirs)) {
4112
+ try { mkdirSync(dir, { recursive: true, mode: 0o700 }); chmodSync(dir, 0o700) } catch {}
4113
+ }
4114
+ for (const dir of [dirs.outbox, dirs.registry, dirs.inbox]) {
4115
+ let files
4116
+ try { files = readdirSync(dir) } catch { continue }
4117
+ for (const file of files) {
4118
+ try { chmodSync(join(dir, file), 0o600) } catch {}
4119
+ }
4120
+ }
4121
+ }
4122
+
4123
+ /** Move oversized inbox files out of the library's readFile path (DoS guard). */
4124
+ function guardBridgeInbox(bridgeDir, name) {
4125
+ const dirs = bridgeDirs(bridgeDir, name)
4126
+ let files
4127
+ try { files = readdirSync(dirs.inbox) } catch { return }
4128
+ for (const file of files) {
4129
+ if (!file.endsWith('.json')) continue
4130
+ const source = join(dirs.inbox, file)
4131
+ let size
4132
+ try { size = statSync(source).size } catch { continue }
4133
+ try { chmodSync(source, 0o600) } catch {}
4134
+ if (size <= BRIDGE_INBOX_MAX_BYTES) continue
4135
+ try {
4136
+ mkdirSync(dirs.quarantine, { recursive: true, mode: 0o700 })
4137
+ chmodSync(dirs.quarantine, 0o700)
4138
+ renameSync(source, join(dirs.quarantine, file))
4139
+ dbStore()?.appendAudit({ actor: 'bridge', action: 'bridge.inbox_quarantine', allowed: false, reason: `${size} bytes > ${BRIDGE_INBOX_MAX_BYTES}` })
4140
+ console.log(`[bridge] quarantined oversized inbox file ${file} (${size} bytes)`)
4141
+ } catch {}
4142
+ }
4143
+ }
4144
+
4145
+ /** Never hand an absolute local attachment path to the third-party Hermes side. */
4146
+ function sanitizeBridgeOutbound(message) {
4147
+ if (!message || !Array.isArray(message.attachments) || !message.attachments.length) return message
4148
+ const attachments = message.attachments.map((attachment) => {
4149
+ const next = { ...(attachment ?? {}) }
4150
+ delete next.localPath
4151
+ if (typeof next.url === 'string' && isAbsolute(next.url)) delete next.url
4152
+ return next
4153
+ })
4154
+ return { ...message, attachments }
4155
+ }
4156
+
3554
4157
  async function bridge(args) {
3555
4158
  let dir
3556
4159
  let name = 'advisers'
@@ -3564,6 +4167,9 @@ async function bridge(args) {
3564
4167
  process.exitCode = 1
3565
4168
  return
3566
4169
  }
4170
+ // Files/directories below are private conversation data; tighten the umask for
4171
+ // every file this process creates in the bridge tree (SEC2-09: outbox 0644).
4172
+ process.umask(0o077)
3567
4173
  let mod
3568
4174
  if (process.env.ADVISERS_BRIDGE_LOCAL === '1') {
3569
4175
  mod = await import('../../bridge-hermes/dist/index.js')
@@ -3579,6 +4185,20 @@ async function bridge(args) {
3579
4185
  const ledger = loadLedger()
3580
4186
  const runtime = runtimeFor(ledger)
3581
4187
  const link = new mod.HermesBridgeLink({ bridgeDir: dir, name })
4188
+ const libraryPollOnce = link.pollOnce.bind(link)
4189
+ link.pollOnce = async () => {
4190
+ guardBridgeInbox(dir, name)
4191
+ const polled = await libraryPollOnce()
4192
+ secureBridgeTree(dir, name)
4193
+ return polled
4194
+ }
4195
+ const librarySend = link.send.bind(link)
4196
+ link.send = async (message) => {
4197
+ const sent = await librarySend(sanitizeBridgeOutbound(message))
4198
+ secureBridgeTree(dir, name)
4199
+ return sent
4200
+ }
4201
+ secureBridgeTree(dir, name)
3582
4202
  const permitSecret = process.env.ADVISERS_PERMIT_SECRET || randomUUID()
3583
4203
  const permitGate = new core.PermitGate(permitSecret, { replay: dbStore()?.permitReplayStore() })
3584
4204
  const host = {
@@ -3594,6 +4214,14 @@ async function bridge(args) {
3594
4214
  dbStore()?.appendAudit({ actor: 'bridge', action: 'policy.deny', allowed: false, reason: context.policy.code ?? 'DENY' })
3595
4215
  reply = context.policy.reason
3596
4216
  }
4217
+ // Security audit P1-1: bridge is a model egress path; apply the same
4218
+ // matter-secrecy gate as chat/review/research BEFORE any network call.
4219
+ const bridgeEgressDenied = reply ? null : egressDeniedReason(context.matter, 'bridge')
4220
+ if (bridgeEgressDenied) {
4221
+ dbStore()?.appendAudit({ actor: 'bridge', action: 'policy.egress_deny', allowed: false, reason: 'bridge' })
4222
+ console.log(`[bridge] blocked: ${bridgeEgressDenied}`)
4223
+ reply = '[advisers] received (protected matter: model call denied)'
4224
+ }
3597
4225
  const key = process.env.ADVISERS_API_KEY
3598
4226
  if (!reply && key && process.env.ADVISERS_NO_MODEL !== '1') {
3599
4227
  try {
@@ -3771,8 +4399,17 @@ async function soul(sub, file) {
3771
4399
  // names version/sha256/channel and NEVER the terms text.
3772
4400
  // ---------------------------------------------------------------------------
3773
4401
 
3774
- /** Commands usable without accepting the TOS (TOS §2.1: local functions stay usable). */
3775
- const TOS_EXEMPT_COMMANDS = new Set(['help', '--help', 'version', '--version', '-v', 'status', 'doctor', 'init', 'tos'])
4402
+ /**
4403
+ * Commands usable without accepting the TOS (TOS §2.1: local functions stay usable).
4404
+ * TOS §2.1 / §9.8: reviewing, exporting and deleting your own local data is not
4405
+ * a gated feature. After a revoke the data-rights commands (privacy/export/
4406
+ * audit/purge), tos itself, and the other local-only commands below must stay
4407
+ * usable, otherwise the user must re-consent before exporting or deleting data.
4408
+ */
4409
+ const TOS_EXEMPT_COMMANDS = new Set([
4410
+ 'help', '--help', '-h', 'version', '--version', '-v', 'status', 'doctor', 'init', 'tos',
4411
+ 'privacy', 'export', 'audit', 'purge',
4412
+ ])
3776
4413
  /** Known commands. Unknown commands keep the plain "unknown command" error, not the gate. */
3777
4414
  const KNOWN_COMMANDS = new Set([
3778
4415
  'version', '--version', '-v', 'help', '--help', 'chat', 'status', 'doctor', 'init', 'history', 'mcp',
@@ -4102,6 +4739,7 @@ if (!command) {
4102
4739
  if (!run || !apiKey) { console.error('usage: ADVISERS_API_KEY=... advisers learn review <run-id>'); process.exitCode = 1 }
4103
4740
  else {
4104
4741
  const ledger = loadLedger()
4742
+ const { reviewRun, lintReview, materializeReview } = await loadReview()
4105
4743
  const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
4106
4744
  const checked = lintReview(review, { run, routines: ledger.listRoutines() })
4107
4745
  if (!checked.ok) { console.error(`review rejected: ${checked.error}`); process.exitCode = 1 }
@@ -4198,10 +4836,12 @@ if (!command) {
4198
4836
  }
4199
4837
  } else { console.error('usage: advisers commit add|edit|ls|done|snooze'); process.exitCode = 1 }
4200
4838
  } else if (command === 'diff') {
4839
+ const { diffLatest } = await loadUndo()
4201
4840
  const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
4202
4841
  console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
4203
4842
  if (!result.ok) process.exitCode = 1
4204
4843
  } else if (command === 'undo') {
4844
+ const { listBackups, undoLatest } = await loadUndo()
4205
4845
  if (args.includes('--list')) {
4206
4846
  for (const row of await listBackups(join(HOME, 'undo'), { workspace: process.cwd() })) console.log(`${row.id}\t${row.path}\t${row.existed ? 'overwrite' : 'create'}`)
4207
4847
  } else {
@@ -4239,13 +4879,16 @@ if (!command) {
4239
4879
  else console.log(`${sub}: ${id}`)
4240
4880
  } else { console.error('usage: advisers nudge list|done|ignore'); process.exitCode = 1 }
4241
4881
  } else if (command === 'risks') {
4242
- risks(loadLedger())
4882
+ risks(loadLedger({ commitments: { status: 'open' } }))
4243
4883
  } else if (command === 'pet-brief') {
4244
4884
  await petBrief(args)
4245
4885
  } else if (command === 'today') {
4246
- await today(loadLedger(), { calendar: args.includes('--calendar'), sources: args.includes('--sources'), json: args.includes('--json') })
4886
+ // P1-2 (0.2.2): today only reads open commitments; --sources reports source
4887
+ // rows for every commitment, so that flag keeps the wider load.
4888
+ const sources = args.includes('--sources')
4889
+ await today(loadLedger({ commitments: sources ? {} : { status: 'open' } }), { calendar: args.includes('--calendar'), sources, json: args.includes('--json') })
4247
4890
  } else if (command === 'tick') {
4248
- tick(loadLedger(), args.includes('--json'))
4891
+ tick(loadLedger({ commitments: {} }), args.includes('--json'))
4249
4892
  } else if (command === 'ui') {
4250
4893
  await ui(args)
4251
4894
  } else if (command === 'remind') {
@@ -4253,7 +4896,7 @@ if (!command) {
4253
4896
  } else if (command === 'calendar') {
4254
4897
  await calendarImport(args.slice(1))
4255
4898
  } else if (command === 'who') {
4256
- const open = loadLedger().openCommitments()
4899
+ const open = loadLedger({ commitments: { status: 'open' } }).openCommitments()
4257
4900
  const mine = open.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
4258
4901
  const waiting = open.filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:'))
4259
4902
  if (args.includes('--json')) { console.log(JSON.stringify({ mine, waiting }, null, 2)); }
@@ -4315,6 +4958,7 @@ if (!command) {
4315
4958
  } else if (command === 'digest') {
4316
4959
  const period = args[0] === 'week' ? 'week' : 'day'
4317
4960
  const store = dbStore()
4961
+ const { buildDigest } = await loadDigest()
4318
4962
  console.log(buildDigest({
4319
4963
  period,
4320
4964
  turns: store?.listTurns(latestConversationId(), 200) ?? [],
@@ -4322,7 +4966,7 @@ if (!command) {
4322
4966
  deliveries: store?.listDeliveries(100) ?? [],
4323
4967
  }))
4324
4968
  } else if (command === 'week') {
4325
- printWeek(loadLedger())
4969
+ printWeek(loadLedger({ commitments: {} }))
4326
4970
  } else if (command === 'prefs') {
4327
4971
  printPreferences()
4328
4972
  } else if (command === 'privacy') {
@@ -4333,6 +4977,7 @@ if (!command) {
4333
4977
  purgeMatter(args[0], args.includes('--yes'))
4334
4978
  } else if (command === 'decay') {
4335
4979
  const ledger = loadLedger()
4980
+ const { applyPreferenceDecay } = await loadLearning()
4336
4981
  const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
4337
4982
  saveLedger(ledger)
4338
4983
  console.log(`[decay] ${changed.length} preference(s) updated`)