advisers 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,11 +237,46 @@ 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
  }
@@ -189,6 +286,8 @@ function openStore({ checkIntegrity = false } = {}) {
189
286
  function loadLedger() {
190
287
  ensureHome()
191
288
  if (mode === 'json') return loadJson()
289
+ const sealed = vaultSealedPath()
290
+ if (sealed) throw vaultSealedError(sealed)
192
291
  try {
193
292
  if (!existsSync(DB) && existsSync(STATE)) {
194
293
  const ledger = loadJson()
@@ -197,6 +296,11 @@ function loadLedger() {
197
296
  }
198
297
  return Ledger.fromJSON(openStore().load(), LOCAL_PORTS)
199
298
  } catch (error) {
299
+ const hint = storeFailureHint(error)
300
+ if (hint) {
301
+ console.error(hint)
302
+ process.exit(1)
303
+ }
200
304
  console.error(`sqlite unavailable: ${error.message}`)
201
305
  console.error('Run `advisers doctor`; refusing to silently switch to JSON (would split the ledger).')
202
306
  process.exit(1)
@@ -207,6 +311,11 @@ function exitStoreWriteFailure(error) {
207
311
  // P0-2: never fall back to state.json. The SQLite database is the only ledger
208
312
  // once it exists, so a JSON fallback would silently split the book (and the
209
313
  // command would still exit 0). Fail loudly instead.
314
+ const hint = storeFailureHint(error)
315
+ if (hint) {
316
+ console.error(hint)
317
+ process.exit(1)
318
+ }
210
319
  console.error(`advisers: could not write the ledger to ${DB}: ${error.message}`)
211
320
  console.error('Nothing was written to state.json; the SQLite database is the only ledger, so this command did not apply.')
212
321
  console.error('Retry the command; if it keeps failing run `advisers doctor` (or `advisers audit --check-db`).')
@@ -325,7 +434,7 @@ function runtimeFor(ledger) {
325
434
  }
326
435
 
327
436
  async function backupCliFile(path) {
328
- try { await backupBeforeWrite(path, { cwd: process.cwd(), backupDir: join(HOME, 'undo') }) } catch {}
437
+ try { const { backupBeforeWrite } = await loadUndo(); await backupBeforeWrite(path, { cwd: process.cwd(), backupDir: join(HOME, 'undo') }) } catch {}
329
438
  }
330
439
 
331
440
  function now() {
@@ -436,8 +545,15 @@ function friendlyError(error) {
436
545
  if (/database is locked/.test(message)) return 'database is busy; close other advisers processes and retry'
437
546
  return message
438
547
  }
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) })
548
+ function reportFatalError(error) {
549
+ // E_DB_LOCKED / E_DB_CORRUPT get backup/doctor/concurrency guidance instead of
550
+ // the generic one-line message (commands that touch the store without going
551
+ // through loadLedger() end up here).
552
+ console.error(storeFailureHint(error) ?? `advisers: ${friendlyError(error)}`)
553
+ process.exit(1)
554
+ }
555
+ process.on('uncaughtException', reportFatalError)
556
+ process.on('unhandledRejection', reportFatalError)
441
557
  /**
442
558
  * TOS gate: `--accept-tos[=<version>]` is a global pre-dispatch flag, so it is
443
559
  * stripped from argv before the command is parsed (it may appear before or after
@@ -521,7 +637,7 @@ Usage:
521
637
  advisers mcp --stdio MCP server(7 工具 + 4 resources;写入口仅 pending 候选/回执校验)
522
638
  advisers evidence show <id> [--json] 承诺/事实/偏好→原文来源
523
639
  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 回执)
640
+ advisers deliveries --pack [--out dir] [--ids ...] [--all] 证据包(manifest/README/SHA256SUMS + DOCX 回执;默认上限 2000)
525
641
  advisers deliveries --receipt [--out dir] [--ids ...] [--all] [--recipient "Name <mail>"]
526
642
  交付回执包 v1.1(交付文件副本 + 全文件 SHA-256 + 证据;默认上限 2000)
527
643
  advisers evidence verify <dir> 离线校验回执包(JSON,exit 0/1;不读账本、不联网)
@@ -579,13 +695,32 @@ Environment:
579
695
  ADVISERS_PROGRESS=0 hide [tool] progress lines
580
696
  ADVISERS_ACCEPT_TOS=1 record TOS consent without a TTY (same as --accept-tos)
581
697
  ADVISERS_NOTIFY_WEBHOOK optional outbound webhook for remind --deliver --notify
698
+ ADVISERS_LOCK_TIMEOUT_MS wait for another advisers process to release the
699
+ instance lock (milliseconds; default 10000, 0 = fail immediately)
700
+
701
+ Concurrency:
702
+ One advisers process per ADVISERS_HOME uses the SQLite ledger at a time. The
703
+ CLI takes ~/.advisers/instance.lock before opening state.db; a second process
704
+ waits up to ADVISERS_LOCK_TIMEOUT_MS and then exits with E_DB_LOCKED instead
705
+ of writing from a stale ledger snapshot. ui / mcp / bridge keep the lock while
706
+ they run, so stop them before running other commands (or raise the timeout).
707
+ A stale lock (dead pid, or not refreshed for 1h) is reclaimed; SIGINT/SIGTERM
708
+ and normal exit release the lock. Concurrent commands therefore either run one
709
+ after another or fail explicitly — they never silently overwrite each other.
582
710
 
583
711
  Exit codes:
584
712
  0 success
585
- 1 user/config/runtime error (bad args, missing key, unknown id, failed verification)
713
+ 1 user/config/runtime error (bad args, missing key, unknown id, failed
714
+ verification, E_DB_LOCKED when another process holds the instance lock,
715
+ E_DB_CORRUPT when state.db is 0 bytes/corrupt: back it up and run
716
+ \`advisers doctor\`; damaged databases are never silently rebuilt)
586
717
  3 TOS consent required: non-interactive command blocked by the consent gate.
587
718
  Run \`advisers tos accept\` in a TTY, or pass --accept-tos / ADVISERS_ACCEPT_TOS=1.
588
719
  \`advisers evidence verify <dir>\` is offline/read-only and exempt from the gate.
720
+ Data-rights commands (audit/export/privacy/purge) and \`tos\` are exempt too.
721
+
722
+ Requirements:
723
+ Node >= 22.16 (node:sqlite). Node 22 prints an ExperimentalWarning for SQLite; Node 24 does not.
589
724
  `)
590
725
  }
591
726
 
@@ -861,10 +996,24 @@ function tick(ledger, asJson = false) {
861
996
  if (!c.dueAt || Date.parse(c.dueAt) > weekAhead) continue
862
997
  candidates.push(c)
863
998
  }
999
+ // P2-2 (0.2.1): the recent-outcome read is bounded by the candidate set.
1000
+ // Only candidates whose pre-outcome level is L2/L3 can be downgraded by an
1001
+ // ignored run (the `level !== 'L1'` guard below), so those are the only ids
1002
+ // the query needs; the history table is never scanned as a whole.
1003
+ const baseLevelById = new Map()
1004
+ const outcomeIds = []
1005
+ for (const c of candidates) {
1006
+ const dueDay = localDayOf(c.dueAt)
1007
+ const msLeft = Date.parse(c.dueAt) - now
1008
+ let baseLevel = (msLeft < 0 || dueDay === localDay) ? 'L2' : 'L1'
1009
+ if (baseLevel === 'L2' && Date.parse(c.dueAt) < now - 86400_000 && process.env.ADVISERS_ALLOW_L3 === '1') baseLevel = 'L3'
1010
+ baseLevelById.set(c.id, baseLevel)
1011
+ if (baseLevel !== 'L1') outcomeIds.push(c.id)
1012
+ }
864
1013
  // P0-2: replace the per-commitment N+1 queries (listCommitmentNudges +
865
1014
  // countNudges) with three batch reads: recent outcomes per commitment,
866
1015
  // today's level counts and today's existing (commitment, level) keys.
867
- const recentByCommitment = store && candidates.length ? store.recentNudgeOutcomes(3) : new Map()
1016
+ const recentByCommitment = store && outcomeIds.length ? store.recentNudgeOutcomes(3, outcomeIds) : new Map()
868
1017
  const levelCounts = store && candidates.length ? store.countNudgesByDay(localDay) : new Map()
869
1018
  const existingKeys = store && candidates.length ? store.listNudgeLevelKeysByDay(localDay) : new Set()
870
1019
  const pendingKeys = new Set()
@@ -872,10 +1021,7 @@ function tick(ledger, asJson = false) {
872
1021
  let l2Today = levelCounts.get('L2') ?? 0
873
1022
  const nudgeRows = []
874
1023
  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'
1024
+ let level = baseLevelById.get(c.id)
879
1025
  const recent = recentByCommitment.get(c.id) ?? []
880
1026
  if (recent.length === 3 && recent.every((outcome) => outcome === 'ignored') && level !== 'L1') level = level === 'L3' ? 'L2' : 'L1'
881
1027
  // Budgets keep the historical in-run semantics: a nudge already written by
@@ -938,25 +1084,39 @@ function printPrivacy(args = []) {
938
1084
  const store = dbStore()
939
1085
  let audit = null
940
1086
  try { const v = store?.verifyAudit(); if (v) audit = { ok: v.ok, count: v.count ?? 0 } } catch {}
1087
+ // Privacy audit P2-2: list every actual egress surface from the code base
1088
+ // instead of two hardcoded names, and never expose internal numbering.
1089
+ const egressSurfaces = [
1090
+ 'model provider — chat / brief --deep / review / learn review (only when ADVISERS_API_KEY is set; ADVISERS_BASE_URL)',
1091
+ 'research --web|--url — provider web search/read tool (explicit opt-in; no silent research egress)',
1092
+ 'capture --from-imap — read-only IMAP fetch from the server you configure (TLS by default)',
1093
+ 'remind --deliver --notify — optional outbound webhook or local notifier you configure',
1094
+ 'sync push|pull — the directory you provide; snapshots are AES-256-GCM encrypted before writing',
1095
+ 'bridge — Hermes file gateway: inbox/outbox JSON files are handed to the Hermes process',
1096
+ 'MCP --stdio / DSH host tools / pet-brief — local consumers; the host or reader may forward the data',
1097
+ 'ocr / timestamp — local adapter subprocess you configure (this CLI does not call a cloud OCR/TSA)',
1098
+ ]
941
1099
  const facts = {
942
1100
  home: HOME,
943
1101
  database: DB,
944
1102
  telemetry: 'none',
945
1103
  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',
1104
+ explicit_egress: egressSurfaces,
1105
+ provider: { baseUrl: process.env.ADVISERS_BASE_URL ?? 'https://api.deepseek.com', model: process.env.ADVISERS_MODEL ?? 'deepseek-flash' },
1106
+ secret_matter: 'egress fail-closed for secrecy > 0 on the wired model paths (local rule layer)',
1107
+ at_rest_encryption: 'opt-in database vault (advisers vault seal); general data is not encrypted at rest',
950
1108
  audit,
951
1109
  export: 'advisers export --all',
952
1110
  delete: 'advisers purge <matter> --yes',
953
1111
  }
954
1112
  if (asJson) { console.log(JSON.stringify(facts, null, 2)); return }
955
1113
  console.log('privacy · local data facts')
1114
+ console.log('self-attestation(本地自检口径:只读本机文件/环境与纯函数,不是第三方审计;本命令不联网)')
956
1115
  console.log(`home: ${facts.home}`)
957
1116
  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(', ')}`)
1117
+ console.log(`telemetry: ${facts.telemetry} (build-time statement; this package contains no telemetry code)`)
1118
+ console.log(`egress: ${facts.default_egress} by default — nothing leaves the machine until you configure/opt in to:`)
1119
+ for (const surface of egressSurfaces) console.log(` - ${surface}`)
960
1120
  console.log(`provider: ${facts.provider.model} @ ${facts.provider.baseUrl}`)
961
1121
  console.log(`secret: ${facts.secret_matter}`)
962
1122
  console.log(`encryption: ${facts.at_rest_encryption}`)
@@ -965,15 +1125,18 @@ function printPrivacy(args = []) {
965
1125
  console.log(`delete: ${facts.delete}`)
966
1126
  if (prove) {
967
1127
  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 } })()],
1128
+ ['home exists', existsSync(HOME), 'local self-check'],
1129
+ ['database exists', existsSync(DB), 'local self-check'],
1130
+ ['audit verified', Boolean(audit?.ok), 'local self-check: keyed hash chain'],
1131
+ ['telemetry disabled', facts.telemetry === 'none', 'local self-check: build-time statement, not network-verified'],
1132
+ ['no default network egress', facts.default_egress === 'none', 'local self-check: build-time statement, not network-verified'],
1133
+ ['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
1134
  ]
1135
+ console.log('')
1136
+ console.log('self-checks(本地自检:结果只说明本机文件/配置与纯函数检查;不是第三方审计,也不证明运行时无出网)')
975
1137
  let failed = 0
976
- for (const [name, ok] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name}`) }
1138
+ for (const [name, ok, detail] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name} (${detail})`) }
1139
+ 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
1140
  if (failed) process.exitCode = 1
978
1141
  }
979
1142
  }
@@ -995,7 +1158,12 @@ function printLinks() {
995
1158
  * allowlist). The test suite asserts the generated document is deep-equal to
996
1159
  * the canonical snapshot in docs/pet-brief/schema-v0.2.json.
997
1160
  */
998
- function petBriefJsonSchema() {
1161
+ async function petBriefJsonSchema() {
1162
+ const {
1163
+ PET_BRIEF_DEFAULT_DISPLAY_POLICY, PET_BRIEF_DISPLAY_POLICIES, PET_BRIEF_MAX_ITEMS,
1164
+ PET_BRIEF_MAX_LINE_LENGTH, PET_BRIEF_MAX_SUGGESTED_LINES, PET_BRIEF_MOODS,
1165
+ PET_BRIEF_SCHEMA_VERSION, PET_BRIEF_SOURCE,
1166
+ } = await loadPetBrief()
999
1167
  const maxItems = PET_BRIEF_MAX_ITEMS
1000
1168
  const id = { type: 'string', minLength: 1, maxLength: 64 }
1001
1169
  const confidence = { type: 'number', minimum: 0, maximum: 1 }
@@ -1088,6 +1256,11 @@ function petBriefJsonSchema() {
1088
1256
  * legacy/missing-displayPolicy into errors instead).
1089
1257
  */
1090
1258
  async function petBrief(args) {
1259
+ const {
1260
+ PET_BRIEF_DEFAULT_DISPLAY_POLICY, PET_BRIEF_DISPLAY_POLICIES, PET_BRIEF_MAX_ITEMS,
1261
+ PET_BRIEF_MAX_LINE_LENGTH, PET_BRIEF_MAX_SUGGESTED_LINES, PET_BRIEF_MOODS,
1262
+ PET_BRIEF_SCHEMA_VERSION, PET_BRIEF_SOURCE, buildPetBrief, validatePetBrief, writePetBriefAtomic,
1263
+ } = await loadPetBrief()
1091
1264
  const { flags } = parseFlags(args)
1092
1265
  const asJson = args.includes('--json')
1093
1266
  const check = args.includes('--check')
@@ -1104,7 +1277,7 @@ async function petBrief(args) {
1104
1277
  if (inFile !== undefined || outFlag !== undefined || displayPolicyFlag !== undefined || asJson || check) {
1105
1278
  return fail('E_USAGE', '--print-schema cannot be combined with other pet-brief options')
1106
1279
  }
1107
- console.log(JSON.stringify(petBriefJsonSchema(), null, 2))
1280
+ console.log(JSON.stringify(await petBriefJsonSchema(), null, 2))
1108
1281
  return
1109
1282
  }
1110
1283
  if (inFile !== undefined && !check) return fail('E_USAGE', '--in can only be used with --check')
@@ -1129,6 +1302,15 @@ async function petBrief(args) {
1129
1302
  if (!result.ok) process.exitCode = 1
1130
1303
  return
1131
1304
  }
1305
+ // P1-1/P0-1: pet-brief reads state.db read-only, but it still shares the
1306
+ // single-writer HOME. Report a sealed vault with the stable code instead of
1307
+ // "store not found", and take the instance lock so the read cannot race a
1308
+ // seal/unseal/sync-pull replacing the database.
1309
+ if (mode === 'sqlite') {
1310
+ const sealed = vaultSealedPath()
1311
+ 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)')
1312
+ ensureInstanceLock()
1313
+ }
1132
1314
  const { readLedgerSnapshotReadOnly } = await import('../lib/pet-brief-store.js')
1133
1315
  let snapshot
1134
1316
  try {
@@ -1181,18 +1363,56 @@ function printPreferences() {
1181
1363
  async function doctor() {
1182
1364
  const rows = []
1183
1365
  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)
1366
+ const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(Number)
1367
+ check('node', nodeMajor > 22 || (nodeMajor === 22 && nodeMinor >= 16), process.version)
1185
1368
  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) }
1369
+ // Sealed vault (robustness audit P1-1): report the real state instead of
1370
+ // silently creating an empty database and printing all-PASS diagnostics.
1371
+ const sealed = vaultSealedPath()
1372
+ if (sealed) {
1373
+ check('vault', true, `sealed (${sealed}); run ` + '`advisers vault unseal`')
1374
+ check('lock', true, 'not taken (vault sealed)')
1375
+ check('database', true, 'skipped (vault sealed)')
1376
+ check('sqlite', true, 'skipped (vault sealed)')
1377
+ check('audit', true, 'skipped (vault sealed)')
1378
+ check('schema', true, 'skipped (vault sealed)')
1379
+ } else {
1380
+ try {
1381
+ const store = openStore()
1382
+ // P0-1: doctor holds the instance lock while it inspects the store; the
1383
+ // row also exposes the lock path so a stuck holder can be diagnosed.
1384
+ check('lock', true, `${instanceLock?.path ?? LOCK_PATH} (held by pid ${process.pid})`)
1385
+ let dbBytes = 0
1386
+ try { dbBytes = statSync(DB).size } catch {}
1387
+ check('database', dbBytes > 0, dbBytes > 0 ? `${DB} (${dbBytes} bytes)` : `E_DB_CORRUPT: ${DB} is 0 bytes; back it up and restore`)
1388
+ const integrity = store.assertIntegrity()
1389
+ check('sqlite', integrity === 'ok', `${DB} (${integrity})`)
1390
+ const audit = store.verifyAudit()
1391
+ check('audit', audit.ok, audit.ok ? `${audit.count} entries` : `BROKEN at seq ${audit.seq}`)
1392
+ check('schema', true, String(store.db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value ?? '?'))
1393
+ } catch (error) {
1394
+ if (error?.code === 'E_DB_LOCKED') {
1395
+ // Another live process holds the store; this is a real FAIL, not a
1396
+ // reason to silently inspect a stale snapshot.
1397
+ check('lock', false, error.message)
1398
+ check('sqlite', false, 'skipped (another instance holds the instance lock)')
1399
+ } else if (error?.code === 'E_DB_CORRUPT') {
1400
+ check('lock', true, `${instanceLock?.path ?? LOCK_PATH} (held by pid ${process.pid})`)
1401
+ check('database', false, error.message)
1402
+ check('sqlite', false, 'refusing to open a 0-byte/corrupt database (no silent rebuild)')
1403
+ check('audit', false, 'skipped (database damaged)')
1404
+ check('schema', false, 'skipped (database damaged)')
1405
+ } else {
1406
+ check('lock', Boolean(instanceLock?.held), instanceLock?.held ? `${LOCK_PATH} (held by pid ${process.pid})` : 'not taken')
1407
+ check('sqlite', false, error.message)
1408
+ }
1409
+ }
1410
+ }
1411
+ // P2-3 (0.2.1): probe resolvability instead of importing the office barrel
1412
+ // (222-573ms, and only needed to answer "is the peer installed?").
1194
1413
  let officeOk = false
1195
- try { await import('advisers-office'); officeOk = true } catch { try { await import('../../office/dist/index.js'); officeOk = true } catch {} }
1414
+ try { officeOk = Boolean(import.meta.resolve('advisers-office')) } catch {}
1415
+ if (!officeOk) officeOk = existsSync(new URL('../../office/dist/index.js', import.meta.url))
1196
1416
  check('office', officeOk, officeOk ? 'advisers-office resolvable' : 'npm i -g advisers-office@next, or ADVISERS_OFFICE_LOCAL=1 in checkout')
1197
1417
  check('policy', Boolean(StrictPolicyPack), StrictPolicyPack ? 'strict pack loaded' : 'policy pack missing')
1198
1418
  check('model', true, process.env.ADVISERS_API_KEY ? 'API key present (not tested)' : 'optional; ADVISERS_API_KEY not set')
@@ -1252,10 +1472,11 @@ function printStatus(asJson = false) {
1252
1472
  console.log(`soul ${data.soul}`)
1253
1473
  }
1254
1474
 
1255
- function loadHistory(conversationId) {
1475
+ async function loadHistory(conversationId) {
1256
1476
  try {
1257
1477
  const store = dbStore()
1258
1478
  if (!store) return { turns: [], summary: '' }
1479
+ const { buildHistory } = await loadContextWindow()
1259
1480
  const turns = store.listTurns(conversationId, 100)
1260
1481
  const summary = store.getSessionSummary(conversationId)
1261
1482
  return buildHistory({ turns, summary: summary?.summary, throughSeq: summary?.throughSeq ?? 0 })
@@ -1273,6 +1494,7 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
1273
1494
  try {
1274
1495
  const store = dbStore()
1275
1496
  if (!store) return
1497
+ const { shouldSummarize, buildPins, summarizeTurns, ensurePins, continuityProbes } = await loadContextWindow()
1276
1498
  const turns = store.listTurns(conversationId, 500)
1277
1499
  const old = store.getSessionSummary(conversationId)
1278
1500
  if (!shouldSummarize(turns, old?.throughSeq ?? 0, 10, 20)) return
@@ -1285,6 +1507,7 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
1285
1507
  if (apiKey && process.env.ADVISERS_LLM_SUMMARY !== '0') {
1286
1508
  try {
1287
1509
  const transcript = fresh.map((t) => `${t.role === 'user' ? '用户' : '助手'}:${t.content}`).join('\n')
1510
+ const { chatCompletion } = await loadModel()
1288
1511
  const response = await chatCompletion({
1289
1512
  apiKey,
1290
1513
  baseUrl: baseUrl || 'https://api.deepseek.com',
@@ -1305,10 +1528,11 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
1305
1528
  } catch {}
1306
1529
  }
1307
1530
 
1308
- function printOpening(conversationId) {
1531
+ async function printOpening(conversationId) {
1309
1532
  try {
1310
1533
  const store = dbStore()
1311
1534
  if (!store) return
1535
+ const { buildOpening } = await loadContextWindow()
1312
1536
  const turns = store.listTurns(conversationId, 20)
1313
1537
  const summary = store.getSessionSummary(conversationId)
1314
1538
  const commitments = loadLedger().openCommitments()
@@ -1316,7 +1540,8 @@ function printOpening(conversationId) {
1316
1540
  } catch {}
1317
1541
  }
1318
1542
 
1319
- function applyNudgeFeedback(text) {
1543
+ async function applyNudgeFeedback(text) {
1544
+ const { classifyNudgeOutcome } = await loadNudge()
1320
1545
  const outcome = classifyNudgeOutcome(text)
1321
1546
  if (!outcome) return
1322
1547
  try {
@@ -1328,7 +1553,75 @@ function applyNudgeFeedback(text) {
1328
1553
  } catch {}
1329
1554
  }
1330
1555
 
1331
- async function runTurn({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [] }) {
1556
+ let safetyModule
1557
+ let lastTurnSafetyBlock = null
1558
+
1559
+ /** Build the structured audit reason for a safety decision (never the original text). */
1560
+ function safetyReasonFor(result, fallbackSurface = 'model.output') {
1561
+ try {
1562
+ return safetyModule.buildAuditReason({
1563
+ rulesetVersion: result?.rulesetVersion,
1564
+ surface: result?.surface ?? fallbackSurface,
1565
+ action: result?.action ?? 'block',
1566
+ code: result?.code ?? 'CONTENT_SAFETY_BLOCKED',
1567
+ ruleIds: result?.ruleIds,
1568
+ evidenceHash: result?.evidenceHash,
1569
+ })
1570
+ } catch {
1571
+ return `code=${result?.code ?? 'CONTENT_SAFETY_BLOCKED'}`
1572
+ }
1573
+ }
1574
+
1575
+ /**
1576
+ * Report a local content-safety block without echoing or persisting the original
1577
+ * text (privacy audit P2 / security audit SEC2-04): user-facing rejection plus a
1578
+ * keyed `actor: 'safety'` audit row so the block is explainable later.
1579
+ */
1580
+ function recordSafetyBlock(result, { action = 'safety.chat', surface = 'model.output' } = {}) {
1581
+ const code = result?.code || 'CONTENT_SAFETY_BLOCKED'
1582
+ const ruleIds = Array.isArray(result?.ruleIds) ? result.ruleIds : []
1583
+ console.error('advisers: 内容安全审核未通过(CONTENT_SAFETY_BLOCKED)')
1584
+ console.error('本次输入未发送到模型,也未写入账本或会话;被拒内容不会保存为标题或会话。')
1585
+ console.error(`本地自检(${surface}):code=${code} rules=${ruleIds.join(',') || '-'};这是本地规则层判定,不是人工审核。`)
1586
+ if (result?.crisis) console.error('如果你或他人正处于危险中,请立即联系当地紧急服务或可信任的人。')
1587
+ try {
1588
+ ensureHome()
1589
+ dbStore()?.appendAudit({ actor: 'safety', action, allowed: false, reason: safetyReasonFor(result, surface) })
1590
+ } catch {}
1591
+ }
1592
+
1593
+ /**
1594
+ * Wrapper around runTurnInner: local content-safety pre-flight BEFORE
1595
+ * runtime.ingest()/upsertSession() (SEC2-04). A blocked input must not create a
1596
+ * matter, a session title or a ledger fact, and must not purge the active matter
1597
+ * pointer later (the old order persisted the raw text as sessions.title).
1598
+ */
1599
+ async function runTurn(options) {
1600
+ lastTurnSafetyBlock = null
1601
+ ensureHome()
1602
+ safetyModule ??= await loadSafety()
1603
+ const text = String(options?.text ?? '')
1604
+ const decision = safetyModule.classify(text, { surface: 'model.output', hmacKey: process.env.ADVISERS_AUDIT_KEY })
1605
+ if (decision.action === 'block') {
1606
+ lastTurnSafetyBlock = decision
1607
+ recordSafetyBlock(decision, { surface: 'chat.input' })
1608
+ return undefined
1609
+ }
1610
+ try {
1611
+ return await runTurnInner(options)
1612
+ } catch (error) {
1613
+ // Context/history/attachments can still trip the model choke point; audit
1614
+ // it as safety rather than letting it look like an unexplained crash.
1615
+ if (error?.name === 'ContentSafetyError') {
1616
+ lastTurnSafetyBlock = error
1617
+ recordSafetyBlock(error, { surface: error.surface || 'model.output' })
1618
+ return undefined
1619
+ }
1620
+ throw error
1621
+ }
1622
+ }
1623
+
1624
+ async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [] }) {
1332
1625
  const result = await runtime.ingest({
1333
1626
  linkId: 'cli',
1334
1627
  accountId: 'local',
@@ -1343,7 +1636,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1343
1636
  console.log(`[ignored: ${result.reason}]`)
1344
1637
  return
1345
1638
  }
1346
- applyNudgeFeedback(text)
1639
+ await applyNudgeFeedback(text)
1347
1640
  const context = runtime.lastContext
1348
1641
  if (!context) throw new Error('runtime did not produce a context')
1349
1642
  const egressDenied = egressDeniedReason(context.matter, 'chat')
@@ -1401,7 +1694,8 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1401
1694
  if (!intent?.questions?.length) console.log('[local] 未配置模型;已记录到当前会话,但没有创建承诺或文件。设置 ADVISERS_API_KEY 后可用自然语言执行;也可用 `advisers office` / `advisers template` 直接生成文件。')
1402
1695
  return intent?.questions?.[0]
1403
1696
  }
1404
- const history = loadHistory(conversationId)
1697
+ const { buildPins, fitHistory } = await loadContextWindow()
1698
+ const history = await loadHistory(conversationId)
1405
1699
  const pins = buildPins({
1406
1700
  preferences: ledger.listPreferences({ matterId: context.matter.id }),
1407
1701
  commitments: ledger.openCommitments(context.matter.id),
@@ -1409,6 +1703,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1409
1703
  const prompt = pins ? `${context.prompt}\n<session-pins>\n${pins}\n</session-pins>` : context.prompt
1410
1704
  const fitted = fitHistory({ system: prompt, summary: history.summary, history: history.turns, current: agentText, maxTokens: Number(process.env.ADVISERS_CONTEXT_TOKENS || 12000) })
1411
1705
  if (fitted.trimmed) console.log(`[compact] 裁剪 ${fitted.trimmed} 轮旧历史`)
1706
+ const { runAgent } = await loadAgent()
1412
1707
  const { reply, artifacts, toolLog } = await runAgent({
1413
1708
  runtime,
1414
1709
  text: agentText,
@@ -1475,6 +1770,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1475
1770
  if (runId && process.env.ADVISERS_LEARNING === 'auto' && apiKey) {
1476
1771
  try {
1477
1772
  const run = dbStore()?.listTaskRuns(50).find((r) => r.id === runId)
1773
+ const { reviewRun, lintReview, materializeReview } = await loadReview()
1478
1774
  const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
1479
1775
  const checked = lintReview(review, { run, routines: ledger.listRoutines() })
1480
1776
  if (checked.ok && checked.review.verdict !== 'NONE') {
@@ -1484,6 +1780,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
1484
1780
  }
1485
1781
  } catch {}
1486
1782
  }
1783
+ const { buildRoutineCandidate } = await loadLearning()
1487
1784
  const candidate = buildRoutineCandidate({ text, toolLog, artifacts })
1488
1785
  if (candidate && !ledger.listRoutines().some((r) => r.name === candidate.name)) {
1489
1786
  try {
@@ -1521,6 +1818,7 @@ async function chat(args) {
1521
1818
  const ledger = loadLedger()
1522
1819
  const runtime = runtimeFor(ledger)
1523
1820
  await runTurn({ runtime, ledger, text, conversationId: latestConversationId(), attachments: files })
1821
+ if (lastTurnSafetyBlock) process.exitCode = 1
1524
1822
  saveLedger(ledger)
1525
1823
  }
1526
1824
 
@@ -1540,7 +1838,7 @@ async function repl() {
1540
1838
  }
1541
1839
  try {
1542
1840
  const latest = dbStore()?.listSessions(1)[0]
1543
- printOpening(latest?.conversationId ?? conversationId)
1841
+ await printOpening(latest?.conversationId ?? conversationId)
1544
1842
  } catch {}
1545
1843
  console.log('/help for commands, /quit to leave')
1546
1844
 
@@ -1645,6 +1943,7 @@ async function repl() {
1645
1943
  continue
1646
1944
  }
1647
1945
  if (text === '/decay') {
1946
+ const { applyPreferenceDecay } = await loadLearning()
1648
1947
  const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
1649
1948
  saveLedger(ledger)
1650
1949
  console.log(`[decay] ${changed.length} preference(s) updated`)
@@ -1664,6 +1963,7 @@ async function repl() {
1664
1963
  if (text === '/week') { printWeek(ledger); continue }
1665
1964
  if (text === '/digest' || text === '/digest day' || text === '/digest week') {
1666
1965
  const store = dbStore()
1966
+ const { buildDigest } = await loadDigest()
1667
1967
  console.log(buildDigest({
1668
1968
  period: text.endsWith('week') ? 'week' : 'day',
1669
1969
  turns: store?.listTurns(conversationId, 200) ?? [],
@@ -1673,11 +1973,13 @@ async function repl() {
1673
1973
  continue
1674
1974
  }
1675
1975
  if (text === '/diff') {
1976
+ const { diffLatest } = await loadUndo()
1676
1977
  const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
1677
1978
  console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
1678
1979
  continue
1679
1980
  }
1680
1981
  if (text === '/undo') {
1982
+ const { undoLatest } = await loadUndo()
1681
1983
  const result = await undoLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo'), force: args.includes('--force') })
1682
1984
  console.log(result.ok ? `已回滚:${result.path}` : `撤销失败:${result.error}`)
1683
1985
  continue
@@ -1753,7 +2055,7 @@ async function repl() {
1753
2055
  pendingFiles = []
1754
2056
  console.log(`resumed: ${pick.title} [${pick.conversationId}]`)
1755
2057
  } catch { console.log('history is not available') }
1756
- printOpening(conversationId)
2058
+ await printOpening(conversationId)
1757
2059
  continue
1758
2060
  }
1759
2061
  if (text.startsWith('/brief ')) {
@@ -1763,6 +2065,7 @@ async function repl() {
1763
2065
  continue
1764
2066
  }
1765
2067
  if (text.startsWith('/')) { console.log(`unknown command: ${text}; /help`); continue }
2068
+ const { correctionStatement } = await loadLearning()
1766
2069
  const feedback = correctionStatement(text)
1767
2070
  if (feedback) {
1768
2071
  const result = learnPreference(ledger, feedback, text, { explicit: /^(以后|记住|每次)/.test(text) })
@@ -1869,6 +2172,9 @@ async function importLedger(file, { replace = false } = {}) {
1869
2172
  if (!data || !Array.isArray(data.matters)) { console.error('import file does not contain an Advisers ledger'); process.exitCode = 1; return }
1870
2173
  await requireTosReaccept({ scope: 'import', subject: basename(file), action: 'import --replace' })
1871
2174
  ensureHome()
2175
+ // import replaces the ledger wholesale; serialize it with every other store
2176
+ // user (P0-1) before copying the pre-import backup and writing.
2177
+ ensureInstanceLock()
1872
2178
  try {
1873
2179
  const store = dbStore()
1874
2180
  if (store) copyFileSync(DB, join(HOME, `import-backup-${Date.now()}.db`))
@@ -1883,6 +2189,13 @@ async function importLedger(file, { replace = false } = {}) {
1883
2189
 
1884
2190
  function backup(file) {
1885
2191
  if (!file) { console.error('usage: advisers backup <path.db>'); process.exitCode = 1; return }
2192
+ const sealed = vaultSealedPath()
2193
+ if (sealed) {
2194
+ console.error(`advisers: E_VAULT_SEALED — cannot back up a sealed database (${sealed}).`)
2195
+ console.error('Run `advisers vault unseal` first; the sealed file itself is already an encrypted backup.')
2196
+ process.exitCode = 1
2197
+ return
2198
+ }
1886
2199
  const store = openStore()
1887
2200
  const checkpoint = store.checkpoint()
1888
2201
  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 +2220,7 @@ async function brief(text, deep = false) {
1907
2220
  const briefDenied = egressDeniedReason(briefLedger.getMatter(activeMatterId(briefLedger)), 'brief --deep')
1908
2221
  if (briefDenied) { console.error(briefDenied); process.exitCode = 1; return }
1909
2222
  try {
2223
+ const { chatCompletion } = await loadModel()
1910
2224
  const response = await chatCompletion({
1911
2225
  apiKey: process.env.ADVISERS_API_KEY,
1912
2226
  baseUrl: process.env.ADVISERS_BASE_URL,
@@ -1990,6 +2304,7 @@ async function routine(sub, arg, arg2) {
1990
2304
  if (!arg) { console.error('usage: advisers routine check <id>'); process.exitCode = 1; return }
1991
2305
  const routine = ledger.listRoutines().find((r) => r.id === arg)
1992
2306
  if (!routine) { console.error(`unknown routine: ${arg}`); process.exitCode = 1; return }
2307
+ const { checkRoutine } = await loadRoutine()
1993
2308
  const result = checkRoutine(routine)
1994
2309
  for (const item of result.results) console.log(`${item.ok ? 'ok' : 'FAIL'}\t${item.kind}\t${item.entry}`)
1995
2310
  if (!result.ok) process.exitCode = 1
@@ -2054,6 +2369,7 @@ async function routine(sub, arg, arg2) {
2054
2369
  const routine = ledger.listRoutines().find((r) => r.id === pending.routineId)
2055
2370
  if (!routine) { console.error(`unknown routine: ${pending.routineId}`); process.exitCode = 1; return }
2056
2371
  const candidate = { ...routine, ...pending.changes }
2372
+ const { checkRoutine } = await loadRoutine()
2057
2373
  const check = checkRoutine(candidate)
2058
2374
  if (!check.ok) {
2059
2375
  console.error('routine checks failed; patch not applied')
@@ -2152,6 +2468,7 @@ async function documentReview(args) {
2152
2468
  if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
2153
2469
  else { try { mod = await import('advisers-office') } catch { mod = await import('../../office/dist/index.js') } }
2154
2470
  const doc = await mod.readOffice(readFileSync(file))
2471
+ const { reviewDocument } = await loadDocReview()
2155
2472
  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
2473
  dbStore()?.appendAudit({ actor: 'local', action: 'doc.review', allowed: !result.findings.some((f) => f.severity === 'blocker'), reason: file })
2157
2474
  console.log(result.summary || '(no summary)')
@@ -2172,7 +2489,20 @@ async function research(args) {
2172
2489
  const matterId = activeMatterId(ledger)
2173
2490
  const denied = egressDeniedReason(ledger.getMatter(matterId), 'research')
2174
2491
  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) })
2492
+ // Privacy audit P1-2: the library already redacts upstream bodies, but the CLI
2493
+ // must not print stacks/upstream text either. Print only stable status + code.
2494
+ let result
2495
+ try {
2496
+ const { research: runResearch } = await loadResearch()
2497
+ result = await runResearch({ query, urls, apiKey, baseUrl: process.env.ADVISERS_BASE_URL, deep: Boolean(flags.deep) })
2498
+ } catch (error) {
2499
+ const status = Number.isFinite(Number(error?.status)) ? `HTTP ${Number(error.status)} ` : ''
2500
+ const rawCode = String(error?.code ?? error?.name ?? 'RESEARCH_FAILED').toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 40)
2501
+ console.error(`research failed: ${status}(${rawCode || 'RESEARCH_FAILED'})`)
2502
+ 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`.')
2503
+ process.exitCode = 1
2504
+ return
2505
+ }
2176
2506
  const store = dbStore()
2177
2507
  store?.addResearchRun({ matterId, query: query || urls[0], answer: result.answer, sources: result.sources, usage: result.usage, stopReason: result.stopReason })
2178
2508
  store?.appendAudit({ actor: 'local', action: 'egress.research', allowed: true, reason: `${urls.length ? 'url' : 'search'}:${result.sources.length}` })
@@ -2210,6 +2540,7 @@ async function buildCaptureSource({ meta, quote, ref, capturedAt }) {
2210
2540
  * @returns {Promise<{count: number, candidates: object[]}>}
2211
2541
  */
2212
2542
  async function proposeCaptureText({ text, source = 'wechat', date, matterId, meta = {}, store, json = false }) {
2543
+ const { captureCandidates } = await loadCapture()
2213
2544
  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
2545
  if (!result.candidates.length) return { count: 0, candidates: [] }
2215
2546
  const conversationId = latestConversationId()
@@ -2373,6 +2704,7 @@ async function captureFromImap(flags) {
2373
2704
  const { parseEml, dedupeKey, toCaptureInput } = await loadImporters()
2374
2705
  let messages
2375
2706
  try {
2707
+ const { fetchImapMessages } = await loadImap()
2376
2708
  messages = await fetchImapMessages({
2377
2709
  host,
2378
2710
  port: Number(process.env.ADVISERS_IMAP_PORT) || (String(process.env.ADVISERS_IMAP_SECURE) === '0' ? 143 : 993),
@@ -2474,9 +2806,20 @@ async function printCalendarToday() {
2474
2806
  }
2475
2807
  }
2476
2808
 
2809
+ /** Host header allowlist for the local read-only UI (DNS-rebinding hardening, SEC2-07). */
2810
+ function isLoopbackHostHeader(host) {
2811
+ if (!host) return false
2812
+ const value = String(host).trim().toLowerCase()
2813
+ const bare = value.startsWith('[')
2814
+ ? value.replace(/^\[([^\]]+)\](?::\d+)?$/, '$1')
2815
+ : value.replace(/:\d+$/, '')
2816
+ return bare === '127.0.0.1' || bare === 'localhost' || bare === '::1'
2817
+ }
2818
+
2477
2819
  async function ui(args) {
2478
2820
  const flags = parseFlags(args).flags
2479
- const port = Number(flags.port) || 17860
2821
+ // --port 0 requests an ephemeral port (used by tests and scripts).
2822
+ const port = typeof flags.port === 'string' && flags.port.trim() !== '' ? Number(flags.port) : 17860
2480
2823
  const ledger = loadLedger()
2481
2824
  const store = dbStore()
2482
2825
  const { buildReminders } = await loadRemind()
@@ -2489,7 +2832,20 @@ async function ui(args) {
2489
2832
  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
2833
  reminders: () => buildReminders(ledger, { now: new Date() }),
2491
2834
  }
2835
+ const { createReadOnlyServer } = await loadUi()
2492
2836
  const app = createReadOnlyServer({ snapshot, port })
2837
+ // SEC2-07: DNS rebinding can point an attacker origin at 127.0.0.1; the
2838
+ // library only checks method=GET, so validate Host before its handler runs.
2839
+ const handlers = app.server.listeners('request').slice()
2840
+ app.server.removeAllListeners('request')
2841
+ app.server.on('request', (req, res) => {
2842
+ if (!isLoopbackHostHeader(req.headers.host)) {
2843
+ res.writeHead(403, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' })
2844
+ res.end(JSON.stringify({ error: 'forbidden host header' }))
2845
+ return
2846
+ }
2847
+ for (const handler of handlers) handler.call(app.server, req, res)
2848
+ })
2493
2849
  const url = await app.listen()
2494
2850
  console.log(`advisers ui (read-only): ${url}`)
2495
2851
  console.log('Ctrl-C to stop; no writes, no telemetry, 127.0.0.1 only.')
@@ -2717,7 +3073,6 @@ async function deliver(args) {
2717
3073
  }
2718
3074
  sections.push({ heading: '校验', paragraphs: [`内容哈希:${sha256Hex(JSON.stringify(commitments.map((c) => ({ id: c.id, action: c.action, dueAt: c.dueAt, evidence: c.evidence }))))}`, '本文件由本地账本生成;哈希用于事后比对,不是第三方存证。'] })
2719
3075
  try {
2720
- const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
2721
3076
  let buffer
2722
3077
  if (format === 'pdf') {
2723
3078
  const { buildSimplePdf } = await loadPdf()
@@ -2727,6 +3082,9 @@ async function deliver(args) {
2727
3082
  await backupCliFile(out)
2728
3083
  writeFileSync(out, buffer)
2729
3084
  } else if (format === 'xlsx') {
3085
+ // P2-3: the office barrel (exceljs + pptxgenjs + read/check) is only paid
3086
+ // on the formats that actually need it; PDF used to import it too.
3087
+ const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
2730
3088
  const rows = commitments.map((c) => ({
2731
3089
  id: c.id, creditor: c.creditor, action: c.action, due: c.dueAt ?? '',
2732
3090
  status: c.status, evidence: (c.evidence ?? []).length,
@@ -2742,6 +3100,7 @@ async function deliver(args) {
2742
3100
  await backupCliFile(out)
2743
3101
  writeFileSync(out, buffer)
2744
3102
  } else {
3103
+ const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
2745
3104
  buffer = await mod.buildDocx({ title: `${label} · Advisers`, sections })
2746
3105
  await mod.validateOffice(buffer, 'docx')
2747
3106
  await backupCliFile(out)
@@ -2784,7 +3143,23 @@ async function mcpServer() {
2784
3143
  version: VERSION,
2785
3144
  audit: (entry) => store?.appendAudit(entry),
2786
3145
  })
2787
- await server.serve(process.stdin, process.stdout)
3146
+ // Robustness audit P2-3: a closed client stdout surfaces as an asynchronous
3147
+ // 'error' event (EPIPE) and used to reach the global uncaughtException handler
3148
+ // as "write EPIPE"/exit 1. The MCP host went away, so exit cleanly (0).
3149
+ const onStdoutError = (error) => {
3150
+ if (error?.code === 'EPIPE') {
3151
+ try { process.stdin.pause() } catch {}
3152
+ process.exit(0)
3153
+ }
3154
+ console.error(`advisers: ${friendlyError(error)}`)
3155
+ process.exit(1)
3156
+ }
3157
+ process.stdout.on('error', onStdoutError)
3158
+ try {
3159
+ await server.serve(process.stdin, process.stdout)
3160
+ } finally {
3161
+ process.stdout.removeListener('error', onStdoutError)
3162
+ }
2788
3163
  }
2789
3164
 
2790
3165
  async function ocrCommand(args) {
@@ -2811,13 +3186,74 @@ function vaultPass() {
2811
3186
  return pass
2812
3187
  }
2813
3188
 
3189
+ /**
3190
+ * Plaintext database copies left behind by unseal/migrate/import/sync and by an
3191
+ * interrupted unseal (robustness audit P1-2). `vault seal --remove` must delete
3192
+ * these too, otherwise the CLI says "plaintext removed" while a readable SQLite
3193
+ * copy (including the before-unseal backup) is still in HOME.
3194
+ */
3195
+ const PLAINTEXT_DB_COPY_RE = /^(?:state\.db\.before-(?:unseal|migrate|sync)-|\.state\.db\.unseal-|import-backup-)/
3196
+ function plaintextDbCopies() {
3197
+ try {
3198
+ return readdirSync(HOME).filter((name) => PLAINTEXT_DB_COPY_RE.test(name)).map((name) => join(HOME, name))
3199
+ } catch {
3200
+ return []
3201
+ }
3202
+ }
3203
+
3204
+ /**
3205
+ * Remove the live plaintext database and every plaintext copy. Failures are
3206
+ * collected (never swallowed) so the caller can report them and exit non-zero.
3207
+ */
3208
+ function removePlaintextDatabase() {
3209
+ const removed = []
3210
+ const failures = []
3211
+ for (const file of [DB, `${DB}-wal`, `${DB}-shm`, ...plaintextDbCopies()]) {
3212
+ try {
3213
+ if (!existsSync(file)) continue
3214
+ rmSync(file)
3215
+ removed.push(file)
3216
+ } catch (error) {
3217
+ failures.push(`${file}: ${error.message}`)
3218
+ }
3219
+ }
3220
+ fsyncDir(HOME)
3221
+ return { removed, failures }
3222
+ }
3223
+
3224
+ /** Print the result of a --remove cleanup; returns true only when nothing failed. */
3225
+ function reportPlaintextCleanup(cleanup, out) {
3226
+ if (cleanup.failures.length) {
3227
+ console.error(`vault seal failed: the sealed file ${out} is in place, but ${cleanup.failures.length} plaintext file(s) could not be removed:`)
3228
+ for (const failure of cleanup.failures) console.error(` ${failure}`)
3229
+ console.error('Close other advisers processes / check file permissions, then rerun `advisers vault seal --remove`.')
3230
+ process.exitCode = 1
3231
+ return false
3232
+ }
3233
+ console.log(`sealed ${DB} -> ${out} (plaintext removed: ${cleanup.removed.length} file(s))`)
3234
+ return true
3235
+ }
3236
+
2814
3237
  async function vaultSeal(args) {
2815
3238
  const { flags } = parseFlags(args)
2816
3239
  ensureHome()
2817
- if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
3240
+ // P1-3: seal mutates/removes state.db, so it takes the same single-writer lock
3241
+ // as ordinary commands; a ui/mcp/bridge server holding the store now makes seal
3242
+ // fail with E_DB_LOCKED instead of silently discarding that process's writes.
3243
+ ensureInstanceLock()
3244
+ const removePlaintext = Boolean(flags.remove) || args.includes('--remove')
3245
+ if (!existsSync(DB)) {
3246
+ const sealed = vaultSealedPath()
3247
+ // Already sealed: --remove still means "purge the leftover plaintext copies".
3248
+ if (sealed && removePlaintext) return reportPlaintextCleanup(removePlaintextDatabase(), sealed)
3249
+ console.error(sealed
3250
+ ? `advisers: E_VAULT_SEALED — no plaintext database at ${DB}; the sealed file ${sealed} is intact.`
3251
+ : `no database at ${DB}`)
3252
+ process.exitCode = 1
3253
+ return
3254
+ }
2818
3255
  const pass = vaultPass(); if (!pass) return
2819
3256
  const { encryptJson, decryptJson } = await loadVault()
2820
- const removePlaintext = Boolean(flags.remove) || args.includes('--remove')
2821
3257
  try {
2822
3258
  const store = new SqliteStore(DB)
2823
3259
  try {
@@ -2841,10 +3277,10 @@ async function vaultSeal(args) {
2841
3277
  const check = decryptJson(JSON.parse(readFileSync(out, 'utf8')), pass)
2842
3278
  if (check.sha256 !== sha) throw new Error('sealed file verification failed')
2843
3279
  if (removePlaintext) {
2844
- for (const f of [DB, `${DB}-wal`, `${DB}-shm`]) { try { if (existsSync(f)) rmSync(f) } catch {} }
2845
- fsyncDir(HOME)
3280
+ if (!reportPlaintextCleanup(removePlaintextDatabase(), out)) return
3281
+ return
2846
3282
  }
2847
- console.log(`sealed ${DB} -> ${out}${removePlaintext ? ' (plaintext removed)' : ' (plaintext kept; pass --remove)'}`)
3283
+ console.log(`sealed ${DB} -> ${out} (plaintext kept; pass --remove)`)
2848
3284
  } catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1 }
2849
3285
  }
2850
3286
 
@@ -2867,6 +3303,9 @@ async function vaultUnseal(args) {
2867
3303
  return
2868
3304
  }
2869
3305
  ensureHome()
3306
+ // P1-3: unseal replaces state.db; hold the single-writer lock for the whole
3307
+ // verify + backup + rename sequence (E_DB_LOCKED while another process runs).
3308
+ ensureInstanceLock()
2870
3309
  // P1-3: never write the payload straight over the live database. Write a
2871
3310
  // same-directory temp file, fsync it, verify the SQLite image, keep the old
2872
3311
  // database (and its WAL) as a backup, then rename atomically.
@@ -2910,6 +3349,8 @@ function vaultStatus() {
2910
3349
  console.log(`database: ${existsSync(DB) ? DB : 'absent'}`)
2911
3350
  console.log(`sealed: ${existsSync(sealed) ? sealed : 'none'}`)
2912
3351
  console.log(`state: ${existsSync(DB) ? 'plaintext at rest' : existsSync(sealed) ? 'encrypted at rest (run vault unseal)' : 'empty'}`)
3352
+ const copies = plaintextDbCopies()
3353
+ if (copies.length) console.log(`plaintext copies: ${copies.length} (run \`advisers vault seal --remove\` to purge them)`)
2913
3354
  }
2914
3355
 
2915
3356
  async function timestampCommand(args) {
@@ -3033,6 +3474,10 @@ async function syncCommand(args) {
3033
3474
  }
3034
3475
  const pass = syncPass(); if (!pass) return
3035
3476
  ensureHome()
3477
+ // P1-3: push checkpoints/copies the live database and pull replaces it, so both
3478
+ // must not run while another process holds the store (or be run by two sync
3479
+ // commands at once). The lock is held for the whole operation.
3480
+ if (sub === 'push' || sub === 'pull') ensureInstanceLock()
3036
3481
  if (sub === 'push') {
3037
3482
  if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
3038
3483
  const device = typeof flags.device === 'string' ? flags.device : hostname()
@@ -3145,17 +3590,33 @@ async function evidencePack(args) {
3145
3590
  facts: ledger.listFacts().map((f) => f.id),
3146
3591
  preferences: ledger.listPreferences({ includeCandidates: false }).map((p) => p.id),
3147
3592
  }
3148
- const { buildEvidencePack, toDocxRows, verifyPack } = await loadEvidence()
3149
- const pack = buildEvidencePack({ store, ledger, ids: targetIds })
3593
+ const { buildEvidencePack, toDocxRows, verifyPack, EvidencePackLimitError } = await loadEvidence()
3594
+ let pack
3595
+ try {
3596
+ // Performance audit P1-1: --all was parsed but never forwarded, so the
3597
+ // documented escape hatch was a no-op and large ledgers always failed.
3598
+ pack = buildEvidencePack({ store, ledger, ids: targetIds, all: flags.all === true })
3599
+ } catch (error) {
3600
+ if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
3601
+ console.error('error: ' + error.message)
3602
+ if (error.hint) console.error('hint: ' + error.hint)
3603
+ process.exitCode = 1
3604
+ return
3605
+ }
3606
+ throw error
3607
+ }
3150
3608
  const out = flags.out ? String(flags.out) : join(HOME, 'evidence', `evidence-${new Date().toISOString().replace(/[:.]/g, '-')}`)
3151
3609
  mkdirSync(out, { recursive: true, mode: 0o700 })
3152
3610
  for (const [name, content] of Object.entries(pack.files)) writeFileSync(join(out, name), content, { mode: 0o600 })
3153
3611
  let receipt
3154
3612
  try {
3155
- const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
3613
+ // P2-3: import the docx/validate submodules, not the office barrel.
3614
+ const docxModule = await importOfficeSubmodule('docx')
3615
+ if (typeof docxModule?.buildDocx !== 'function') throw new Error('advisers-office docx builder is not available')
3616
+ const validateOffice = await loadOfficeOperation('validate', 'validateOffice')
3156
3617
  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')
3618
+ const buffer = await docxModule.buildDocx({ title: '证据包回执', sections: [{ heading: '证据清单', paragraphs: rows.length ? rows : ['(没有可导出条目)'] }, { heading: '校验', paragraphs: [`manifest.json / README.txt 的 SHA256 见 SHA256SUMS`, `生成时间:${new Date().toISOString()}`, 'SHA256SUMS 只证明包生成后未被修改;不是签名或第三方存证。'] }] })
3619
+ await validateOffice(buffer, 'docx')
3159
3620
  writeFileSync(join(out, 'receipt.docx'), buffer)
3160
3621
  receipt = join(out, 'receipt.docx')
3161
3622
  } catch (error) { console.error(`docx receipt skipped: ${error.message}`) }
@@ -3551,6 +4012,76 @@ function link(sub, from, to, type) {
3551
4012
  process.exitCode = 1
3552
4013
  }
3553
4014
 
4015
+ /**
4016
+ * Bridge (Hermes file gateway) hardening — security audit P1-1 / SEC2-09.
4017
+ *
4018
+ * The bridge library owns the wire format; the CLI tightens what it can before
4019
+ * the library sees it: 0700 directories / 0600 files (the library used mkdir and
4020
+ * writeFile defaults), a 1 MiB inbox cap enforced before its unbounded readFile,
4021
+ * and no absolute local attachment paths in the outbox JSON. The library polls
4022
+ * through the instance method, so wrapping pollOnce() covers both the immediate
4023
+ * poll in start() and the interval.
4024
+ */
4025
+ const BRIDGE_INBOX_MAX_BYTES = 1024 * 1024
4026
+
4027
+ function bridgeDirs(bridgeDir, name) {
4028
+ return {
4029
+ inbox: join(bridgeDir, 'inbox', name),
4030
+ outbox: join(bridgeDir, 'outbox', name),
4031
+ status: join(bridgeDir, 'status', name),
4032
+ registry: join(bridgeDir, 'registry'),
4033
+ quarantine: join(bridgeDir, 'quarantine', name),
4034
+ }
4035
+ }
4036
+
4037
+ function secureBridgeTree(bridgeDir, name) {
4038
+ const dirs = bridgeDirs(bridgeDir, name)
4039
+ for (const dir of Object.values(dirs)) {
4040
+ try { mkdirSync(dir, { recursive: true, mode: 0o700 }); chmodSync(dir, 0o700) } catch {}
4041
+ }
4042
+ for (const dir of [dirs.outbox, dirs.registry, dirs.inbox]) {
4043
+ let files
4044
+ try { files = readdirSync(dir) } catch { continue }
4045
+ for (const file of files) {
4046
+ try { chmodSync(join(dir, file), 0o600) } catch {}
4047
+ }
4048
+ }
4049
+ }
4050
+
4051
+ /** Move oversized inbox files out of the library's readFile path (DoS guard). */
4052
+ function guardBridgeInbox(bridgeDir, name) {
4053
+ const dirs = bridgeDirs(bridgeDir, name)
4054
+ let files
4055
+ try { files = readdirSync(dirs.inbox) } catch { return }
4056
+ for (const file of files) {
4057
+ if (!file.endsWith('.json')) continue
4058
+ const source = join(dirs.inbox, file)
4059
+ let size
4060
+ try { size = statSync(source).size } catch { continue }
4061
+ try { chmodSync(source, 0o600) } catch {}
4062
+ if (size <= BRIDGE_INBOX_MAX_BYTES) continue
4063
+ try {
4064
+ mkdirSync(dirs.quarantine, { recursive: true, mode: 0o700 })
4065
+ chmodSync(dirs.quarantine, 0o700)
4066
+ renameSync(source, join(dirs.quarantine, file))
4067
+ dbStore()?.appendAudit({ actor: 'bridge', action: 'bridge.inbox_quarantine', allowed: false, reason: `${size} bytes > ${BRIDGE_INBOX_MAX_BYTES}` })
4068
+ console.log(`[bridge] quarantined oversized inbox file ${file} (${size} bytes)`)
4069
+ } catch {}
4070
+ }
4071
+ }
4072
+
4073
+ /** Never hand an absolute local attachment path to the third-party Hermes side. */
4074
+ function sanitizeBridgeOutbound(message) {
4075
+ if (!message || !Array.isArray(message.attachments) || !message.attachments.length) return message
4076
+ const attachments = message.attachments.map((attachment) => {
4077
+ const next = { ...(attachment ?? {}) }
4078
+ delete next.localPath
4079
+ if (typeof next.url === 'string' && isAbsolute(next.url)) delete next.url
4080
+ return next
4081
+ })
4082
+ return { ...message, attachments }
4083
+ }
4084
+
3554
4085
  async function bridge(args) {
3555
4086
  let dir
3556
4087
  let name = 'advisers'
@@ -3564,6 +4095,9 @@ async function bridge(args) {
3564
4095
  process.exitCode = 1
3565
4096
  return
3566
4097
  }
4098
+ // Files/directories below are private conversation data; tighten the umask for
4099
+ // every file this process creates in the bridge tree (SEC2-09: outbox 0644).
4100
+ process.umask(0o077)
3567
4101
  let mod
3568
4102
  if (process.env.ADVISERS_BRIDGE_LOCAL === '1') {
3569
4103
  mod = await import('../../bridge-hermes/dist/index.js')
@@ -3579,6 +4113,20 @@ async function bridge(args) {
3579
4113
  const ledger = loadLedger()
3580
4114
  const runtime = runtimeFor(ledger)
3581
4115
  const link = new mod.HermesBridgeLink({ bridgeDir: dir, name })
4116
+ const libraryPollOnce = link.pollOnce.bind(link)
4117
+ link.pollOnce = async () => {
4118
+ guardBridgeInbox(dir, name)
4119
+ const polled = await libraryPollOnce()
4120
+ secureBridgeTree(dir, name)
4121
+ return polled
4122
+ }
4123
+ const librarySend = link.send.bind(link)
4124
+ link.send = async (message) => {
4125
+ const sent = await librarySend(sanitizeBridgeOutbound(message))
4126
+ secureBridgeTree(dir, name)
4127
+ return sent
4128
+ }
4129
+ secureBridgeTree(dir, name)
3582
4130
  const permitSecret = process.env.ADVISERS_PERMIT_SECRET || randomUUID()
3583
4131
  const permitGate = new core.PermitGate(permitSecret, { replay: dbStore()?.permitReplayStore() })
3584
4132
  const host = {
@@ -3594,6 +4142,14 @@ async function bridge(args) {
3594
4142
  dbStore()?.appendAudit({ actor: 'bridge', action: 'policy.deny', allowed: false, reason: context.policy.code ?? 'DENY' })
3595
4143
  reply = context.policy.reason
3596
4144
  }
4145
+ // Security audit P1-1: bridge is a model egress path; apply the same
4146
+ // matter-secrecy gate as chat/review/research BEFORE any network call.
4147
+ const bridgeEgressDenied = reply ? null : egressDeniedReason(context.matter, 'bridge')
4148
+ if (bridgeEgressDenied) {
4149
+ dbStore()?.appendAudit({ actor: 'bridge', action: 'policy.egress_deny', allowed: false, reason: 'bridge' })
4150
+ console.log(`[bridge] blocked: ${bridgeEgressDenied}`)
4151
+ reply = '[advisers] received (protected matter: model call denied)'
4152
+ }
3597
4153
  const key = process.env.ADVISERS_API_KEY
3598
4154
  if (!reply && key && process.env.ADVISERS_NO_MODEL !== '1') {
3599
4155
  try {
@@ -3771,8 +4327,17 @@ async function soul(sub, file) {
3771
4327
  // names version/sha256/channel and NEVER the terms text.
3772
4328
  // ---------------------------------------------------------------------------
3773
4329
 
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'])
4330
+ /**
4331
+ * Commands usable without accepting the TOS (TOS §2.1: local functions stay usable).
4332
+ * TOS §2.1 / §9.8: reviewing, exporting and deleting your own local data is not
4333
+ * a gated feature. After a revoke the data-rights commands (privacy/export/
4334
+ * audit/purge), tos itself, and the other local-only commands below must stay
4335
+ * usable, otherwise the user must re-consent before exporting or deleting data.
4336
+ */
4337
+ const TOS_EXEMPT_COMMANDS = new Set([
4338
+ 'help', '--help', '-h', 'version', '--version', '-v', 'status', 'doctor', 'init', 'tos',
4339
+ 'privacy', 'export', 'audit', 'purge',
4340
+ ])
3776
4341
  /** Known commands. Unknown commands keep the plain "unknown command" error, not the gate. */
3777
4342
  const KNOWN_COMMANDS = new Set([
3778
4343
  'version', '--version', '-v', 'help', '--help', 'chat', 'status', 'doctor', 'init', 'history', 'mcp',
@@ -4102,6 +4667,7 @@ if (!command) {
4102
4667
  if (!run || !apiKey) { console.error('usage: ADVISERS_API_KEY=... advisers learn review <run-id>'); process.exitCode = 1 }
4103
4668
  else {
4104
4669
  const ledger = loadLedger()
4670
+ const { reviewRun, lintReview, materializeReview } = await loadReview()
4105
4671
  const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
4106
4672
  const checked = lintReview(review, { run, routines: ledger.listRoutines() })
4107
4673
  if (!checked.ok) { console.error(`review rejected: ${checked.error}`); process.exitCode = 1 }
@@ -4198,10 +4764,12 @@ if (!command) {
4198
4764
  }
4199
4765
  } else { console.error('usage: advisers commit add|edit|ls|done|snooze'); process.exitCode = 1 }
4200
4766
  } else if (command === 'diff') {
4767
+ const { diffLatest } = await loadUndo()
4201
4768
  const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
4202
4769
  console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
4203
4770
  if (!result.ok) process.exitCode = 1
4204
4771
  } else if (command === 'undo') {
4772
+ const { listBackups, undoLatest } = await loadUndo()
4205
4773
  if (args.includes('--list')) {
4206
4774
  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
4775
  } else {
@@ -4315,6 +4883,7 @@ if (!command) {
4315
4883
  } else if (command === 'digest') {
4316
4884
  const period = args[0] === 'week' ? 'week' : 'day'
4317
4885
  const store = dbStore()
4886
+ const { buildDigest } = await loadDigest()
4318
4887
  console.log(buildDigest({
4319
4888
  period,
4320
4889
  turns: store?.listTurns(latestConversationId(), 200) ?? [],
@@ -4333,6 +4902,7 @@ if (!command) {
4333
4902
  purgeMatter(args[0], args.includes('--yes'))
4334
4903
  } else if (command === 'decay') {
4335
4904
  const ledger = loadLedger()
4905
+ const { applyPreferenceDecay } = await loadLearning()
4336
4906
  const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
4337
4907
  saveLedger(ledger)
4338
4908
  console.log(`[decay] ${changed.length} preference(s) updated`)