advisers 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE +0 -0
  2. package/NOTICE +0 -0
  3. package/README-zh.md +10 -6
  4. package/README.md +15 -6
  5. package/THIRD-PARTY-NOTICES.md +1 -1
  6. package/bin/advisers.js +3323 -222
  7. package/index.js +1 -1
  8. package/lib/agent.js +0 -0
  9. package/lib/attachments.js +0 -0
  10. package/lib/audit-anchor.js +683 -0
  11. package/lib/backup.js +1345 -0
  12. package/lib/capture.js +0 -0
  13. package/lib/context-window.js +0 -0
  14. package/lib/digest.js +0 -0
  15. package/lib/doc-review.js +0 -0
  16. package/lib/egress.js +0 -0
  17. package/lib/error-codes.js +1373 -0
  18. package/lib/evidence.js +202 -26
  19. package/lib/fs-safe.js +70 -7
  20. package/lib/ical.js +0 -0
  21. package/lib/imap.js +6 -2
  22. package/lib/importers.js +0 -0
  23. package/lib/learning.js +0 -0
  24. package/lib/ledger-read.js +608 -0
  25. package/lib/mcp-server.js +294 -38
  26. package/lib/model.js +0 -0
  27. package/lib/node-warning-filter.js +15 -0
  28. package/lib/notify.js +13 -3
  29. package/lib/nudge.js +0 -0
  30. package/lib/ocr.js +0 -0
  31. package/lib/pdf.js +0 -0
  32. package/lib/pet-brief-store.js +0 -0
  33. package/lib/pet-brief.js +102 -39
  34. package/lib/receipt-verify.js +213 -15
  35. package/lib/relative-date.js +0 -0
  36. package/lib/remind.js +91 -36
  37. package/lib/research.js +0 -0
  38. package/lib/review.js +0 -0
  39. package/lib/routine.js +0 -0
  40. package/lib/safety/classifier.js +0 -0
  41. package/lib/safety/explain.js +0 -0
  42. package/lib/safety/index.js +0 -0
  43. package/lib/safety/redact.js +0 -0
  44. package/lib/safety/rules.js +0 -0
  45. package/lib/scheduler.js +0 -0
  46. package/lib/source.js +0 -0
  47. package/lib/sqlite.js +1214 -24
  48. package/lib/sync.js +0 -0
  49. package/lib/text-safe.js +229 -0
  50. package/lib/timestamp.js +0 -0
  51. package/lib/tos/index.js +1 -1
  52. package/lib/tos/manifest.json +6 -6
  53. package/lib/tos/privacy.zh-CN.md +12 -9
  54. package/lib/tos/safety.zh-CN.md +4 -3
  55. package/lib/tos/summary.zh-CN.md +3 -3
  56. package/lib/tos/terms.zh-CN.md +8 -6
  57. package/lib/tui/color.js +164 -0
  58. package/lib/tui/index.js +33 -0
  59. package/lib/tui/json.js +124 -0
  60. package/lib/tui/labels.js +50 -0
  61. package/lib/tui/policy.js +108 -0
  62. package/lib/tui/render.js +371 -0
  63. package/lib/tui/sanitize.js +142 -0
  64. package/lib/tui/text-file.js +116 -0
  65. package/lib/tui/width.js +577 -0
  66. package/lib/ui.js +0 -0
  67. package/lib/undo.js +0 -0
  68. package/lib/untrusted.js +0 -0
  69. package/lib/vault.js +0 -0
  70. package/package.json +6 -5
package/bin/advisers.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import '../lib/node-warning-filter.js'
2
3
  import { spawnSync } from 'node:child_process'
3
4
  import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
4
5
  import { homedir, hostname } from 'node:os'
@@ -11,6 +12,10 @@ let inspectWalStatus
11
12
  let readInstanceLock
12
13
  let instanceLockIsStale
13
14
  let openReadStoreLib
15
+ let WAL_CORRUPT_SUFFIX
16
+ // 0.3.0 customer entities (destructured from lib/sqlite.js below).
17
+ let DATA_TABLES
18
+ let SCHEMA_VERSION
14
19
  try {
15
20
  ({
16
21
  SqliteStore,
@@ -20,6 +25,13 @@ try {
20
25
  readInstanceLock,
21
26
  instanceLockIsStale,
22
27
  openReadStore: openReadStoreLib,
28
+ WAL_CORRUPT_SUFFIX,
29
+ // 0.3.0 customer entities: DATA_TABLES is the single list export --all
30
+ // reads (and import --replace restores) so a new table cannot be silently
31
+ // dropped by a hard-coded bin list; SCHEMA_VERSION gates imports of a
32
+ // database/export written by a newer CLI.
33
+ DATA_TABLES,
34
+ SCHEMA_VERSION,
23
35
  } = await import('../lib/sqlite.js'))
24
36
  } catch (error) {
25
37
  if (String(error?.message || error).includes('node:sqlite')) {
@@ -28,7 +40,13 @@ try {
28
40
  }
29
41
  throw error
30
42
  }
31
- import { egressDeniedReason } from '../lib/egress.js'
43
+ import { egressDeniedReason, secrecyLevel } from '../lib/egress.js'
44
+ // 0.3.0 Wave 3 (TUI/console wiring, docs/TUI.md §4): the one-line console/log
45
+ // sanitiser is the chokepoint for text that came from outside the program before
46
+ // it reaches stderr, friendlyError()/reportFatalError() or reminders.log.
47
+ // lib/notify.js already sanitises webhook details and lib/imap.js sanitises
48
+ // server greeting/status lines; bin must not trust its own formatting either.
49
+ import { sanitizeConsoleText } from '../lib/text-safe.js'
32
50
  // 0.2.3 Wave 1: every durable bin/ output goes through the crash-safe helpers
33
51
  // (short-write loop, fsync, atomic rename, bounded Windows retry) instead of a
34
52
  // one-shot writeFileSync that ENOSPC can truncate.
@@ -39,6 +57,7 @@ import {
39
57
  describeFsError,
40
58
  fsyncDirSync,
41
59
  fsyncFileSync,
60
+ renameWithRetrySync,
42
61
  rmWithRetrySync,
43
62
  writeAllToTempSync,
44
63
  } from '../lib/fs-safe.js'
@@ -63,6 +82,9 @@ const loadIcal = lazyModule(() => import('../lib/ical.js'))
63
82
  const loadImporters = lazyModule(() => import('../lib/importers.js'))
64
83
  const loadNotify = lazyModule(() => import('../lib/notify.js'))
65
84
  const loadReceiptVerify = lazyModule(() => import('../lib/receipt-verify.js'))
85
+ // 0.3.0 Wave 2: operations libraries (audit tail anchor, backup rotation/restore).
86
+ const loadAuditAnchor = lazyModule(() => import('../lib/audit-anchor.js'))
87
+ const loadBackup = lazyModule(() => import('../lib/backup.js'))
66
88
  const loadScheduler = lazyModule(() => import('../lib/scheduler.js'))
67
89
  const loadSource = lazyModule(() => import('../lib/source.js'))
68
90
  const loadOcr = lazyModule(() => import('../lib/ocr.js'))
@@ -74,6 +96,10 @@ const loadVault = lazyModule(() => import('../lib/vault.js'))
74
96
  const loadTos = lazyModule(() => import('../lib/tos/index.js'))
75
97
  const loadMcpServer = lazyModule(() => import('../lib/mcp-server.js'))
76
98
  const loadSafety = lazyModule(() => import('../lib/safety/index.js'))
99
+ // 0.3.0 Wave 3: the output kernel (policy/width/render/json) is loaded only by
100
+ // the human-output paths that need it (tui, repl, rendered error blocks), so
101
+ // --version / --json-only commands do not pay for the width tables.
102
+ const loadTui = lazyModule(() => import('../lib/tui/index.js'))
77
103
  // P2-4 (0.2.1): every command used to pay for the full static import graph,
78
104
  // including the model/agent stack, safety classifier, Pet Brief, UI server,
79
105
  // IMAP client and review helpers (~63-75ms of compiled JS). They are only
@@ -197,6 +223,26 @@ const DAY_FORMAT = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai'
197
223
  /** Asia/Shanghai calendar day (YYYY-MM-DD) for a Date, timestamp or ISO string. */
198
224
  const localDayOf = (value) => DAY_FORMAT.format(new Date(value))
199
225
 
226
+ /**
227
+ * Calendar TZIDs the local reader accepts (0.3.0 Wave 3, 13-mail-calendar C5).
228
+ *
229
+ * lib/ical.js pins all wall-clock reasoning to Asia/Shanghai and ships no
230
+ * time-zone database, so both `agenda` and `today --calendar` must treat every
231
+ * other zone as degraded-and-skip instead of guessing. Before this, agenda
232
+ * skipped a Berlin event while today --calendar sliced the UTC instant as if it
233
+ * were +08:00 (Berlin 10:00 shown as 17:00) - one dataset, two semantics.
234
+ */
235
+ const CALENDAR_TZID_WHITELIST = new Set(['', 'Asia/Shanghai', 'UTC', 'Etc/UTC', 'GMT', 'Z'])
236
+
237
+ function calendarTzidOf(row) {
238
+ return row?.tzid === undefined || row?.tzid === null ? '' : String(row.tzid)
239
+ }
240
+
241
+ function calendarTzidSupported(row) {
242
+ const tzid = calendarTzidOf(row)
243
+ return !tzid || CALENDAR_TZID_WHITELIST.has(tzid)
244
+ }
245
+
200
246
  /**
201
247
  * P1-6: default upper bound for `advisers deliver` (open commitments).
202
248
  * --all lifts it; the command always reports the untruncated total.
@@ -670,20 +716,34 @@ function readLedgerForCommand(parts = null) {
670
716
  }
671
717
 
672
718
  /**
673
- * Minimal open-commitment rows for the HUMAN `today` view (0.2.3 hot path).
719
+ * 0.3.0 P0-T2: run one or more narrow read projections on the lock-free read
720
+ * store inside a single read transaction (one snapshot for a multi-part view).
721
+ * Returns null in legacy JSON-store mode so the caller keeps that path.
674
722
  *
675
- * `today` classifies every open commitment but only displays id/debtor/creditor/
676
- * action/dueAt. Loading them through loadCommitments() maps the full entity
677
- * (JSON.parse of evidence/reminder_offsets, defaults, sortable objects) which at
678
- * 200k rows is ~365ms in-process vs ~139ms for the six columns actually needed.
679
- * The JSON/sources forms keep the full entities (their contract needs them).
680
- * The query runs on the lock-free read connection and is read-only.
723
+ * The projections return only the columns the view reads, in table-scan order.
724
+ * Before this, `today` alone loaded 66k full commitment entities for five
725
+ * displayed columns and every `ORDER BY rowid` after a status predicate spilled
726
+ * a TEMP B-TREE (today 5.6 MB, pet-brief 29 MB of writes per run at 200k rows).
681
727
  */
682
- function loadOpenCommitmentRowsForToday() {
728
+ function readProjection(project) {
683
729
  const store = readStoreOrExit()
684
- if (!store) return []
685
- const rows = store.db.prepare("SELECT id, debtor, creditor, action, due_at FROM commitments WHERE status = 'open' ORDER BY rowid").all()
686
- return rows.map((row) => ({ id: row.id, debtor: row.debtor, creditor: row.creditor, action: row.action, dueAt: row.due_at ?? undefined }))
730
+ if (!store) return null
731
+ return store.read(() => project(store))
732
+ }
733
+
734
+ /** Minimal open-commitment rows for the HUMAN `today` view. */
735
+ function loadOpenCommitmentRowsForToday() {
736
+ return readProjection((store) => store.projectOpenCommitmentsForToday()) ?? []
737
+ }
738
+
739
+ /** Narrow commitment rows for reminder planning (remind / tui). */
740
+ function loadReminderRows({ includeUndated = false } = {}) {
741
+ return readProjection((store) => store.projectCommitmentsForReminders({ includeUndated }))
742
+ }
743
+
744
+ /** A ledger-shaped view over already-loaded narrow rows (no entity mapping). */
745
+ function reminderLedgerFromRows(rows) {
746
+ return { listCommitments: () => rows }
687
747
  }
688
748
 
689
749
  function exitStoreWriteFailure(error) {
@@ -795,7 +855,7 @@ function resolveDeliveryMatterId(store) {
795
855
  return matter.id
796
856
  }
797
857
 
798
- function recordDeliveryWithAudit({ files, tool, title, validation, audit, matterId }) {
858
+ function recordDeliveryWithAudit({ files, tool, title, validation, audit, matterId, clientId, projectId, templateName, templateVersion, quoteNo, dataSha256 }) {
799
859
  const store = dbStore()
800
860
  if (!store) return
801
861
  const conversationId = latestConversationId()
@@ -807,6 +867,16 @@ function recordDeliveryWithAudit({ files, tool, title, validation, audit, matter
807
867
  tool,
808
868
  title,
809
869
  validation: typeof validation === 'string' ? validation : JSON.stringify(validation),
870
+ // v21 lineage (0.3.0): snapshot WHO and WHICH template this delivery was
871
+ // generated for, at generation time. When the caller omits client/project
872
+ // the store derives them from the delivery's matter, so a later re-link
873
+ // never rewrites an already-generated receipt/timeline entry.
874
+ ...(clientId === undefined ? {} : { clientId }),
875
+ ...(projectId === undefined ? {} : { projectId }),
876
+ ...(templateName === undefined ? {} : { templateName }),
877
+ ...(templateVersion === undefined ? {} : { templateVersion }),
878
+ ...(quoteNo === undefined ? {} : { quoteNo }),
879
+ ...(dataSha256 === undefined ? {} : { dataSha256 }),
810
880
  }), audit)
811
881
  }
812
882
 
@@ -974,19 +1044,52 @@ async function askYesNo(rl, prompt, defaultYes = true) {
974
1044
  }
975
1045
 
976
1046
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
1047
+ /**
1048
+ * Additive `status --json` contracts discovery field (0.3.0 contract C6).
1049
+ *
1050
+ * Keep in sync with contracts/versions-v1.json `discovery.expected`: the
1051
+ * published npm package does not ship contracts/, so the CLI carries the frozen
1052
+ * values and `node scripts/check-contracts.mjs --status` asserts equality with
1053
+ * the artifact tree. mcpProtocol is the negotiated *default* legacy revision
1054
+ * (lib/mcp-server.js PROTOCOL_VERSION); a client may still negotiate 2025-06-18
1055
+ * or 2025-11-25 through initialize.
1056
+ */
1057
+ const CONTRACTS_DISCOVERY = Object.freeze({
1058
+ cliJson: 1,
1059
+ errors: 1,
1060
+ exitCodes: 1,
1061
+ mcpTools: 1,
1062
+ mcpResources: 1,
1063
+ mcpProtocol: '2024-11-05',
1064
+ dshTools: 1,
1065
+ petBrief: 2,
1066
+ })
977
1067
  function friendlyError(error) {
978
1068
  const message = error instanceof Error ? error.message : String(error)
979
1069
  if (/ENOENT/.test(message)) return 'file not found; check the path and run `advisers doctor`'
980
1070
  if (/Unexpected token|JSON/.test(message)) return 'invalid JSON; use UTF-8 without BOM and see examples/'
981
1071
  if (/model (HTTP|timeout)|fetch failed|ECONN/.test(message)) return 'model request failed; check ADVISERS_API_KEY / network and run `advisers doctor`'
982
1072
  if (/database is locked/.test(message)) return 'database is busy; close other advisers processes and retry'
983
- return message
1073
+ // 0.3.0 Wave 3: the fallback is where a raw Error message reaches the terminal.
1074
+ // Model/provider/IMAP errors can carry ANSI/OSC/bidi and inject a second line
1075
+ // (docs/TUI.md §4), so it always goes through the console sanitiser.
1076
+ return sanitizeConsoleText(message, { max: 4000 })
1077
+ }
1078
+
1079
+ /** Print one message with every line passed through the console sanitiser. */
1080
+ function printSafeConsoleLines(text, { stream = 'error', max = 4000 } = {}) {
1081
+ const write = stream === 'error' ? console.error : console.log
1082
+ for (const line of String(text ?? '').split('\n')) write(sanitizeConsoleText(line, { max }))
984
1083
  }
1084
+
985
1085
  function reportFatalError(error) {
986
1086
  // E_DB_LOCKED / E_DB_CORRUPT get backup/doctor/concurrency guidance instead of
987
1087
  // the generic one-line message (commands that touch the store without going
988
- // through loadLedger() end up here).
989
- console.error(storeFailureHint(error) ?? `advisers: ${friendlyError(error)}`)
1088
+ // through loadLedger() end up here). The hint and the fallback are both
1089
+ // untrusted in the same sense as any other error text.
1090
+ const hint = storeFailureHint(error)
1091
+ if (hint) printSafeConsoleLines(hint, { max: 4000 })
1092
+ else console.error(sanitizeConsoleText(`advisers: ${friendlyError(error)}`, { max: 4000 }))
990
1093
  process.exit(1)
991
1094
  }
992
1095
  process.on('uncaughtException', reportFatalError)
@@ -1003,8 +1106,61 @@ for (let index = rawArgv.length - 1; index >= 0; index--) {
1003
1106
  if (value === '--accept-tos') { acceptTosFlag = true; rawArgv.splice(index, 1) }
1004
1107
  else if (value.startsWith('--accept-tos=')) { acceptTosFlag = value.slice('--accept-tos='.length); rawArgv.splice(index, 1) }
1005
1108
  }
1109
+
1110
+ // 0.3.0 Wave 3: global output flags (docs/TUI.md §5-§6, plan 26 §5.5).
1111
+ //
1112
+ // --plain / --accessible / --color[=]auto|always|never are accepted by every
1113
+ // human-output command and stripped before the per-command flag parser runs, so
1114
+ // an older command cannot mistake them for one of its own options. The resolved
1115
+ // policy is computed lazily by getOutputPolicy() (tui + REPL consume it); the
1116
+ // commands that keep their historical bytes are otherwise unaffected.
1117
+ // NO_COLOR / ADVISERS_PLAIN / ADVISERS_ACCESSIBLE stay environment-only.
1118
+ const outputArgv = rawArgv.slice()
1119
+ const OUTPUT_MODE_FLAGS = new Set(['--plain', '--accessible'])
1120
+ const COLOR_MODES = new Set(['auto', 'always', 'never'])
1121
+ function invalidColorFlag(value) {
1122
+ console.error('advisers: E_USAGE: --color must be auto, always or never (got ' + JSON.stringify(String(value ?? '')) + ')')
1123
+ process.exit(1)
1124
+ }
1125
+ for (let index = rawArgv.length - 1; index >= 0; index--) {
1126
+ const value = rawArgv[index]
1127
+ if (OUTPUT_MODE_FLAGS.has(value)) { rawArgv.splice(index, 1); continue }
1128
+ if (value === '--color') {
1129
+ const mode = String(rawArgv[index + 1] ?? '').toLowerCase()
1130
+ if (!COLOR_MODES.has(mode)) invalidColorFlag(rawArgv[index + 1])
1131
+ rawArgv.splice(index, 2)
1132
+ continue
1133
+ }
1134
+ if (value.startsWith('--color=')) {
1135
+ const mode = value.slice('--color='.length).toLowerCase()
1136
+ if (!COLOR_MODES.has(mode)) invalidColorFlag(value.slice('--color='.length))
1137
+ rawArgv.splice(index, 1)
1138
+ }
1139
+ }
1140
+
1006
1141
  const [command, ...args] = rawArgv
1007
1142
 
1143
+ /**
1144
+ * Resolve the single output policy for this invocation (docs/TUI.md §5-§6).
1145
+ *
1146
+ * One decision object covers plain/accessible/colour/cursor control for the
1147
+ * whole process; renderers receive it spread into their options. Loaded lazily
1148
+ * because only tui and the REPL render through the kernel today.
1149
+ */
1150
+ let outputPolicyCache = null
1151
+ async function getOutputPolicy() {
1152
+ if (outputPolicyCache) return outputPolicyCache
1153
+ const { resolveOutputPolicy } = await loadTui()
1154
+ outputPolicyCache = resolveOutputPolicy({
1155
+ argv: outputArgv,
1156
+ env: process.env,
1157
+ stdinIsTTY: Boolean(process.stdin.isTTY),
1158
+ stdoutIsTTY: Boolean(process.stdout.isTTY),
1159
+ stderrIsTTY: Boolean(process.stderr.isTTY),
1160
+ })
1161
+ return outputPolicyCache
1162
+ }
1163
+
1008
1164
  function help() {
1009
1165
  console.log(`advisers — a staff of AI advisers
1010
1166
 
@@ -1013,10 +1169,14 @@ Usage:
1013
1169
  advisers chat [--file <path>] [--allow-path <dir>]... [text]
1014
1170
  one-shot task, or start the local conversation
1015
1171
  advisers init initialize home + soul
1016
- advisers doctor [--check-db]
1172
+ advisers doctor [--check-db] [--json]
1017
1173
  check Node/SQLite/Office/policy/model; --check-db adds
1018
1174
  quick_check + FTS integrity + WAL + backup + plaintext/temp checks
1019
- advisers status home/store/model/counts
1175
+ advisers doctor --repair [--dry-run|--yes] [--only lock,temp,wal,fts] [--json]
1176
+ recovery console: dry-run plan by default; --yes takes the
1177
+ writer lock, writes a safety backup, repairs, re-verifies,
1178
+ records doctor.repair and refreshes the audit anchor
1179
+ advisers status [--json] home/store/model/counts (+ contracts discovery in --json)
1020
1180
  advisers history recent conversations
1021
1181
  advisers search <text> full-text search old turns
1022
1182
  advisers compact ls|rollback summary versions
@@ -1031,7 +1191,7 @@ Usage:
1031
1191
  advisers pet-brief [--json] [--out [path]] [--check [--strict]] [--display-policy public|private|none]
1032
1192
  read-only redacted Pet Brief (contract v0.2); --print-schema prints the JSON Schema
1033
1193
  advisers tick due commitments in the next 7 days
1034
- advisers week last 7 days
1194
+ advisers week [--json] last 7 local days (Asia/Shanghai); --json is one JSON document
1035
1195
  advisers agenda [--days 7] [--json]
1036
1196
  7-day agenda: commitments + calendar_events, Asia/Shanghai days
1037
1197
  advisers morning [--json] [--out f]
@@ -1048,7 +1208,10 @@ Usage:
1048
1208
  advisers prefs [--all] | correct <text>
1049
1209
  advisers nudge list|done|ignore <id> nudge outcomes
1050
1210
  advisers decay apply 30-day preference decay
1051
- advisers audit verify the local audit hash chain
1211
+ advisers audit verify the local audit hash chain + tail anchor (--json, --check-db)
1212
+ advisers audit --write-anchor record the current head as the tail-deletion baseline
1213
+ advisers audit --expect-count <N> [--expect-head <64 hex>] explicit head check
1214
+ advisers audit --rebuild-fts rebuild the FTS5 indexes (the repair the reader warning names)
1052
1215
  advisers purge <matter> [--yes] privacy delete a matter
1053
1216
  advisers commit add|edit|ls|done|snooze commitments
1054
1217
  advisers commit add "..." --quote "..." [--remind-offsets "-1d,-2h"]
@@ -1057,10 +1220,28 @@ Usage:
1057
1220
  advisers deliveries recent generated files
1058
1221
  advisers receipt one-screen delivery receipt
1059
1222
  advisers ls list matters (alias of matter ls)
1060
- advisers matter add <title> [--secrecy 0-3] [--domain d] [--summary s] [--json]
1061
- advisers matter ls [--all] [--json]
1223
+ advisers matter add <title> [--secrecy 0-3] [--domain d] [--summary s]
1224
+ [--client <id> [--project <id>]] [--json]
1225
+ advisers matter ls [--all] [--client <id>] [--project <id>] [--unclassified] [--json]
1062
1226
  advisers matter show|rename|archive|use <id> ...
1063
1227
  create/inspect/rename/archive a matter; 'use' sets the write default
1228
+ advisers client add "<name>" [--aliases a,b] [--tags t1,t2] [--secrecy 0-3]
1229
+ [--note text] [--link-matter <id>] [--json]
1230
+ advisers client list [--all] [--limit n] [--json]
1231
+ advisers client show <id> [--timeline-limit n] [--clearance 0-3] [--json]
1232
+ advisers client timeline <id> [--since 90d|ISO] [--kind delivery,note,commitment]
1233
+ [--limit n] [--clearance 0-3] [--json]
1234
+ advisers client archive <id> [--dry-run] [--json]
1235
+ advisers client merge <from> <into> [--dry-run] [--json]
1236
+ advisers client note add <id> "<summary>" [--kind k] [--at ISO] [--project id] [--matter id] [--json]
1237
+ advisers client note list <id> [--project id] [--limit n] [--json]
1238
+ advisers project add <client-id> "<name>" [--start YYYY-MM-DD] [--end YYYY-MM-DD]
1239
+ [--default-matter <id>] [--note text] [--json]
1240
+ advisers project list [--client <id>] [--all] [--limit n] [--json]
1241
+ advisers project show <id> [--timeline-limit n] [--clearance 0-3] [--json]
1242
+ advisers project archive <id> [--dry-run] [--json]
1243
+ customer/project entities + derived timeline (SQLite store;
1244
+ see docs/CLIENTS.md)
1064
1245
  advisers privacy [--json] [--prove] show/verify local data & egress facts
1065
1246
  advisers why <pref-id> explain a preference
1066
1247
  advisers forget <pref-id> forget a preference (tombstone)
@@ -1068,7 +1249,14 @@ Usage:
1068
1249
  advisers import <file> [--replace] import an export (encrypted or plain)
1069
1250
  advisers vault seal [--out f] [--remove] | unseal [f] | status AES-256-GCM database vault
1070
1251
  advisers sync push|pull|status --dir <dir> file-based E2EE snapshot sync (user-provided dir)
1071
- advisers backup <path.db> checkpoint and copy the SQLite database
1252
+ advisers backup [<path.db>|--out f] [--tag name] [--keep daily=7,weekly=4,monthly=3] [--dry-run|--apply] [--json]
1253
+ verify+checkpoint the database and copy it: an explicit path is a
1254
+ plain copy; no path writes a managed backup + .sha256/.anchor.json
1255
+ under <home>/backups. --keep plans GFS rotation (dry-run unless --apply)
1256
+ advisers backups ls|verify [--json] [--limit n] list / re-verify managed backups
1257
+ advisers restore <backup> [--dry-run] [--yes] [--allow-anchor-behind] [--json]
1258
+ plan by default; --yes writes a pre-restore backup, installs the
1259
+ verified backup, rolls back on failure, audits db.restore, reopens
1072
1260
  advisers brief [--deep] <text> print the IntentBrief; --deep adds model refinement
1073
1261
  advisers --version print the CLI version
1074
1262
  advisers who who I owe / who owes me
@@ -1092,7 +1280,9 @@ Usage:
1092
1280
  advisers office-read <file> read DOCX/XLSX/PPTX/OFD text
1093
1281
  advisers ocr <image> [--out text] local OCR adapter (ADVISERS_OCR_CMD; no cloud)
1094
1282
  advisers timestamp <file> [--out proof] local timestamp/signing adapter
1095
- advisers tui [--once] read-only terminal dashboard
1283
+ advisers tui [--once] [--json] [--width n]
1284
+ read-only terminal dashboard; non-TTY/--plain/--accessible
1285
+ print one plain snapshot (never clear the screen); --json is pure JSON
1096
1286
  advisers office-edit <file> <ops.json> [out] surgical Office edit
1097
1287
  advisers verify <file> [--json] [--content] structural + deterministic content checks
1098
1288
  advisers office <kind> <spec.json> <out>
@@ -1144,7 +1334,11 @@ Environment:
1144
1334
  ADVISERS_FORCE=1 overwrite existing files without asking
1145
1335
  ADVISERS_ALLOW_PATHS explicit path-list (OS path separator) widening the
1146
1336
  agent file-tool boundary, same as repeated --allow-path
1147
- ADVISERS_PROGRESS=0 hide [tool] progress lines
1337
+ ADVISERS_PROGRESS=1 show internal [tool]/[attach]/[compact] process lines
1338
+ (default hidden; /debug in the REPL also enables them)
1339
+ --plain / --accessible / --color auto|always|never
1340
+ global output policy for every human-output command; NO_COLOR
1341
+ and TERM=dumb are honoured (see docs/TUI.md)
1148
1342
  ADVISERS_ACCEPT_TOS=1 record TOS consent without a TTY (same as --accept-tos)
1149
1343
  ADVISERS_NOTIFY_WEBHOOK optional outbound webhook for remind --deliver --notify
1150
1344
  ADVISERS_LOCK_TIMEOUT_MS wait for another advisers process to release the
@@ -1236,7 +1430,8 @@ function purgeMatter(id, confirmed) {
1236
1430
  const commitments = ledger.openCommitments(id).length
1237
1431
  console.log(`matter ${id}: ${matter.title}`)
1238
1432
  console.log(`facts=${facts} links=${links} updates=${updates} open_commitments=${commitments}`)
1239
- if (!confirmed) { console.log('dry-run only; re-run with --yes to purge'); return }
1433
+ if (!confirmed) { console.log('后果:加 --yes 后不可撤销;先运行 advisers backup 可保留可恢复副本。'); console.log('dry-run only; re-run with --yes to purge'); return }
1434
+ console.log('! 需要确认:删除事项 ' + sanitizeConsoleText(id, { max: 200 }) + ' 的本地数据(--yes,不可撤销);已保留审计行,不会删除备份文件')
1240
1435
  const counts = ledger.purgeMatter(id)
1241
1436
  saveJson(ledger)
1242
1437
  console.log(`purged: ${JSON.stringify(counts)} sqlite={}`)
@@ -1259,10 +1454,17 @@ function purgeMatter(id, confirmed) {
1259
1454
  if (!matter) { console.error(`unknown matter: ${id}`); process.exitCode = 1; return }
1260
1455
  console.log(`matter ${id}: ${matter.title}`)
1261
1456
  console.log(`facts=${facts} links=${links} updates=${updates} open_commitments=${commitments}`)
1457
+ console.log('后果:--yes 后不可撤销;先运行 advisers backup 可保留可恢复副本。')
1262
1458
  console.log('dry-run only; re-run with --yes to purge')
1263
1459
  } catch (error) { reportCommandFailure(error) }
1264
1460
  return
1265
1461
  }
1462
+ // 0.3.0 Wave 3 (plan 26 §4.5): --yes is the confirmation; state the
1463
+ // irreversible consequence before the transaction (tombstones + VACUUM).
1464
+ console.log('! 需要确认:删除事项 ' + sanitizeConsoleText(id, { max: 200 }) + ' 的本地数据(--yes,不可撤销)')
1465
+ console.log(' 删除:事实/承诺/偏好/路由/链接标记(状态改为 [purged])')
1466
+ console.log(' 已保留:本地审计行(记录本次 purge);不会删除备份文件')
1467
+ console.log(' 如需可恢复副本,请先运行:advisers backup')
1266
1468
  const audit = { actor: 'local', action: 'matter.purge', allowed: true, reason: '' }
1267
1469
  try {
1268
1470
  const { result } = mutateWithAudit((store) => {
@@ -1329,6 +1531,96 @@ function parseFlags(args) {
1329
1531
  return { flags, positional }
1330
1532
  }
1331
1533
 
1534
+ /* ---------------------------------------------------------------------------
1535
+ * 0.3.0 Wave 2: strict option parsing for the operational commands.
1536
+ *
1537
+ * Before this, unknown flags were silently ignored, so `doctor --repair` and
1538
+ * `audit --rebuild-fts` (both not implemented in 0.2.4) exited 0 without doing
1539
+ * anything, and a typo like `--yse` looked like success (P0-D1). The commands
1540
+ * extended below parse an explicit allowlist and fail closed with E_USAGE.
1541
+ * parseFlags() above keeps its historical lenient behaviour for the older
1542
+ * commands; do not use it for new options.
1543
+ * ------------------------------------------------------------------------- */
1544
+
1545
+ /**
1546
+ * Parse `--flag`, `--flag=value` and `--flag value` against an allowlist.
1547
+ * @returns {{ok: true, flags: object, positional: string[]} | {ok: false, error: string}}
1548
+ */
1549
+ function parseStrictFlags(args, { booleans = [], values = [], positional = true } = {}) {
1550
+ const flags = {}
1551
+ const rest = []
1552
+ const booleanSet = new Set(booleans)
1553
+ const valueSet = new Set(values)
1554
+ for (let index = 0; index < args.length; index++) {
1555
+ const arg = args[index]
1556
+ if (arg === '--') { rest.push(...args.slice(index + 1)); break }
1557
+ if (typeof arg !== 'string' || !arg.startsWith('--')) { rest.push(arg); continue }
1558
+ const eq = arg.indexOf('=')
1559
+ const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq)
1560
+ const inline = eq === -1 ? undefined : arg.slice(eq + 1)
1561
+ if (booleanSet.has(name)) {
1562
+ if (inline !== undefined) return { ok: false, error: `--${name} does not take a value` }
1563
+ flags[name] = true
1564
+ continue
1565
+ }
1566
+ if (valueSet.has(name)) {
1567
+ if (inline !== undefined) { flags[name] = inline; continue }
1568
+ const next = args[index + 1]
1569
+ if (next === undefined || (typeof next === 'string' && next.startsWith('--'))) {
1570
+ return { ok: false, error: `--${name} requires a value` }
1571
+ }
1572
+ flags[name] = next
1573
+ index++
1574
+ continue
1575
+ }
1576
+ return { ok: false, error: `unknown option ${arg}` }
1577
+ }
1578
+ if (!positional && rest.length) return { ok: false, error: `unexpected argument ${rest[0]}` }
1579
+ return { ok: true, flags, positional: rest }
1580
+ }
1581
+
1582
+ /** Print one usage error (E_USAGE) and mark the command failed; never throws. */
1583
+ function usageFail(message, usage = '') {
1584
+ console.error(`advisers: E_USAGE: ${message}${usage ? '\n' + usage : ''}`)
1585
+ process.exitCode = 1
1586
+ }
1587
+
1588
+ /** 12-hex audit/command hash prefix for human output (full hash in --json). */
1589
+ function shortAuditHash(hash) {
1590
+ return typeof hash === 'string' && hash ? hash.slice(0, 12) : '(none)'
1591
+ }
1592
+
1593
+ /** Human byte size for backup listings (1024-based, one decimal). */
1594
+ function formatBytes(bytes) {
1595
+ const value = Number(bytes)
1596
+ if (!Number.isFinite(value) || value < 0) return '?'
1597
+ if (value < 1024) return value + ' B'
1598
+ const units = ['KiB', 'MiB', 'GiB', 'TiB']
1599
+ let size = value / 1024
1600
+ let unit = 0
1601
+ while (size >= 1024 && unit < units.length - 1) { size /= 1024; unit++ }
1602
+ return (Math.round(size * 10) / 10) + ' ' + units[unit]
1603
+ }
1604
+
1605
+ /** Report a store maintenance failure (writable open / lock) consistently. */
1606
+ function reportMaintenanceFailure(error, asJson, label) {
1607
+ const code = error?.code ?? null
1608
+ const hint = storeFailureHint(error)
1609
+ if (asJson) {
1610
+ console.log(JSON.stringify({ ok: false, label, code, error: String(error?.message ?? error), hint: hint ?? undefined }, null, 2))
1611
+ } else {
1612
+ console.error(`${label}: FAILED${code ? ' (' + code + ')' : ''}: ${error?.message ?? error}`)
1613
+ if (hint) console.error(hint)
1614
+ }
1615
+ process.exitCode = 1
1616
+ }
1617
+
1618
+ const AUDIT_USAGE = 'usage: advisers audit [--check-db] [--json]\n advisers audit --write-anchor [--json]\n advisers audit --expect-count <N> [--expect-head <64 hex>] [--json]\n advisers audit --rebuild-fts [--json]'
1619
+ const DOCTOR_USAGE = 'usage: advisers doctor [--check-db] [--json]\n advisers doctor --repair [--dry-run|--yes] [--only lock,temp,wal,fts] [--json]'
1620
+ const BACKUP_USAGE = 'usage: advisers backup [--out <file> | <path.db>] [--tag <name>] [--keep daily=7,weekly=4,monthly=3] [--dry-run|--apply] [--json]\n advisers backup <path.db> explicit copy, never rotated'
1621
+ const BACKUPS_USAGE = 'usage: advisers backups ls [--json] [--limit <n>]\n advisers backups verify [--json] [--limit <n>]'
1622
+ const RESTORE_USAGE = 'usage: advisers restore <backup-file> [--dry-run] [--yes] [--allow-anchor-behind] [--allow-broken-audit-chain] [--json]'
1623
+
1332
1624
  /**
1333
1625
  * Read --remind / --remind-offsets from parsed flags and strictly normalise.
1334
1626
  * `--remind -1d` is a one-offset alias of `--remind-offsets "-1d,-2h"`.
@@ -1531,23 +1823,74 @@ function printMemory(ledger) {
1531
1823
  console.log('输入 /why <pref-id> 看依据;/forget <pref-id> 删除;/audit 看审计。')
1532
1824
  }
1533
1825
 
1534
- function printWeek(ledger) {
1535
- const now = Date.now()
1536
- const weekAgo = now - 7 * 86400_000
1826
+ /**
1827
+ * `week` window: the last 7 local days ending today (Asia/Shanghai), inclusive.
1828
+ * The old implementation used `due >= weekAgo || due < now`, so any overdue
1829
+ * commitment ever (e.g. a 2026-10-01 item) counted as "this week's due"; the
1830
+ * local-day window is the 0.3.0 fix (13-mail-calendar C8 / U2) and is the same
1831
+ * window the --json contract publishes.
1832
+ */
1833
+ function weekWindow(nowMs) {
1834
+ const to = localDayOf(nowMs)
1835
+ const from = localDayOf(nowMs - 6 * 86400_000)
1836
+ return { from, to, days: 7, timezone: 'Asia/Shanghai' }
1837
+ }
1838
+
1839
+ function weekReport(ledger, nowMs = Date.now()) {
1840
+ const window = weekWindow(nowMs)
1537
1841
  const commitments = ledger.listCommitments()
1538
- const due = commitments.filter((c) => c.dueAt && (Date.parse(c.dueAt) >= weekAgo || Date.parse(c.dueAt) < now))
1539
- const done = due.filter((c) => c.status === 'done')
1842
+ const itemRows = []
1843
+ for (const c of commitments) {
1844
+ if (!c.dueAt) continue
1845
+ const ms = Date.parse(c.dueAt)
1846
+ if (Number.isNaN(ms)) continue
1847
+ const day = localDayOf(ms)
1848
+ if (day < window.from || day > window.to) continue
1849
+ itemRows.push({ commitment: c, ms })
1850
+ }
1851
+ itemRows.sort((a, b) => (a.ms === b.ms ? (String(a.commitment.id) < String(b.commitment.id) ? -1 : 1) : a.ms - b.ms))
1852
+ const dueRows = itemRows.map((row) => row.commitment)
1853
+ const done = dueRows.filter((c) => c.status === 'done')
1540
1854
  const open = commitments.filter((c) => c.status === 'open')
1541
- const overdue = open.filter((c) => c.dueAt && Date.parse(c.dueAt) < now)
1855
+ const overdue = open.filter((c) => c.dueAt && !Number.isNaN(Date.parse(c.dueAt)) && Date.parse(c.dueAt) < nowMs)
1542
1856
  let deliveries = []
1543
1857
  try { deliveries = readStoreOrExit()?.listDeliveries(100) ?? [] } catch {}
1544
- const weekDeliveries = deliveries.filter((d) => Date.parse(d.createdAt) >= weekAgo)
1545
- console.log(`本周(${new Date(weekAgo).toISOString().slice(0, 10)} – ${new Date(now).toISOString().slice(0, 10)})`)
1546
- console.log(`承诺:到期 ${due.length} 件,完成 ${done.length} 件,未完成 ${open.length} 件,逾期 ${overdue.length} 件。`)
1547
- for (const c of due.slice(0, 5)) console.log(` ${c.status === 'done' ? '✓' : '○'} ${c.action}${c.dueAt ? `(${c.dueAt.slice(0, 10)})` : ''}`)
1548
- console.log(`交付:${weekDeliveries.length} 个文件。`)
1549
- const next = [...open].filter((c) => c.dueAt).sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt))[0]
1550
- console.log('下周一件:' + (next?.action ?? open[0]?.action ?? '先定一个承诺或交付。'))
1858
+ const weekDeliveries = deliveries.filter((d) => {
1859
+ const ms = Date.parse(d.createdAt)
1860
+ if (Number.isNaN(ms)) return false
1861
+ const day = localDayOf(ms)
1862
+ return day >= window.from && day <= window.to
1863
+ })
1864
+ const datedOpen = [...open].filter((c) => c.dueAt && !Number.isNaN(Date.parse(c.dueAt)))
1865
+ datedOpen.sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt))
1866
+ const next = datedOpen.find((c) => localDayOf(Date.parse(c.dueAt)) > window.to) ?? datedOpen[0]
1867
+ return { window, dueRows, done, open, overdue, weekDeliveries, next }
1868
+ }
1869
+
1870
+ function printWeek(ledger, asJson = false) {
1871
+ const report = weekReport(ledger)
1872
+ if (asJson) {
1873
+ // 0.3.0 JSON contract (03-design-product-0.3 §5.6.3): window + counts +
1874
+ // deterministic items. Previously `week --json` printed Chinese human text
1875
+ // because the dispatch keyed off the *store* mode instead of the --json flag.
1876
+ console.log(JSON.stringify({
1877
+ ok: true,
1878
+ command: 'week',
1879
+ window: report.window,
1880
+ due: report.dueRows.length,
1881
+ done: report.done.length,
1882
+ overdue: report.overdue.length,
1883
+ deliveries: report.weekDeliveries.length,
1884
+ items: report.dueRows.map((c) => ({ id: c.id, status: c.status, due: c.dueAt ?? null, action: c.action })),
1885
+ next: report.next ? { id: report.next.id, action: report.next.action, dueAt: report.next.dueAt ?? null } : null,
1886
+ }, null, 2))
1887
+ return
1888
+ }
1889
+ console.log('本周(' + report.window.from + ' – ' + report.window.to + ')')
1890
+ console.log('承诺:到期 ' + report.dueRows.length + ' 件,完成 ' + report.done.length + ' 件,未完成 ' + report.open.length + ' 件,逾期 ' + report.overdue.length + ' 件。')
1891
+ for (const c of report.dueRows.slice(0, 5)) console.log(' ' + (c.status === 'done' ? '✓' : '○') + ' ' + sanitizeConsoleText(c.action, { max: 2000 }) + (c.dueAt ? '(' + c.dueAt.slice(0, 10) + ')' : ''))
1892
+ console.log('交付:' + report.weekDeliveries.length + ' 个文件。')
1893
+ console.log('下周一件:' + sanitizeConsoleText(report.next?.action ?? report.open[0]?.action ?? '先定一个承诺或交付。', { max: 2000 }))
1551
1894
  }
1552
1895
 
1553
1896
  // ---------------------------------------------------------------------------
@@ -1581,8 +1924,11 @@ function matterJsonRow(matter, openByMatter) {
1581
1924
  status: matter.status,
1582
1925
  domain: matter.domain ?? 'general',
1583
1926
  secrecy: Number(matter.secrecy ?? 0),
1584
- clientId: null,
1585
- projectId: null,
1927
+ // v21 (0.3.0): real ownership. Pre-v21 matters stay null (unclassified) and
1928
+ // are visible through `matter ls` / `--unclassified` — the CLI never
1929
+ // invents a client for an unlinked matter.
1930
+ clientId: matter.clientId ?? null,
1931
+ projectId: matter.projectId ?? null,
1586
1932
  openCommitments: open.length,
1587
1933
  nextDueAt: matterNextDueAt(open),
1588
1934
  }
@@ -1605,6 +1951,19 @@ async function matterCommand(args) {
1605
1951
  }
1606
1952
  const domain = typeof flags.domain === 'string' ? flags.domain : 'general'
1607
1953
  const summary = typeof flags.summary === 'string' ? flags.summary : undefined
1954
+ // 0.3.0 v21 ownership: --client [--project] links the new matter through the
1955
+ // store (the only writer of matters.client_id/project_id), so an unknown or
1956
+ // archived entity fails closed instead of writing a dangling owner.
1957
+ const clientId = typeof flags.client === 'string' ? flags.client.trim() : undefined
1958
+ const projectId = typeof flags.project === 'string' ? flags.project.trim() : undefined
1959
+ if ((clientId || projectId) && mode !== 'sqlite') {
1960
+ fail('E_STORE', '客户/项目归属需要 SQLite 账本(ADVISERS_STORE=sqlite)', 'advisers client add "<name>"')
1961
+ return
1962
+ }
1963
+ if (projectId && !clientId) {
1964
+ fail('E_USAGE', '--project requires --client (a project belongs to exactly one client)', 'advisers project list --client <id>')
1965
+ return
1966
+ }
1608
1967
  if (mode === 'json') {
1609
1968
  const ledger = loadJson()
1610
1969
  const matter = ledger.addMatter({ title: title, domain: domain, secrecy: secrecy, summary: summary })
@@ -1623,8 +1982,10 @@ async function matterCommand(args) {
1623
1982
  participants: [], deadlines: [], openQuestions: [], createdAt: timestamp, updatedAt: timestamp,
1624
1983
  }
1625
1984
  store.insertMatter(row)
1626
- audit.reason = row.id
1627
- return row
1985
+ if (!clientId) { audit.reason = row.id; return row }
1986
+ const linked = store.setMatterClient(row.id, { clientId: clientId, ...(projectId ? { projectId: projectId } : {}) })
1987
+ audit.reason = row.id + ';client=' + clientId + (projectId ? ';project=' + projectId : '')
1988
+ return linked
1628
1989
  }, audit)
1629
1990
  const matter = made.result
1630
1991
  if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter add', matter: matter }, null, 2)); return }
@@ -1644,7 +2005,26 @@ async function matterCommand(args) {
1644
2005
  list.push(commitment)
1645
2006
  openByMatter.set(commitment.matterId, list)
1646
2007
  }
1647
- const rows = matters.map((matter) => matterJsonRow(matter, openByMatter))
2008
+ // 0.3.0 v21 ownership filters. An unknown --client/--project fails closed
2009
+ // (an empty list would look like "no matters" and hide a typo). With no
2010
+ // filter the default list includes unclassified matters, so incompletely
2011
+ // linked work stays visible instead of disappearing behind the entity view.
2012
+ const clientFilter = typeof flags.client === 'string' ? flags.client.trim() : undefined
2013
+ const projectFilter = typeof flags.project === 'string' ? flags.project.trim() : undefined
2014
+ const onlyUnclassified = flags.unclassified === true
2015
+ if ((clientFilter || projectFilter) && mode === 'sqlite') {
2016
+ const store = readStoreOrExit()
2017
+ if (clientFilter && !store?.getClient(clientFilter)) { fail('E_CLIENT_NOT_FOUND', 'unknown client: ' + clientFilter, 'advisers client list'); return }
2018
+ if (projectFilter && !store?.getProject(projectFilter)) { fail('E_PROJECT_NOT_FOUND', 'unknown project: ' + projectFilter, 'advisers project list'); return }
2019
+ }
2020
+ const rows = matters
2021
+ .map((matter) => matterJsonRow(matter, openByMatter))
2022
+ .filter((row) => {
2023
+ if (clientFilter && row.clientId !== clientFilter) return false
2024
+ if (projectFilter && row.projectId !== projectFilter) return false
2025
+ if (onlyUnclassified && row.clientId !== null) return false
2026
+ return true
2027
+ })
1648
2028
  rows.sort((a, b) => (a.status === b.status ? (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) : (a.status < b.status ? -1 : 1)))
1649
2029
  if (asJson) { console.log(JSON.stringify(rows, null, 2)); return }
1650
2030
  if (!rows.length) { console.log('(没有事项)'); return }
@@ -1661,10 +2041,17 @@ async function matterCommand(args) {
1661
2041
  if (!matter) { fail('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls'); return }
1662
2042
  const commitments = ledger.listCommitments().filter((commitment) => commitment.matterId === id)
1663
2043
  const open = commitments.filter((commitment) => commitment.status === 'open')
2044
+ // 0.3.0: the raw matter row already carries clientId/projectId (v21); the
2045
+ // resolved names are additive display fields, never a second source of truth.
2046
+ const entityStore = mode === 'sqlite' ? readStoreOrExit() : null
2047
+ const linkedClient = matter.clientId && entityStore ? entityStore.getClient(matter.clientId) : undefined
2048
+ const linkedProject = matter.projectId && entityStore ? entityStore.getProject(matter.projectId) : undefined
1664
2049
  const payload = {
1665
2050
  ok: true,
1666
2051
  command: 'matter show',
1667
2052
  matter: matter,
2053
+ client: linkedClient ? { id: linkedClient.id, name: linkedClient.name, status: linkedClient.status } : null,
2054
+ project: linkedProject ? { id: linkedProject.id, name: linkedProject.name, status: linkedProject.status, clientId: linkedProject.clientId } : null,
1668
2055
  counts: { commitments: commitments.length, open: open.length, done: commitments.filter((c) => c.status === 'done').length },
1669
2056
  open: open.map((c) => ({ id: c.id, action: c.action, dueAt: c.dueAt ?? null, debtor: c.debtor, creditor: c.creditor })),
1670
2057
  nextDueAt: matterNextDueAt(open),
@@ -1672,6 +2059,7 @@ async function matterCommand(args) {
1672
2059
  if (asJson) { console.log(JSON.stringify(payload, null, 2)); return }
1673
2060
  console.log(matter.id + ' ' + matter.title)
1674
2061
  console.log('状态 ' + matter.status + ' · 保密 ' + Number(matter.secrecy ?? 0) + ' · 领域 ' + (matter.domain ?? 'general'))
2062
+ if (payload.client) console.log('客户 ' + payload.client.name + ' (' + payload.client.id + ')' + (payload.project ? ' · 项目 ' + payload.project.name + ' (' + payload.project.id + ')' : ''))
1675
2063
  if (matter.summary) console.log('摘要:' + matter.summary)
1676
2064
  console.log('未完成承诺 ' + open.length + ' · 总承诺 ' + commitments.length + ' · 下一截止 ' + (payload.nextDueAt ?? '无'))
1677
2065
  for (const c of open.slice(0, 20)) console.log(' ' + c.id + ' ' + c.action + (c.dueAt ? ' · ' + c.dueAt : ''))
@@ -1777,8 +2165,8 @@ async function matterCommand(args) {
1777
2165
  }
1778
2166
  if (!sub || sub === 'help' || sub === '--help') {
1779
2167
  console.log('usage: advisers matter <add|ls|show|rename|archive|use> ...')
1780
- console.log(' advisers matter add <title> [--secrecy 0-3] [--domain name] [--summary text] [--json]')
1781
- console.log(' advisers matter ls [--all] [--json]')
2168
+ console.log(' advisers matter add <title> [--secrecy 0-3] [--domain name] [--summary text] [--client id [--project id]] [--json]')
2169
+ console.log(' advisers matter ls [--all] [--client id] [--project id] [--unclassified] [--json]')
1782
2170
  console.log(' advisers matter show <id> [--json]')
1783
2171
  console.log(' advisers matter rename <id> <title> [--json]')
1784
2172
  console.log(' advisers matter archive <id> [--dry-run] [--json]')
@@ -1788,6 +2176,1057 @@ async function matterCommand(args) {
1788
2176
  fail('E_USAGE', 'unknown matter subcommand: ' + sub, 'advisers matter help')
1789
2177
  }
1790
2178
 
2179
+ /* ---------------------------------------------------------------------------
2180
+ * 0.3.0 customer entities: client / project commands + derived views.
2181
+ *
2182
+ * clients/projects/client_notes are SQLite-only rows (schema v21): they never
2183
+ * enter the wire LedgerSnapshot, so every command here is a thin adapter over
2184
+ * SqliteStore. Writes are one directed statement in a single mutate()
2185
+ * transaction with exactly one audit row (ids/counts only -- never names, notes,
2186
+ * titles or paths); reads run in one lock-free snapshot and every query is
2187
+ * scoped by the client/project's own matter ids (no full-table read followed by
2188
+ * an in-memory filter, so two clients can never see each other's rows).
2189
+ *
2190
+ * The customer timeline is DERIVED (packages/core/src/customer.ts); there is no
2191
+ * event table and no stored counter. --clearance N is an opt-in per-item
2192
+ * secrecy gate: a matter whose effective secrecy max(client.secrecyDefault,
2193
+ * matter.secrecy) is above N is withheld with its rows and only a COUNT is
2194
+ * reported (never an id/title/name). The local CLI default is 3 (the user's own
2195
+ * data is visible); pass --clearance 0 to build output safe to hand to someone
2196
+ * else. Unclassified (pre-v21) matters stay visible in matter ls: no ownership
2197
+ * is ever invented for them.
2198
+ * ------------------------------------------------------------------------- */
2199
+ const CUSTOMER_SOURCE_LIMIT = 200
2200
+ const CUSTOMER_TIMELINE_DEFAULT = 20
2201
+ const CUSTOMER_TIMELINE_MAX = 200
2202
+ const CUSTOMER_DEFAULT_CLEARANCE = 3
2203
+ const CUSTOMER_DEFAULT_LIMIT = 100
2204
+ const CUSTOMER_MAX_LIMIT = 1000
2205
+
2206
+ const CUSTOMER_USAGE = {
2207
+ add: 'usage: advisers client add "<name>" [--aliases a,b] [--tags t1,t2] [--secrecy 0-3] [--note text] [--link-matter <id>] [--json]',
2208
+ list: 'usage: advisers client list [--all] [--limit n] [--json]',
2209
+ show: 'usage: advisers client show <id> [--timeline-limit n] [--clearance 0-3] [--json]',
2210
+ timeline: 'usage: advisers client timeline <id> [--since 90d|ISO] [--kind delivery,note,commitment] [--limit n] [--clearance 0-3] [--json]',
2211
+ archive: 'usage: advisers client archive <id> [--dry-run] [--json]',
2212
+ merge: 'usage: advisers client merge <from-id> <into-id> [--dry-run] [--json]',
2213
+ note: 'usage: advisers client note add <id> "<summary>" [--kind note|call|meeting|decision|email-summary] [--at ISO] [--project <id>] [--matter <id>] [--json]',
2214
+ noteList: 'usage: advisers client note list <id> [--project <id>] [--limit n] [--json]',
2215
+ projectAdd: 'usage: advisers project add <client-id> "<name>" [--start YYYY-MM-DD] [--end YYYY-MM-DD] [--default-matter <id>] [--note text] [--json]',
2216
+ projectList: 'usage: advisers project list [--client <id>] [--all] [--limit n] [--json]',
2217
+ projectShow: 'usage: advisers project show <id> [--timeline-limit n] [--clearance 0-3] [--json]',
2218
+ projectArchive: 'usage: advisers project archive <id> [--dry-run] [--json]',
2219
+ }
2220
+
2221
+ /** An application error with a stable E_* code and optional actionable hint. */
2222
+ function customerError(code, message, hint) {
2223
+ const error = new Error(code + ': ' + message)
2224
+ error.code = code
2225
+ if (hint) error.hint = hint
2226
+ return error
2227
+ }
2228
+
2229
+ /** Machine-readable failure on stderr; stdout stays a clean JSON document. */
2230
+ function customerFail(code, message, hint) {
2231
+ const payload = { error: { code: code, message: message } }
2232
+ if (hint) payload.error.hint = hint
2233
+ console.error(JSON.stringify(payload))
2234
+ process.exitCode = 1
2235
+ }
2236
+
2237
+ /** Report a customer-command failure (store failures keep their documented hints). */
2238
+ function reportCustomerFailure(error) {
2239
+ if (isStoreWriteFailure(error)) { exitStoreWriteFailure(error); return }
2240
+ const code = typeof error?.code === 'string' ? error.code : 'E_UNKNOWN'
2241
+ let message = String(error?.message ?? error)
2242
+ if (message.startsWith(code + ': ')) message = message.slice(code.length + 2)
2243
+ const hintMarker = message.lastIndexOf(' (hint: ')
2244
+ if (hintMarker !== -1 && message.endsWith(')')) message = message.slice(0, hintMarker)
2245
+ customerFail(code, message, typeof error?.hint === 'string' ? error.hint : undefined)
2246
+ }
2247
+
2248
+ /** Customer entities are SQLite-only; the legacy JSON store has no tables. */
2249
+ function customerStoreOrFail() {
2250
+ if (mode === 'sqlite') return true
2251
+ customerFail('E_STORE', '客户/项目实体只存在于 SQLite 账本(ADVISERS_STORE=sqlite);JSON store 没有这些表。', 'advisers init')
2252
+ return false
2253
+ }
2254
+
2255
+ /** Parse one --flag as an integer inside [min,max]; undefined -> fallback. */
2256
+ function customerIntegerFlag(value, name, min, max, fallback, usage) {
2257
+ if (value === undefined) return fallback
2258
+ if (typeof value !== 'string' || !/^(?:0|[1-9][0-9]*)$/.test(value)) {
2259
+ throw customerError('E_USAGE', '--' + name + ' must be an integer ' + min + '..' + max, usage)
2260
+ }
2261
+ const number = Number(value)
2262
+ if (!Number.isFinite(number) || number < min || number > max) {
2263
+ throw customerError('E_USAGE', '--' + name + ' must be an integer ' + min + '..' + max, usage)
2264
+ }
2265
+ return number
2266
+ }
2267
+
2268
+ /** Parse a comma-separated list flag (undefined stays undefined). */
2269
+ function customerCommaList(value, name, usage) {
2270
+ if (value === undefined) return undefined
2271
+ if (typeof value !== 'string') throw customerError('E_USAGE', '--' + name + ' requires a comma-separated value', usage)
2272
+ const list = value.split(',').map((item) => item.trim()).filter(Boolean)
2273
+ if (!list.length) throw customerError('E_USAGE', '--' + name + ' requires at least one value', usage)
2274
+ return list
2275
+ }
2276
+
2277
+ /** Strict subcommand flag parsing: unknown options fail closed with E_USAGE. */
2278
+ function customerFlags(args, spec, usage) {
2279
+ const parsed = parseStrictFlags(args, spec)
2280
+ if (!parsed.ok) throw customerError('E_USAGE', parsed.error, usage)
2281
+ return parsed
2282
+ }
2283
+
2284
+ /** Required positional id (trimmed); E_USAGE when missing. */
2285
+ function customerIdArg(parts, index, name, usage) {
2286
+ const value = parts[index]
2287
+ const id = typeof value === 'string' ? value.trim() : ''
2288
+ if (!id) throw customerError('E_USAGE', name + ' is required', usage)
2289
+ return id
2290
+ }
2291
+
2292
+ /** Effective secrecy of a matter for one client: max(default, matter level). */
2293
+ function effectiveMatterSecrecy(client, matter) {
2294
+ const clientLevel = Number(client?.secrecyDefault ?? 0)
2295
+ const matterLevel = matter?.secrecy === undefined || matter?.secrecy === null ? 0 : Number(matter.secrecy)
2296
+ if (!Number.isFinite(clientLevel) || !Number.isFinite(matterLevel)) return Number.POSITIVE_INFINITY
2297
+ return Math.max(clientLevel, matterLevel)
2298
+ }
2299
+
2300
+ function customerSqlIn(ids) {
2301
+ return ids.map(() => '?').join(',')
2302
+ }
2303
+
2304
+ function customerCountRows(store, table, matterIds) {
2305
+ if (!matterIds.length) return 0
2306
+ const row = store.db.prepare('SELECT COUNT(*) AS n FROM ' + table + ' WHERE matter_id IN (' + customerSqlIn(matterIds) + ')').get(...matterIds)
2307
+ return Number(row?.n ?? 0)
2308
+ }
2309
+
2310
+ function customerNextDueAt(openRows) {
2311
+ let next = null
2312
+ for (const row of openRows) {
2313
+ const ms = dueInstantOfValue(row.due_at ?? row.dueAt)
2314
+ if (ms !== null && (next === null || ms < next)) next = ms
2315
+ }
2316
+ return next === null ? null : toShanghaiIso(next)
2317
+ }
2318
+
2319
+ /** mine = we owe the client; waiting = the client owes us (debtor third:*). */
2320
+ function customerSplitOpen(openRows, matterById) {
2321
+ const rows = openRows.map((row) => ({
2322
+ id: row.id,
2323
+ action: row.action,
2324
+ debtor: row.debtor,
2325
+ creditor: row.creditor,
2326
+ status: 'open',
2327
+ ...(row.matter_id === null || row.matter_id === undefined ? {} : { matterId: row.matter_id }),
2328
+ ...(row.due_at === null || row.due_at === undefined ? {} : { dueAt: row.due_at }),
2329
+ }))
2330
+ const matters = [...matterById.values()].map((matter) => ({
2331
+ id: matter.id,
2332
+ ...(matter.projectId === undefined ? {} : { projectId: matter.projectId }),
2333
+ ...(matter.status === undefined ? {} : { status: matter.status }),
2334
+ ...(matter.secrecy === undefined ? {} : { secrecy: matter.secrecy }),
2335
+ }))
2336
+ return core.splitOpenCommitments(rows, matters)
2337
+ }
2338
+
2339
+ function customerOverdueCount(rows) {
2340
+ const nowMs = Date.now()
2341
+ return rows.filter((row) => {
2342
+ const ms = dueInstantOfValue(row.dueAt)
2343
+ return ms !== null && ms < nowMs
2344
+ }).length
2345
+ }
2346
+
2347
+ /** Map raw rows to the core timeline input shapes (no unmapped column leaks). */
2348
+ function customerCommitmentEvent(row) {
2349
+ return {
2350
+ id: row.id,
2351
+ matterId: row.matter_id,
2352
+ action: row.action,
2353
+ debtor: row.debtor,
2354
+ creditor: row.creditor,
2355
+ status: row.status,
2356
+ ...(row.due_at === null || row.due_at === undefined ? {} : { dueAt: row.due_at }),
2357
+ ...(row.done_at === null || row.done_at === undefined ? {} : { doneAt: row.done_at }),
2358
+ ...(row.created_at === null || row.created_at === undefined ? {} : { createdAt: row.created_at }),
2359
+ }
2360
+ }
2361
+
2362
+ function customerDeliveryEvent(row) {
2363
+ return {
2364
+ id: row.id,
2365
+ matterId: row.matter_id,
2366
+ createdAt: row.created_at,
2367
+ ...(row.title === null || row.title === undefined ? {} : { title: row.title }),
2368
+ ...(row.tool === null || row.tool === undefined ? {} : { tool: row.tool }),
2369
+ ...(row.template_name === null || row.template_name === undefined ? {} : { templateName: row.template_name }),
2370
+ }
2371
+ }
2372
+
2373
+ function customerNoteEvent(row) {
2374
+ return {
2375
+ id: row.id,
2376
+ at: row.at,
2377
+ summary: row.summary,
2378
+ ...(row.kind === undefined ? {} : { kind: row.kind }),
2379
+ ...(row.projectId === undefined ? {} : { projectId: row.projectId }),
2380
+ ...(row.matterId === undefined ? {} : { matterId: row.matterId }),
2381
+ }
2382
+ }
2383
+
2384
+ function customerNoteRow(row) {
2385
+ let source
2386
+ if (row.source) {
2387
+ try { source = JSON.parse(row.source) } catch { source = undefined }
2388
+ }
2389
+ return {
2390
+ id: row.id,
2391
+ clientId: row.client_id,
2392
+ kind: row.kind,
2393
+ at: row.at,
2394
+ summary: row.summary,
2395
+ createdAt: row.created_at,
2396
+ ...(row.project_id === null || row.project_id === undefined ? {} : { projectId: row.project_id }),
2397
+ ...(row.matter_id === null || row.matter_id === undefined ? {} : { matterId: row.matter_id }),
2398
+ ...(source === undefined ? {} : { source: source }),
2399
+ ...(row.deleted_at === null || row.deleted_at === undefined ? {} : { deletedAt: row.deleted_at }),
2400
+ }
2401
+ }
2402
+
2403
+ /** Load the matter-scoped rows a client/project view derives from (bounded). */
2404
+ function customerMatterRows(store, matterIds, limit) {
2405
+ if (!matterIds.length) return { commitments: [], deliveries: [], open: [] }
2406
+ const marks = customerSqlIn(matterIds)
2407
+ return {
2408
+ commitments: store.db.prepare(
2409
+ 'SELECT id, matter_id, action, debtor, creditor, status, due_at, done_at, created_at FROM commitments WHERE matter_id IN (' + marks + ') ORDER BY (created_at IS NULL), created_at DESC, rowid DESC LIMIT ?'
2410
+ ).all(...matterIds, limit),
2411
+ deliveries: store.db.prepare(
2412
+ 'SELECT id, matter_id, client_id, project_id, title, tool, template_name, created_at FROM deliveries WHERE matter_id IN (' + marks + ') ORDER BY created_at DESC, rowid DESC LIMIT ?'
2413
+ ).all(...matterIds, limit),
2414
+ open: store.db.prepare(
2415
+ "SELECT id, matter_id, action, debtor, creditor, due_at FROM commitments WHERE matter_id IN (" + marks + ") AND status = 'open' ORDER BY rowid"
2416
+ ).all(...matterIds),
2417
+ }
2418
+ }
2419
+
2420
+ /** One read snapshot of a client's rows (every query scoped by its own matters). */
2421
+ function readClientView(store, clientId) {
2422
+ const client = store.getClient(String(clientId))
2423
+ if (!client) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(clientId), 'advisers client list')
2424
+ const projects = store.listProjects({ clientId: client.id, status: 'all', includeDeleted: true, limit: 1000 })
2425
+ const matters = store.listMattersByClient(client.id)
2426
+ const rows = customerMatterRows(store, matters.map((matter) => matter.id), CUSTOMER_SOURCE_LIMIT)
2427
+ const notes = store.listClientNotes({ clientId: client.id, limit: CUSTOMER_SOURCE_LIMIT })
2428
+ return {
2429
+ client: client,
2430
+ projects: projects,
2431
+ matters: matters,
2432
+ matterById: new Map(matters.map((matter) => [matter.id, matter])),
2433
+ commitments: rows.commitments,
2434
+ deliveries: rows.deliveries,
2435
+ open: rows.open,
2436
+ notes: notes,
2437
+ }
2438
+ }
2439
+
2440
+ /** Notes of one project: explicit project_id OR a matter belonging to the project. */
2441
+ function customerProjectNotes(store, project, matterIds, limit) {
2442
+ let sql = 'SELECT id, client_id, project_id, matter_id, kind, at, summary, source, created_at, deleted_at FROM client_notes WHERE client_id = ? AND deleted_at IS NULL AND project_id = ?'
2443
+ const params = [project.clientId, project.id]
2444
+ if (matterIds.length) {
2445
+ sql = 'SELECT id, client_id, project_id, matter_id, kind, at, summary, source, created_at, deleted_at FROM client_notes WHERE client_id = ? AND deleted_at IS NULL AND (project_id = ? OR matter_id IN (' + customerSqlIn(matterIds) + '))'
2446
+ params.push(...matterIds)
2447
+ }
2448
+ return store.db.prepare(sql + ' ORDER BY at DESC, rowid DESC LIMIT ?').all(...params, limit).map(customerNoteRow)
2449
+ }
2450
+
2451
+ /** One read snapshot of a project's rows (matter/project scoped). */
2452
+ function readProjectView(store, projectId) {
2453
+ const project = store.getProject(String(projectId))
2454
+ if (!project) throw customerError('E_PROJECT_NOT_FOUND', 'unknown project: ' + String(projectId), 'advisers project list')
2455
+ const client = store.getClient(project.clientId)
2456
+ const matters = store.listMattersByProject(project.id)
2457
+ const matterIds = matters.map((matter) => matter.id)
2458
+ const rows = customerMatterRows(store, matterIds, CUSTOMER_SOURCE_LIMIT)
2459
+ return {
2460
+ project: project,
2461
+ client: client,
2462
+ matters: matters,
2463
+ matterById: new Map(matters.map((matter) => [matter.id, matter])),
2464
+ commitments: rows.commitments,
2465
+ deliveries: rows.deliveries,
2466
+ open: rows.open,
2467
+ notes: customerProjectNotes(store, project, matterIds, CUSTOMER_SOURCE_LIMIT),
2468
+ }
2469
+ }
2470
+
2471
+ function customerCountClientNotes(store, client, allowedSet, clearance) {
2472
+ const groups = store.db.prepare('SELECT matter_id, COUNT(*) AS n FROM client_notes WHERE client_id = ? AND deleted_at IS NULL GROUP BY matter_id').all(client.id)
2473
+ const clientLevel = Number(client?.secrecyDefault ?? 0)
2474
+ let count = 0
2475
+ for (const group of groups) {
2476
+ if (group.matter_id === null || group.matter_id === undefined) {
2477
+ if (clientLevel <= clearance) count += Number(group.n)
2478
+ } else if (allowedSet.has(group.matter_id)) {
2479
+ count += Number(group.n)
2480
+ }
2481
+ }
2482
+ return count
2483
+ }
2484
+
2485
+ function customerCountProjectNotes(store, project, allowedSet, clearance, client) {
2486
+ const ids = [...allowedSet]
2487
+ let sql = 'SELECT matter_id, COUNT(*) AS n FROM client_notes WHERE client_id = ? AND deleted_at IS NULL AND project_id = ? GROUP BY matter_id'
2488
+ let params = [project.clientId, project.id]
2489
+ if (ids.length) {
2490
+ sql = 'SELECT matter_id, COUNT(*) AS n FROM client_notes WHERE client_id = ? AND deleted_at IS NULL AND (project_id = ? OR matter_id IN (' + customerSqlIn(ids) + ')) GROUP BY matter_id'
2491
+ params = [project.clientId, project.id, ...ids]
2492
+ }
2493
+ const clientLevel = Number(client?.secrecyDefault ?? 0)
2494
+ let count = 0
2495
+ for (const group of store.db.prepare(sql).all(...params)) {
2496
+ if (group.matter_id === null || group.matter_id === undefined) {
2497
+ if (clientLevel <= clearance) count += Number(group.n)
2498
+ } else if (allowedSet.has(group.matter_id)) {
2499
+ count += Number(group.n)
2500
+ }
2501
+ }
2502
+ return count
2503
+ }
2504
+
2505
+ /**
2506
+ * Apply the opt-in clearance gate to one client/project view BEFORE counting,
2507
+ * paging or limiting: a withheld matter takes its commitments/deliveries/notes
2508
+ * with it, and only the COUNT is reported (never an id/title/name/quote).
2509
+ */
2510
+ function clearCustomerView(view, clearance) {
2511
+ const allowed = []
2512
+ const allowedIds = new Set()
2513
+ let protectedExcluded = 0
2514
+ for (const matter of view.matters) {
2515
+ if (effectiveMatterSecrecy(view.client, matter) <= clearance) {
2516
+ allowed.push(matter)
2517
+ allowedIds.add(matter.id)
2518
+ } else {
2519
+ protectedExcluded++
2520
+ }
2521
+ }
2522
+ const clientLevel = Number(view.client?.secrecyDefault ?? 0)
2523
+ const notes = view.notes.filter((note) => {
2524
+ if (note.matterId !== undefined && note.matterId !== null) return allowedIds.has(note.matterId)
2525
+ if (clientLevel <= clearance) return true
2526
+ protectedExcluded++
2527
+ return false
2528
+ })
2529
+ return {
2530
+ ...view,
2531
+ matters: allowed,
2532
+ matterById: new Map(allowed.map((matter) => [matter.id, matter])),
2533
+ allowedIds: allowedIds,
2534
+ commitments: view.commitments.filter((row) => allowedIds.has(row.matter_id)),
2535
+ deliveries: view.deliveries.filter((row) => allowedIds.has(row.matter_id)),
2536
+ open: view.open.filter((row) => allowedIds.has(row.matter_id)),
2537
+ notes: notes,
2538
+ protectedExcluded: protectedExcluded,
2539
+ }
2540
+ }
2541
+
2542
+ /** Exact counts for one filtered client view (SQL counts, not the bounded page). */
2543
+ function customerClientCounts(store, view, filtered, clearance) {
2544
+ const { mine, waiting } = customerSplitOpen(filtered.open, view.matterById)
2545
+ return {
2546
+ matters: filtered.matters.length,
2547
+ mattersArchived: filtered.matters.filter((matter) => matter.status === 'archived').length,
2548
+ deliveries: customerCountRows(store, 'deliveries', [...filtered.allowedIds]),
2549
+ notes: customerCountClientNotes(store, view.client, filtered.allowedIds, clearance),
2550
+ commitments: customerCountRows(store, 'commitments', [...filtered.allowedIds]),
2551
+ openMine: mine.length,
2552
+ openWaiting: waiting.length,
2553
+ overdue: customerOverdueCount([...mine, ...waiting]),
2554
+ }
2555
+ }
2556
+
2557
+ /** Exact counts for one filtered project view. */
2558
+ function customerProjectCounts(store, view, filtered, clearance) {
2559
+ const matters = filtered.matters
2560
+ const allowedIds = matters.map((matter) => matter.id)
2561
+ const allowedSet = new Set(allowedIds)
2562
+ const openRows = filtered.open.filter((row) => allowedSet.has(row.matter_id))
2563
+ const { mine, waiting } = customerSplitOpen(openRows, view.matterById)
2564
+ return {
2565
+ matters: matters.length,
2566
+ mattersArchived: matters.filter((matter) => matter.status === 'archived').length,
2567
+ deliveries: customerCountRows(store, 'deliveries', allowedIds),
2568
+ notes: customerCountProjectNotes(store, view.project, allowedSet, clearance, view.client),
2569
+ commitments: customerCountRows(store, 'commitments', allowedIds),
2570
+ openMine: mine.length,
2571
+ openWaiting: waiting.length,
2572
+ overdue: customerOverdueCount([...mine, ...waiting]),
2573
+ }
2574
+ }
2575
+
2576
+ /** Derive the merged timeline from the filtered snapshot (pure core function). */
2577
+ function customerTimeline(view, filtered, options = {}) {
2578
+ const clientLevel = Number(view.client?.secrecyDefault ?? 0)
2579
+ const derived = core.deriveClientTimeline({
2580
+ matters: filtered.matters.map((matter) => ({
2581
+ id: matter.id,
2582
+ status: matter.status,
2583
+ ...(matter.secrecy === undefined ? {} : { secrecy: matter.secrecy }),
2584
+ ...(matter.projectId === undefined ? {} : { projectId: matter.projectId }),
2585
+ })),
2586
+ commitments: filtered.commitments.map(customerCommitmentEvent),
2587
+ deliveries: filtered.deliveries.map(customerDeliveryEvent),
2588
+ notes: filtered.notes.map(customerNoteEvent),
2589
+ }, {
2590
+ ...(options.since === undefined ? {} : { since: options.since }),
2591
+ ...(options.kinds === undefined ? {} : { kinds: options.kinds }),
2592
+ ...(options.limit === undefined ? {} : { limit: options.limit }),
2593
+ defaultLimit: options.defaultLimit === undefined ? CUSTOMER_TIMELINE_DEFAULT : options.defaultLimit,
2594
+ maxLimit: CUSTOMER_TIMELINE_MAX,
2595
+ })
2596
+ // Effective secrecy includes the client default; a withheld row never reaches
2597
+ // this point, so the label can never understate the real protection level.
2598
+ const items = derived.items.map((item) => {
2599
+ const matter = item.matterId === undefined ? undefined : view.matterById.get(item.matterId)
2600
+ const secrecy = matter ? effectiveMatterSecrecy(view.client, matter) : clientLevel
2601
+ return { ...item, secrecy: secrecy }
2602
+ })
2603
+ return { items: items, total: derived.total, truncated: derived.truncated, degraded: derived.degraded }
2604
+ }
2605
+
2606
+ function customerOpenBuckets(view, filtered) {
2607
+ const { mine, waiting } = customerSplitOpen(filtered.open, view.matterById)
2608
+ const decorate = (row) => {
2609
+ const matter = row.matterId === undefined ? undefined : view.matterById.get(row.matterId)
2610
+ const secrecy = matter ? effectiveMatterSecrecy(view.client, matter) : Number(view.client?.secrecyDefault ?? 0)
2611
+ return { ...row, secrecy: secrecy }
2612
+ }
2613
+ return { mine: mine.map(decorate), waiting: waiting.map(decorate) }
2614
+ }
2615
+
2616
+ /** Parse --since as a relative window (90d / 24h) or an ISO timestamp. */
2617
+ function customerSince(value, usage) {
2618
+ if (value === undefined) return undefined
2619
+ if (typeof value !== 'string') throw customerError('E_USAGE', '--since requires an ISO timestamp or a relative window like 90d', usage)
2620
+ const text = value.trim()
2621
+ const relative = /^([0-9]+)([dh])$/i.exec(text)
2622
+ if (relative) {
2623
+ const amount = Number(relative[1])
2624
+ const unitMs = relative[2].toLowerCase() === 'd' ? 86400000 : 3600000
2625
+ return Date.now() - amount * unitMs
2626
+ }
2627
+ const ms = Date.parse(text)
2628
+ if (!Number.isFinite(ms)) throw customerError('E_USAGE', '--since is not a valid timestamp or relative window (90d / 24h / ISO)', usage)
2629
+ return ms
2630
+ }
2631
+
2632
+ /** Parse --kind against the kinds this build derives (facts are 0.3.x). */
2633
+ function customerTimelineKinds(value, usage) {
2634
+ if (value === undefined) return undefined
2635
+ const allowed = ['delivery', 'note', 'commitment']
2636
+ const kinds = String(value).split(',').map((item) => item.trim()).filter(Boolean)
2637
+ if (!kinds.length) throw customerError('E_USAGE', '--kind requires at least one value (' + allowed.join(',') + ')', usage)
2638
+ for (const kind of kinds) {
2639
+ if (!allowed.includes(kind)) throw customerError('E_USAGE', 'unknown timeline kind: ' + kind, usage + ' (allowed: ' + allowed.join(',') + ')')
2640
+ }
2641
+ return kinds
2642
+ }
2643
+
2644
+ function customerTimelineLines(items, emptyText) {
2645
+ if (!items.length) return ['(' + (emptyText || '时间线为空') + ')']
2646
+ return items.map((item) => {
2647
+ const at = String(item.at).replace('T', ' ').slice(0, 16)
2648
+ const status = item.kind === 'commitment' && item.status ? ' [' + item.status + ']' : ''
2649
+ return ' ' + at + ' ' + String(item.kind).padEnd(10) + ' ' + item.title + status
2650
+ })
2651
+ }
2652
+
2653
+ function customerClearanceLines(payload) {
2654
+ const lines = []
2655
+ if (payload.protectedExcluded) lines.push('clearance=' + payload.clearance + ' · 已隐藏 ' + payload.protectedExcluded + ' 个受保护对象(只报计数,不展示内容)')
2656
+ if (payload.degraded && payload.degraded.length) lines.push('降级(无法放置到时间线的行):' + payload.degraded.join(', '))
2657
+ return lines
2658
+ }
2659
+
2660
+ function customerDescribeOpen(open, limit) {
2661
+ const lines = []
2662
+ if (open.mine.length) {
2663
+ lines.push('未完成 · 我方欠客户(' + open.mine.length + '):')
2664
+ for (const row of open.mine.slice(0, limit)) lines.push(' ' + row.id + ' ' + row.action + (row.dueAt ? ' · 截止 ' + row.dueAt : '') + (row.projectId ? ' [' + row.projectId + ']' : ''))
2665
+ }
2666
+ if (open.waiting.length) {
2667
+ lines.push('未完成 · 等对方(' + open.waiting.length + '):')
2668
+ for (const row of open.waiting.slice(0, limit)) lines.push(' ' + row.id + ' ' + row.action + (row.dueAt ? ' · 截止 ' + row.dueAt : '') + (row.projectId ? ' [' + row.projectId + ']' : ''))
2669
+ }
2670
+ return lines
2671
+ }
2672
+
2673
+ function customerPrint(asJson, payload, lines) {
2674
+ if (asJson) { console.log(JSON.stringify(payload, null, 2)); return }
2675
+ for (const line of lines) console.log(line)
2676
+ }
2677
+
2678
+ /* ---------------------------- client commands ---------------------------- */
2679
+
2680
+ function clientUsage() {
2681
+ console.log('usage: advisers client <add|list|show|timeline|archive|merge|note> ...')
2682
+ console.log(' ' + CUSTOMER_USAGE.add)
2683
+ console.log(' ' + CUSTOMER_USAGE.list)
2684
+ console.log(' ' + CUSTOMER_USAGE.show)
2685
+ console.log(' ' + CUSTOMER_USAGE.timeline)
2686
+ console.log(' ' + CUSTOMER_USAGE.archive)
2687
+ console.log(' ' + CUSTOMER_USAGE.merge)
2688
+ console.log(' ' + CUSTOMER_USAGE.note)
2689
+ console.log(' ' + CUSTOMER_USAGE.noteList)
2690
+ console.log('客户是归属维度:matter 通过 --client/--project 挂到客户;commitments/facts 仍只挂 matter。')
2691
+ }
2692
+
2693
+ function clientAdd(rest) {
2694
+ const usage = CUSTOMER_USAGE.add
2695
+ try {
2696
+ const parsed = customerFlags(rest, { booleans: ['json'], values: ['aliases', 'tags', 'secrecy', 'note', 'link-matter'] }, usage)
2697
+ const name = parsed.positional.join(' ').trim()
2698
+ if (!name) throw customerError('E_USAGE', 'a client name is required', usage)
2699
+ const aliases = customerCommaList(parsed.flags.aliases, 'aliases', usage)
2700
+ const tags = customerCommaList(parsed.flags.tags, 'tags', usage)
2701
+ const secrecyDefault = customerIntegerFlag(parsed.flags.secrecy, 'secrecy', 0, 3, 0, usage)
2702
+ const notes = typeof parsed.flags.note === 'string' ? parsed.flags.note : undefined
2703
+ const linkMatter = typeof parsed.flags['link-matter'] === 'string' ? parsed.flags['link-matter'].trim() : undefined
2704
+ if (!customerStoreOrFail()) return
2705
+ const audit = { actor: 'local', action: 'client.add', allowed: true, reason: '' }
2706
+ const made = mutateWithAudit((store) => {
2707
+ const client = store.addClient({ name: name, aliases: aliases, tags: tags, secrecyDefault: secrecyDefault, notes: notes })
2708
+ let matter = null
2709
+ if (linkMatter) {
2710
+ matter = store.setMatterClient(linkMatter, { clientId: client.id })
2711
+ audit.reason = client.id + ';matter=' + matter.id
2712
+ } else {
2713
+ audit.reason = client.id
2714
+ }
2715
+ return { client: client, matter: matter }
2716
+ }, audit)
2717
+ const result = made.result
2718
+ const payload = { ok: true, command: 'client add', client: result.client }
2719
+ if (result.matter) payload.matter = result.matter
2720
+ const lines = ['created ' + result.client.id + ' ' + result.client.name + (result.client.aliases.length ? ' (' + result.client.aliases.join('/') + ')' : '')]
2721
+ if (result.matter) lines.push('linked matter ' + result.matter.id + ' ' + result.matter.title)
2722
+ customerPrint(parsed.flags.json === true, payload, lines)
2723
+ } catch (error) { reportCustomerFailure(error) }
2724
+ }
2725
+
2726
+ /* ---------------------------- client views ------------------------------- */
2727
+
2728
+ /** One derived list row: client row + exact counts + next due + clearance info. */
2729
+ function clientListRow(store, client) {
2730
+ const clearance = CUSTOMER_DEFAULT_CLEARANCE
2731
+ const view = readClientView(store, client.id)
2732
+ const filtered = clearCustomerView(view, clearance)
2733
+ return {
2734
+ ...client,
2735
+ counts: customerClientCounts(store, view, filtered, clearance),
2736
+ nextDueAt: customerNextDueAt(filtered.open),
2737
+ clearance: clearance,
2738
+ protectedExcluded: filtered.protectedExcluded,
2739
+ }
2740
+ }
2741
+
2742
+ /** One project row inside a cleared client view (counts scoped to that project). */
2743
+ function customerProjectOfClientCounts(store, view, filtered, project, clearance) {
2744
+ const matters = filtered.matters.filter((matter) => matter.projectId === project.id)
2745
+ const allowedIds = matters.map((matter) => matter.id)
2746
+ const allowedSet = new Set(allowedIds)
2747
+ const openRows = filtered.open.filter((row) => allowedSet.has(row.matter_id))
2748
+ const { mine, waiting } = customerSplitOpen(openRows, filtered.matterById)
2749
+ return {
2750
+ counts: {
2751
+ matters: matters.length,
2752
+ mattersArchived: matters.filter((matter) => matter.status === 'archived').length,
2753
+ deliveries: customerCountRows(store, 'deliveries', allowedIds),
2754
+ notes: customerCountProjectNotes(store, project, allowedSet, clearance, view.client),
2755
+ commitments: customerCountRows(store, 'commitments', allowedIds),
2756
+ openMine: mine.length,
2757
+ openWaiting: waiting.length,
2758
+ overdue: customerOverdueCount([...mine, ...waiting]),
2759
+ },
2760
+ nextDueAt: customerNextDueAt(openRows),
2761
+ }
2762
+ }
2763
+
2764
+ function clientList(rest) {
2765
+ const usage = CUSTOMER_USAGE.list
2766
+ try {
2767
+ const parsed = customerFlags(rest, { booleans: ['json', 'all'], values: ['limit'] }, usage)
2768
+ const limit = customerIntegerFlag(parsed.flags.limit, 'limit', 1, CUSTOMER_MAX_LIMIT, CUSTOMER_DEFAULT_LIMIT, usage)
2769
+ if (!customerStoreOrFail()) return
2770
+ const store = readStoreOrExit()
2771
+ const all = parsed.flags.all === true
2772
+ const rows = store.read(() => store.listClients({ status: all ? 'all' : 'active', includeDeleted: all, limit: limit }).map((client) => clientListRow(store, client)))
2773
+ const lines = rows.length
2774
+ ? rows.map((row) => row.id + ' ' + row.status + ' secrecy=' + row.secrecyDefault + ' matters=' + row.counts.matters + ' open=' + (row.counts.openMine + row.counts.openWaiting) + ' next=' + (row.nextDueAt || '-') + ' ' + row.name + (row.aliases.length ? ' (' + row.aliases.join('/') + ')' : ''))
2775
+ : ['(没有客户)']
2776
+ customerPrint(parsed.flags.json === true, rows, lines)
2777
+ } catch (error) { reportCustomerFailure(error) }
2778
+ }
2779
+
2780
+ function clientShow(rest) {
2781
+ const usage = CUSTOMER_USAGE.show
2782
+ try {
2783
+ const parsed = customerFlags(rest, { booleans: ['json'], values: ['timeline-limit', 'clearance'] }, usage)
2784
+ const id = customerIdArg(parsed.positional, 0, 'a client id', usage)
2785
+ const clearance = customerIntegerFlag(parsed.flags.clearance, 'clearance', 0, 3, CUSTOMER_DEFAULT_CLEARANCE, usage)
2786
+ const timelineLimit = customerIntegerFlag(parsed.flags['timeline-limit'], 'timeline-limit', 0, CUSTOMER_TIMELINE_MAX, CUSTOMER_TIMELINE_DEFAULT, usage)
2787
+ if (!customerStoreOrFail()) return
2788
+ const store = readStoreOrExit()
2789
+ const payload = store.read(() => {
2790
+ const view = readClientView(store, id)
2791
+ const filtered = clearCustomerView(view, clearance)
2792
+ const counts = customerClientCounts(store, view, filtered, clearance)
2793
+ const timeline = customerTimeline(view, filtered, { limit: timelineLimit })
2794
+ const open = customerOpenBuckets(view, filtered)
2795
+ const projects = view.projects.map((project) => {
2796
+ const summary = customerProjectOfClientCounts(store, view, filtered, project, clearance)
2797
+ return { ...project, counts: summary.counts, nextDueAt: summary.nextDueAt }
2798
+ })
2799
+ const matters = filtered.matters.map((matter) => {
2800
+ const openRows = filtered.open.filter((row) => row.matter_id === matter.id)
2801
+ return {
2802
+ id: matter.id,
2803
+ title: matter.title,
2804
+ status: matter.status,
2805
+ secrecy: Number(matter.secrecy ?? 0),
2806
+ projectId: matter.projectId ?? null,
2807
+ openCommitments: openRows.length,
2808
+ nextDueAt: customerNextDueAt(openRows),
2809
+ }
2810
+ })
2811
+ return {
2812
+ ok: true,
2813
+ command: 'client show',
2814
+ client: view.client,
2815
+ projects: projects,
2816
+ matters: matters,
2817
+ counts: counts,
2818
+ open: open,
2819
+ nextDueAt: customerNextDueAt(filtered.open),
2820
+ timeline: timeline.items,
2821
+ timelineTotal: timeline.total,
2822
+ timelineTruncated: timeline.truncated,
2823
+ nextCursor: null,
2824
+ clearance: clearance,
2825
+ protectedExcluded: filtered.protectedExcluded,
2826
+ degraded: timeline.degraded,
2827
+ }
2828
+ })
2829
+ const lines = []
2830
+ lines.push(payload.client.name + ' ' + payload.client.id + ' ' + payload.client.status)
2831
+ lines.push('保密默认 ' + payload.client.secrecyDefault + ' · 标签 ' + (payload.client.tags.length ? payload.client.tags.join(',') : '-') + (payload.client.notes ? ' · 备注 ' + payload.client.notes : ''))
2832
+ lines.push('事项 ' + payload.counts.matters + '(归档 ' + payload.counts.mattersArchived + ') · 未完成 我方 ' + payload.counts.openMine + ' / 对方 ' + payload.counts.openWaiting + ' · 逾期 ' + payload.counts.overdue + ' · 交付 ' + payload.counts.deliveries + ' · 备注 ' + payload.counts.notes + ' · 下一截止 ' + (payload.nextDueAt || '无'))
2833
+ if (payload.projects.length) {
2834
+ lines.push('项目(' + payload.projects.length + '):')
2835
+ for (const project of payload.projects) {
2836
+ lines.push(' ' + project.id + ' ' + project.name + ' ' + project.status + ' matters=' + project.counts.matters + ' open=' + (project.counts.openMine + project.counts.openWaiting) + ' next=' + (project.nextDueAt || '-'))
2837
+ }
2838
+ }
2839
+ lines.push(...customerDescribeOpen(payload.open, 10))
2840
+ lines.push('时间线(显示 ' + payload.timeline.length + ' / 匹配 ' + payload.timelineTotal + '):')
2841
+ lines.push(...customerTimelineLines(payload.timeline))
2842
+ lines.push(...customerClearanceLines(payload))
2843
+ customerPrint(parsed.flags.json === true, payload, lines)
2844
+ } catch (error) { reportCustomerFailure(error) }
2845
+ }
2846
+
2847
+ function clientTimeline(rest) {
2848
+ const usage = CUSTOMER_USAGE.timeline
2849
+ try {
2850
+ const parsed = customerFlags(rest, { booleans: ['json'], values: ['since', 'kind', 'limit', 'clearance'] }, usage)
2851
+ const id = customerIdArg(parsed.positional, 0, 'a client id', usage)
2852
+ const clearance = customerIntegerFlag(parsed.flags.clearance, 'clearance', 0, 3, CUSTOMER_DEFAULT_CLEARANCE, usage)
2853
+ const limit = customerIntegerFlag(parsed.flags.limit, 'limit', 0, CUSTOMER_TIMELINE_MAX, CUSTOMER_TIMELINE_DEFAULT, usage)
2854
+ const since = customerSince(typeof parsed.flags.since === 'string' ? parsed.flags.since : undefined, usage)
2855
+ const kinds = customerTimelineKinds(typeof parsed.flags.kind === 'string' ? parsed.flags.kind : undefined, usage)
2856
+ if (!customerStoreOrFail()) return
2857
+ const store = readStoreOrExit()
2858
+ const payload = store.read(() => {
2859
+ const view = readClientView(store, id)
2860
+ const filtered = clearCustomerView(view, clearance)
2861
+ const timeline = customerTimeline(view, filtered, { since: since, kinds: kinds, limit: limit })
2862
+ return {
2863
+ ok: true,
2864
+ command: 'client timeline',
2865
+ clientId: view.client.id,
2866
+ client: { id: view.client.id, name: view.client.name },
2867
+ items: timeline.items,
2868
+ total: timeline.total,
2869
+ truncated: timeline.truncated,
2870
+ nextCursor: null,
2871
+ clearance: clearance,
2872
+ protectedExcluded: filtered.protectedExcluded,
2873
+ degraded: timeline.degraded,
2874
+ }
2875
+ })
2876
+ const lines = [payload.client.name + ' 时间线(显示 ' + payload.items.length + ' / 匹配 ' + payload.total + (payload.truncated ? ',已截断' : '') + '):']
2877
+ lines.push(...customerTimelineLines(payload.items))
2878
+ lines.push(...customerClearanceLines(payload))
2879
+ customerPrint(parsed.flags.json === true, payload, lines)
2880
+ } catch (error) { reportCustomerFailure(error) }
2881
+ }
2882
+
2883
+ /** Shared archive precondition: active projects block archiving (fail closed). */
2884
+ function clientActiveProjects(store, clientId) {
2885
+ return store.listProjects({ clientId: clientId, status: 'active', limit: 1000 })
2886
+ }
2887
+
2888
+ function clientArchive(rest) {
2889
+ const usage = CUSTOMER_USAGE.archive
2890
+ try {
2891
+ const parsed = customerFlags(rest, { booleans: ['json', 'dry-run'], values: [] }, usage)
2892
+ const id = customerIdArg(parsed.positional, 0, 'a client id', usage)
2893
+ if (!customerStoreOrFail()) return
2894
+ const dryRun = parsed.flags['dry-run'] === true
2895
+ if (dryRun) {
2896
+ const store = readStoreOrExit()
2897
+ const plan = store.read(() => {
2898
+ const client = store.getClient(id)
2899
+ if (!client) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + id, 'advisers client list')
2900
+ return { client: client, activeProjects: clientActiveProjects(store, id) }
2901
+ })
2902
+ const payload = {
2903
+ ok: true,
2904
+ command: 'client archive',
2905
+ dryRun: true,
2906
+ client: plan.client,
2907
+ activeProjects: plan.activeProjects.length,
2908
+ wouldBlock: plan.activeProjects.length > 0,
2909
+ }
2910
+ const lines = ['would archive ' + plan.client.id + ' ' + plan.client.name + '(dry-run,未写入)']
2911
+ if (payload.wouldBlock) lines.push('注意:还有 ' + payload.activeProjects + ' 个 active 项目,正式执行会被拒绝(E_CLIENT_HAS_ACTIVE_PROJECTS)')
2912
+ customerPrint(parsed.flags.json === true, payload, lines)
2913
+ return
2914
+ }
2915
+ const audit = { actor: 'local', action: 'client.archive', allowed: true, reason: id }
2916
+ const made = mutateWithAudit((store) => {
2917
+ const client = store.getClient(id)
2918
+ if (!client) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + id, 'advisers client list')
2919
+ const activeProjects = clientActiveProjects(store, id)
2920
+ if (activeProjects.length) {
2921
+ throw customerError('E_CLIENT_HAS_ACTIVE_PROJECTS', 'client has ' + activeProjects.length + ' active project(s); archive them first', 'advisers project list --client ' + id)
2922
+ }
2923
+ return store.archiveClient(id)
2924
+ }, audit)
2925
+ const payload = { ok: true, command: 'client archive', client: made.result }
2926
+ customerPrint(parsed.flags.json === true, payload, ['archived ' + made.result.id + ' ' + made.result.name])
2927
+ } catch (error) { reportCustomerFailure(error) }
2928
+ }
2929
+
2930
+ function clientMerge(rest) {
2931
+ const usage = CUSTOMER_USAGE.merge
2932
+ try {
2933
+ const parsed = customerFlags(rest, { booleans: ['json', 'dry-run'], values: [] }, usage)
2934
+ const fromId = customerIdArg(parsed.positional, 0, 'a source client id', usage)
2935
+ const intoId = customerIdArg(parsed.positional, 1, 'a target client id', usage)
2936
+ if (fromId === intoId) throw customerError('E_CLIENT_MERGE_SELF', 'cannot merge a client into itself', usage)
2937
+ if (!customerStoreOrFail()) return
2938
+ const dryRun = parsed.flags['dry-run'] === true
2939
+ if (dryRun) {
2940
+ const store = readStoreOrExit()
2941
+ const plan = store.read(() => {
2942
+ const source = store.getClient(fromId)
2943
+ if (!source) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + fromId, 'advisers client list')
2944
+ const target = store.getClient(intoId)
2945
+ if (!target) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + intoId, 'advisers client list')
2946
+ if (target.status !== 'active' || target.deletedAt) throw customerError('E_CLIENT_ARCHIVED', 'target client is archived: ' + intoId, 'advisers client list')
2947
+ const sourceProjects = store.listProjects({ clientId: fromId, status: 'all', includeDeleted: true, limit: 1000 })
2948
+ const targetProjects = store.listProjects({ clientId: intoId, status: 'active', limit: 1000 })
2949
+ const targetNames = new Set(targetProjects.map((project) => project.nameNorm))
2950
+ let movedProjects = 0
2951
+ let mergedProjects = 0
2952
+ for (const project of sourceProjects) {
2953
+ if (targetNames.has(project.nameNorm)) mergedProjects++
2954
+ else movedProjects++
2955
+ }
2956
+ const countClientRows = (table) => Number(store.db.prepare('SELECT COUNT(*) AS n FROM ' + table + ' WHERE client_id = ?').get(fromId)?.n ?? 0)
2957
+ return {
2958
+ source: source,
2959
+ target: target,
2960
+ plan: {
2961
+ movedMatters: Number(store.db.prepare('SELECT COUNT(*) AS n FROM matters WHERE client_id = ?').get(fromId)?.n ?? 0),
2962
+ movedProjects: movedProjects,
2963
+ mergedProjects: mergedProjects,
2964
+ movedNotes: countClientRows('client_notes'),
2965
+ movedDeliveries: countClientRows('deliveries'),
2966
+ },
2967
+ }
2968
+ })
2969
+ const payload = { ok: true, command: 'client merge', dryRun: true, from: plan.source, into: plan.target, plan: plan.plan }
2970
+ const lines = [
2971
+ 'would merge ' + plan.source.id + ' ' + plan.source.name + ' -> ' + plan.target.id + ' ' + plan.target.name + '(dry-run,未写入)',
2972
+ ' matters=' + plan.plan.movedMatters + ' projects=' + plan.plan.movedProjects + ' (+' + plan.plan.mergedProjects + ' 同名合并) notes=' + plan.plan.movedNotes + ' deliveries=' + plan.plan.movedDeliveries,
2973
+ ' 源客户会归档(不删除),名称/别名在不冲突时并入目标客户;不自动合并同名事项。',
2974
+ ]
2975
+ customerPrint(parsed.flags.json === true, payload, lines)
2976
+ return
2977
+ }
2978
+ const audit = { actor: 'local', action: 'client.merge', allowed: true, reason: fromId + '->' + intoId }
2979
+ const made = mutateWithAudit((store) => {
2980
+ const result = store.mergeClients(fromId, intoId)
2981
+ audit.reason = fromId + '->' + intoId + ';matter=' + result.movedMatters + ';project=' + result.movedProjects + ';note=' + result.movedNotes
2982
+ return result
2983
+ }, audit)
2984
+ const payload = { ok: true, command: 'client merge', ...made.result }
2985
+ const lines = [
2986
+ 'merged ' + made.result.mergedFrom + ' -> ' + made.result.client.id + ' ' + made.result.client.name,
2987
+ ' matters=' + made.result.movedMatters + ' projects=' + made.result.movedProjects + ' (+' + made.result.mergedProjects + ' 同名合并) notes=' + made.result.movedNotes + ' deliveries=' + made.result.movedDeliveries + ' aliases+' + made.result.carriedAliases,
2988
+ ]
2989
+ customerPrint(parsed.flags.json === true, payload, lines)
2990
+ } catch (error) { reportCustomerFailure(error) }
2991
+ }
2992
+
2993
+ function clientNote(rest) {
2994
+ const sub = rest[0]
2995
+ if (sub === 'add') return clientNoteAdd(rest.slice(1))
2996
+ if (sub === 'list' || sub === 'ls') return clientNoteList(rest.slice(1))
2997
+ customerFail('E_USAGE', 'unknown client note subcommand: ' + String(sub), CUSTOMER_USAGE.note + ' / ' + CUSTOMER_USAGE.noteList)
2998
+ }
2999
+
3000
+ function clientNoteAdd(rest) {
3001
+ const usage = CUSTOMER_USAGE.note
3002
+ try {
3003
+ const parsed = customerFlags(rest, { booleans: ['json'], values: ['kind', 'at', 'project', 'matter'] }, usage)
3004
+ const clientId = customerIdArg(parsed.positional, 0, 'a client id', usage)
3005
+ const summary = parsed.positional.slice(1).join(' ').trim()
3006
+ if (!summary) throw customerError('E_USAGE', 'a note summary is required', usage)
3007
+ const kind = typeof parsed.flags.kind === 'string' ? parsed.flags.kind : undefined
3008
+ const at = typeof parsed.flags.at === 'string' ? parsed.flags.at : undefined
3009
+ const projectId = typeof parsed.flags.project === 'string' ? parsed.flags.project.trim() : undefined
3010
+ const matterId = typeof parsed.flags.matter === 'string' ? parsed.flags.matter.trim() : undefined
3011
+ if (!customerStoreOrFail()) return
3012
+ const audit = { actor: 'local', action: 'client.note.add', allowed: true, reason: '' }
3013
+ const made = mutateWithAudit((store) => {
3014
+ const note = store.addClientNote({ clientId: clientId, summary: summary, kind: kind, at: at, projectId: projectId, matterId: matterId })
3015
+ audit.reason = note.id
3016
+ return note
3017
+ }, audit)
3018
+ const payload = { ok: true, command: 'client note add', note: made.result }
3019
+ const preview = made.result.summary.replace(/\s+/g, ' ').slice(0, 80)
3020
+ customerPrint(parsed.flags.json === true, payload, ['added ' + made.result.id + ' ' + made.result.at + ' [' + made.result.kind + '] ' + preview])
3021
+ } catch (error) { reportCustomerFailure(error) }
3022
+ }
3023
+
3024
+ function clientNoteList(rest) {
3025
+ const usage = CUSTOMER_USAGE.noteList
3026
+ try {
3027
+ const parsed = customerFlags(rest, { booleans: ['json'], values: ['project', 'limit'] }, usage)
3028
+ const clientId = customerIdArg(parsed.positional, 0, 'a client id', usage)
3029
+ const projectId = typeof parsed.flags.project === 'string' ? parsed.flags.project.trim() : undefined
3030
+ const limit = customerIntegerFlag(parsed.flags.limit, 'limit', 1, 500, 50, usage)
3031
+ if (!customerStoreOrFail()) return
3032
+ const store = readStoreOrExit()
3033
+ const rows = store.read(() => {
3034
+ const client = store.getClient(clientId)
3035
+ if (!client) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + clientId, 'advisers client list')
3036
+ return store.listClientNotes({ clientId: clientId, projectId: projectId, limit: limit })
3037
+ })
3038
+ const lines = rows.length
3039
+ ? rows.map((note) => note.id + ' ' + note.at + ' [' + note.kind + '] ' + String(note.summary).replace(/\s+/g, ' ').slice(0, 100) + (note.projectId ? ' [' + note.projectId + ']' : ''))
3040
+ : ['(没有备注)']
3041
+ customerPrint(parsed.flags.json === true, rows, lines)
3042
+ } catch (error) { reportCustomerFailure(error) }
3043
+ }
3044
+
3045
+ function clientCommand(rawArgs) {
3046
+ const sub = rawArgs[0]
3047
+ const rest = rawArgs.slice(1)
3048
+ if (!sub || sub === 'help' || sub === '--help') { clientUsage(); return }
3049
+ if (sub === 'add') return clientAdd(rest)
3050
+ if (sub === 'list' || sub === 'ls') return clientList(rest)
3051
+ if (sub === 'show') return clientShow(rest)
3052
+ if (sub === 'timeline') return clientTimeline(rest)
3053
+ if (sub === 'archive') return clientArchive(rest)
3054
+ if (sub === 'merge') return clientMerge(rest)
3055
+ if (sub === 'note') return clientNote(rest)
3056
+ customerFail('E_USAGE', 'unknown client subcommand: ' + String(sub), 'advisers client help')
3057
+ }
3058
+
3059
+ /* ---------------------------- project commands --------------------------- */
3060
+
3061
+ function projectUsage() {
3062
+ console.log('usage: advisers project <add|list|show|archive> ...')
3063
+ console.log(' ' + CUSTOMER_USAGE.projectAdd)
3064
+ console.log(' ' + CUSTOMER_USAGE.projectList)
3065
+ console.log(' ' + CUSTOMER_USAGE.projectShow)
3066
+ console.log(' ' + CUSTOMER_USAGE.projectArchive)
3067
+ console.log('项目属于一个客户;跨客户工作拆成两个项目。事项用 matter add --client --project 挂到项目。')
3068
+ }
3069
+
3070
+ function projectAdd(rest) {
3071
+ const usage = CUSTOMER_USAGE.projectAdd
3072
+ try {
3073
+ const parsed = customerFlags(rest, { booleans: ['json'], values: ['start', 'end', 'default-matter', 'note'] }, usage)
3074
+ const clientId = customerIdArg(parsed.positional, 0, 'a client id', usage)
3075
+ const name = parsed.positional.slice(1).join(' ').trim()
3076
+ if (!name) throw customerError('E_USAGE', 'a project name is required', usage)
3077
+ const startedAt = typeof parsed.flags.start === 'string' ? parsed.flags.start : undefined
3078
+ const dueAt = typeof parsed.flags.end === 'string' ? parsed.flags.end : undefined
3079
+ const defaultMatterId = typeof parsed.flags['default-matter'] === 'string' ? parsed.flags['default-matter'].trim() : undefined
3080
+ const notes = typeof parsed.flags.note === 'string' ? parsed.flags.note : undefined
3081
+ if (!customerStoreOrFail()) return
3082
+ const audit = { actor: 'local', action: 'project.add', allowed: true, reason: '' }
3083
+ const made = mutateWithAudit((store) => {
3084
+ const project = store.addProject({ clientId: clientId, name: name, startedAt: startedAt, dueAt: dueAt, defaultMatterId: defaultMatterId, notes: notes })
3085
+ audit.reason = project.id
3086
+ return project
3087
+ }, audit)
3088
+ const payload = { ok: true, command: 'project add', project: made.result }
3089
+ customerPrint(parsed.flags.json === true, payload, ['created ' + made.result.id + ' ' + made.result.name + ' (client ' + made.result.clientId + ')'])
3090
+ } catch (error) { reportCustomerFailure(error) }
3091
+ }
3092
+
3093
+ function projectListRow(store, project, client) {
3094
+ const clearance = CUSTOMER_DEFAULT_CLEARANCE
3095
+ const view = readProjectView(store, project.id)
3096
+ const filtered = clearCustomerView(view, clearance)
3097
+ return {
3098
+ ...project,
3099
+ client: client ? { id: client.id, name: client.name, status: client.status } : null,
3100
+ counts: customerProjectCounts(store, view, filtered, clearance),
3101
+ nextDueAt: customerNextDueAt(filtered.open),
3102
+ clearance: clearance,
3103
+ protectedExcluded: filtered.protectedExcluded,
3104
+ }
3105
+ }
3106
+
3107
+ function projectList(rest) {
3108
+ const usage = CUSTOMER_USAGE.projectList
3109
+ try {
3110
+ const parsed = customerFlags(rest, { booleans: ['json', 'all'], values: ['client', 'limit'] }, usage)
3111
+ const clientId = typeof parsed.flags.client === 'string' ? parsed.flags.client.trim() : undefined
3112
+ const limit = customerIntegerFlag(parsed.flags.limit, 'limit', 1, CUSTOMER_MAX_LIMIT, CUSTOMER_DEFAULT_LIMIT, usage)
3113
+ if (!customerStoreOrFail()) return
3114
+ const store = readStoreOrExit()
3115
+ const all = parsed.flags.all === true
3116
+ const rows = store.read(() => {
3117
+ if (clientId && !store.getClient(clientId)) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + clientId, 'advisers client list')
3118
+ const projects = store.listProjects({ clientId: clientId, status: all ? 'all' : 'active', includeDeleted: all, limit: limit })
3119
+ const clientById = new Map(store.listClients({ status: 'all', includeDeleted: true, limit: 1000 }).map((client) => [client.id, client]))
3120
+ return projects.map((project) => projectListRow(store, project, clientById.get(project.clientId)))
3121
+ })
3122
+ const lines = rows.length
3123
+ ? rows.map((row) => row.id + ' ' + row.status + ' matters=' + row.counts.matters + ' open=' + (row.counts.openMine + row.counts.openWaiting) + ' next=' + (row.nextDueAt || '-') + ' ' + row.name + (row.client ? ' [' + row.client.name + ']' : ''))
3124
+ : ['(没有项目)']
3125
+ customerPrint(parsed.flags.json === true, rows, lines)
3126
+ } catch (error) { reportCustomerFailure(error) }
3127
+ }
3128
+
3129
+ function projectShow(rest) {
3130
+ const usage = CUSTOMER_USAGE.projectShow
3131
+ try {
3132
+ const parsed = customerFlags(rest, { booleans: ['json'], values: ['timeline-limit', 'clearance'] }, usage)
3133
+ const id = customerIdArg(parsed.positional, 0, 'a project id', usage)
3134
+ const clearance = customerIntegerFlag(parsed.flags.clearance, 'clearance', 0, 3, CUSTOMER_DEFAULT_CLEARANCE, usage)
3135
+ const timelineLimit = customerIntegerFlag(parsed.flags['timeline-limit'], 'timeline-limit', 0, CUSTOMER_TIMELINE_MAX, CUSTOMER_TIMELINE_DEFAULT, usage)
3136
+ if (!customerStoreOrFail()) return
3137
+ const store = readStoreOrExit()
3138
+ const payload = store.read(() => {
3139
+ const view = readProjectView(store, id)
3140
+ const filtered = clearCustomerView(view, clearance)
3141
+ const counts = customerProjectCounts(store, view, filtered, clearance)
3142
+ const timeline = customerTimeline(view, filtered, { limit: timelineLimit })
3143
+ const open = customerOpenBuckets(view, filtered)
3144
+ const matters = filtered.matters.map((matter) => {
3145
+ const openRows = filtered.open.filter((row) => row.matter_id === matter.id)
3146
+ return {
3147
+ id: matter.id,
3148
+ title: matter.title,
3149
+ status: matter.status,
3150
+ secrecy: Number(matter.secrecy ?? 0),
3151
+ openCommitments: openRows.length,
3152
+ nextDueAt: customerNextDueAt(openRows),
3153
+ }
3154
+ })
3155
+ return {
3156
+ ok: true,
3157
+ command: 'project show',
3158
+ project: view.project,
3159
+ client: view.client,
3160
+ matters: matters,
3161
+ counts: counts,
3162
+ open: open,
3163
+ nextDueAt: customerNextDueAt(filtered.open),
3164
+ timeline: timeline.items,
3165
+ timelineTotal: timeline.total,
3166
+ timelineTruncated: timeline.truncated,
3167
+ nextCursor: null,
3168
+ clearance: clearance,
3169
+ protectedExcluded: filtered.protectedExcluded,
3170
+ degraded: timeline.degraded,
3171
+ }
3172
+ })
3173
+ const lines = []
3174
+ lines.push(payload.project.name + ' ' + payload.project.id + ' ' + payload.project.status + (payload.client ? ' [' + payload.client.name + ']' : ''))
3175
+ lines.push('事项 ' + payload.counts.matters + '(归档 ' + payload.counts.mattersArchived + ') · 未完成 我方 ' + payload.counts.openMine + ' / 对方 ' + payload.counts.openWaiting + ' · 逾期 ' + payload.counts.overdue + ' · 交付 ' + payload.counts.deliveries + ' · 备注 ' + payload.counts.notes + ' · 下一截止 ' + (payload.nextDueAt || '无'))
3176
+ if (payload.matters.length) {
3177
+ lines.push('事项:')
3178
+ for (const matter of payload.matters) lines.push(' ' + matter.id + ' ' + matter.title + ' ' + matter.status + ' open=' + matter.openCommitments + ' next=' + (matter.nextDueAt || '-'))
3179
+ }
3180
+ lines.push(...customerDescribeOpen(payload.open, 10))
3181
+ lines.push('时间线(显示 ' + payload.timeline.length + ' / 匹配 ' + payload.timelineTotal + '):')
3182
+ lines.push(...customerTimelineLines(payload.timeline))
3183
+ lines.push(...customerClearanceLines(payload))
3184
+ customerPrint(parsed.flags.json === true, payload, lines)
3185
+ } catch (error) { reportCustomerFailure(error) }
3186
+ }
3187
+
3188
+ function projectArchive(rest) {
3189
+ const usage = CUSTOMER_USAGE.projectArchive
3190
+ try {
3191
+ const parsed = customerFlags(rest, { booleans: ['json', 'dry-run'], values: [] }, usage)
3192
+ const id = customerIdArg(parsed.positional, 0, 'a project id', usage)
3193
+ if (!customerStoreOrFail()) return
3194
+ const dryRun = parsed.flags['dry-run'] === true
3195
+ if (dryRun) {
3196
+ const store = readStoreOrExit()
3197
+ const plan = store.read(() => {
3198
+ const project = store.getProject(id)
3199
+ if (!project) throw customerError('E_PROJECT_NOT_FOUND', 'unknown project: ' + id, 'advisers project list')
3200
+ return { project: project, activeMatters: store.listMattersByProject(id, { status: 'active' }).length }
3201
+ })
3202
+ const payload = { ok: true, command: 'project archive', dryRun: true, project: plan.project, activeMatters: plan.activeMatters }
3203
+ const lines = ['would archive ' + plan.project.id + ' ' + plan.project.name + '(dry-run,未写入)']
3204
+ if (plan.activeMatters) lines.push('注意:' + plan.activeMatters + ' 个 active 事项仍挂在该项目下(归档项目不会删除事项)')
3205
+ customerPrint(parsed.flags.json === true, payload, lines)
3206
+ return
3207
+ }
3208
+ const audit = { actor: 'local', action: 'project.archive', allowed: true, reason: id }
3209
+ const made = mutateWithAudit((store) => {
3210
+ const project = store.getProject(id)
3211
+ if (!project) throw customerError('E_PROJECT_NOT_FOUND', 'unknown project: ' + id, 'advisers project list')
3212
+ return store.archiveProject(id)
3213
+ }, audit)
3214
+ const payload = { ok: true, command: 'project archive', project: made.result }
3215
+ customerPrint(parsed.flags.json === true, payload, ['archived ' + made.result.id + ' ' + made.result.name])
3216
+ } catch (error) { reportCustomerFailure(error) }
3217
+ }
3218
+
3219
+ function projectCommand(rawArgs) {
3220
+ const sub = rawArgs[0]
3221
+ const rest = rawArgs.slice(1)
3222
+ if (!sub || sub === 'help' || sub === '--help') { projectUsage(); return }
3223
+ if (sub === 'add') return projectAdd(rest)
3224
+ if (sub === 'list' || sub === 'ls') return projectList(rest)
3225
+ if (sub === 'show') return projectShow(rest)
3226
+ if (sub === 'archive') return projectArchive(rest)
3227
+ customerFail('E_USAGE', 'unknown project subcommand: ' + String(sub), 'advisers project help')
3228
+ }
3229
+
1791
3230
  // ---------------------------------------------------------------------------
1792
3231
  // 0.2.3 P3: 7-day agenda + deterministic morning brief.
1793
3232
  //
@@ -1971,9 +3410,8 @@ async function buildAgendaData(input) {
1971
3410
  }
1972
3411
  if (includeCalendar) {
1973
3412
  for (const row of input.events ?? []) {
1974
- const tzid = row.tzid === undefined || row.tzid === null ? '' : String(row.tzid)
1975
- if (tzid && !['Asia/Shanghai', 'UTC', 'Etc/UTC', 'GMT', 'Z'].includes(tzid)) {
1976
- degraded.push({ source: 'calendar', code: 'E_CALENDAR_SKIP', id: row.uid ?? null, reason: 'unsupported tzid: ' + tzid })
3413
+ if (!calendarTzidSupported(row)) {
3414
+ degraded.push({ source: 'calendar', code: 'E_CALENDAR_SKIP', id: row.uid ?? null, reason: 'unsupported tzid: ' + calendarTzidOf(row) })
1977
3415
  continue
1978
3416
  }
1979
3417
  let instances
@@ -2423,7 +3861,13 @@ async function today(openRows, { calendar = false, sources = false, json = false
2423
3861
  noDue,
2424
3862
  next: next ? { id: next.id, action: next.action, dueAt: next.dueAt } : null,
2425
3863
  }
2426
- if (calendar) payload.calendar = (await calendarOccurrencesToday()).occurrences
3864
+ if (calendar) {
3865
+ const calendarToday = await calendarOccurrencesToday()
3866
+ payload.calendar = calendarToday.occurrences
3867
+ // Additive key only: the same E_CALENDAR_SKIP shape `agenda --json`
3868
+ // publishes, so consumers can see which events were skipped (not guessed).
3869
+ payload.calendarDegraded = calendarToday.degraded
3870
+ }
2427
3871
  if (sources && ledger) {
2428
3872
  payload.sources = (await collectSourceRows(ledger)).map(({ commitmentId, action, type, ref, quote }) => ({ commitmentId, action, type, ref, quote }))
2429
3873
  }
@@ -2530,35 +3974,269 @@ function tick(ledger, asJson = false) {
2530
3974
  }
2531
3975
  }
2532
3976
 
2533
- function printAudit(args = []) {
3977
+ /**
3978
+ * Rebuild the two FTS5 indexes from their source tables — the repair action
3979
+ * pointed at by `verifyFtsIntegrity()` / reader warnings ("advisers audit
3980
+ * --rebuild-fts"). Runs in the single-writer lock inside one immediate
3981
+ * transaction so a failure leaves the previous index intact, then verifies the
3982
+ * rebuilt index and records an audit row. `_setupFts()` is the same migration
3983
+ * helper v19 uses (test/fts-integrity.test.js pins this contract).
3984
+ */
3985
+ async function rebuildFtsIndexes({ asJson = false } = {}) {
3986
+ let store
3987
+ try { store = openStore() } catch (error) { return reportMaintenanceFailure(error, asJson, 'fts') }
3988
+ const before = store.verifyFtsIntegrity()
3989
+ if (before.ok) {
3990
+ if (asJson) console.log(JSON.stringify({ ok: true, rebuilt: false, reason: 'already-consistent', state: before.state, tokenizer: before.tokenizer }, null, 2))
3991
+ else console.log(`fts: consistent (state=${before.state}); no rebuild needed`)
3992
+ return
3993
+ }
3994
+ let rebuildError = null
3995
+ try {
3996
+ store.db.exec('BEGIN IMMEDIATE')
3997
+ try {
3998
+ store._setupFts()
3999
+ store.db.exec('COMMIT')
4000
+ } catch (error) {
4001
+ try { store.db.exec('ROLLBACK') } catch {}
4002
+ throw error
4003
+ }
4004
+ } catch (error) { rebuildError = error }
4005
+ const after = rebuildError ? null : store.verifyFtsIntegrity()
4006
+ if (!rebuildError && after.ok) {
4007
+ // The store caches the "FTS unusable, fall back to LIKE" flag; this process
4008
+ // just fixed it, so later reads in the same process may trust FTS again.
4009
+ store._ftsBroken = false
4010
+ store.ftsIntegrityWarning = null
4011
+ let auditRow = null
4012
+ try { auditRow = store.appendAudit({ actor: 'local', action: 'audit.rebuild_fts', allowed: true, reason: `state=${before.state};errors=${(before.errors ?? []).length};tokenizer=${after.tokenizer ?? 'none'}` }) } catch {}
4013
+ if (asJson) {
4014
+ console.log(JSON.stringify({ ok: true, rebuilt: true, before: { state: before.state, errors: before.errors }, after: { state: after.state, tokenizer: after.tokenizer }, audit: auditRow }, null, 2))
4015
+ } else {
4016
+ console.log(`fts: rebuilt (${before.state} -> ${after.state}, tokenizer=${after.tokenizer ?? 'none'})`)
4017
+ console.log(auditRow ? `audit: appended seq ${auditRow.seq}` : 'audit: could not append the rebuild row')
4018
+ }
4019
+ return
4020
+ }
4021
+ const detail = rebuildError ? String(rebuildError.message ?? rebuildError) : (after.errors ?? []).join('; ')
4022
+ if (asJson) console.log(JSON.stringify({ ok: false, rebuilt: false, code: rebuildError?.code ?? null, errors: [detail] }, null, 2))
4023
+ else {
4024
+ console.error(`fts: rebuild FAILED: ${detail}`)
4025
+ console.error(' hint: run `advisers backup` first and retry; search keeps using the LIKE fallback until the index is rebuilt (results stay complete).')
4026
+ }
4027
+ process.exitCode = 1
4028
+ }
4029
+
4030
+ /** Human one-line anchor status for `advisers audit` / `doctor`. */
4031
+ function describeAnchorCheck(check) {
4032
+ const anchor = check.anchor ?? null
4033
+ const head = check.head ?? null
4034
+ if (check.status === 'absent') {
4035
+ return 'absent (yellow — no baseline recorded yet; run `advisers audit --write-anchor` to make future tail deletions detectable)'
4036
+ }
4037
+ if (check.status === 'match') {
4038
+ return `match (count=${anchor?.count ?? head?.count ?? '?'} lastSeq=${anchor?.lastSeq ?? '?'} head=${shortAuditHash(anchor?.headHash)} keyed=${anchor?.keyed === true ? 'hmac' : 'unkeyed'})`
4039
+ }
4040
+ if (check.status === 'grown') {
4041
+ return `grown (anchor ${anchor?.count ?? '?'} -> current ${head?.count ?? '?'}; run \`advisers audit --write-anchor\` to refresh)`
4042
+ }
4043
+ return `FAIL (${check.code ?? 'anchor-error'})`
4044
+ }
4045
+
4046
+ /**
4047
+ * `advisers audit` — verify the audit hash chain and, when recorded, its tail
4048
+ * anchor (0.3.0 P0-L2).
4049
+ *
4050
+ * A hash chain detects edits/deletions in the middle, but a *tail* deletion
4051
+ * leaves a still-valid shorter chain. The local anchor
4052
+ * ($ADVISERS_HOME/audit-anchor.json, HMAC with audit.key) records the last
4053
+ * count/lastSeq/headHash: a live database that is shorter than its anchor is
4054
+ * E_AUDIT_TAIL_TRUNCATED. It is a local self-checkpoint — the same user can
4055
+ * rewrite both files — so it is never third-party attestation.
4056
+ */
4057
+ async function auditCommand(args = []) {
4058
+ const parsed = parseStrictFlags(args, {
4059
+ booleans: ['check-db', 'json', 'write-anchor', 'rebuild-fts'],
4060
+ values: ['expect-count', 'expect-head'],
4061
+ positional: false,
4062
+ })
4063
+ if (!parsed.ok) return usageFail(parsed.error, AUDIT_USAGE)
4064
+ const { flags } = parsed
4065
+ const asJson = flags.json === true
4066
+ const hasExpect = flags['expect-count'] !== undefined || flags['expect-head'] !== undefined
4067
+ if (flags['rebuild-fts'] && (flags['write-anchor'] || hasExpect || flags['check-db'])) {
4068
+ return usageFail('--rebuild-fts cannot be combined with --write-anchor/--expect-*/--check-db', AUDIT_USAGE)
4069
+ }
4070
+ if (flags['write-anchor'] && (hasExpect || flags['check-db'])) {
4071
+ return usageFail('--write-anchor cannot be combined with --expect-*/--check-db', AUDIT_USAGE)
4072
+ }
4073
+ if (hasExpect && flags['check-db']) return usageFail('--expect-* cannot be combined with --check-db', AUDIT_USAGE)
4074
+ if (mode === 'json') {
4075
+ if (asJson) console.log(JSON.stringify({ ok: false, code: 'E_USAGE', error: 'audit requires the SQLite store (ADVISERS_STORE=sqlite)' }, null, 2))
4076
+ else console.log('audit requires SQLite store')
4077
+ process.exitCode = 1
4078
+ return
4079
+ }
2534
4080
  ensureHome()
4081
+ if (flags['rebuild-fts']) return rebuildFtsIndexes({ asJson })
2535
4082
  const store = readStoreOrExit()
2536
- if (!store) { console.log('audit requires SQLite store'); return }
2537
- if (args.includes('--check-db')) {
4083
+ if (!store) {
4084
+ if (asJson) console.log(JSON.stringify({ ok: false, code: 'E_USAGE', error: 'audit requires the SQLite store' }, null, 2))
4085
+ else console.log('audit requires SQLite store')
4086
+ process.exitCode = 1
4087
+ return
4088
+ }
4089
+ let integrity = null
4090
+ if (flags['check-db']) {
2538
4091
  try {
2539
4092
  store.assertIntegrity()
2540
- console.log('integrity: ok')
4093
+ integrity = 'ok'
4094
+ if (!asJson) console.log('integrity: ok')
2541
4095
  } catch (error) {
2542
- console.error(`integrity: FAIL (${error.message})`)
4096
+ integrity = 'FAIL'
4097
+ if (asJson) console.log(JSON.stringify({ ok: false, integrity, code: 'E_DB_CORRUPT', error: error.message }, null, 2))
4098
+ else console.error(`integrity: FAIL (${error.message})`)
2543
4099
  process.exitCode = 1
2544
4100
  return
2545
4101
  }
2546
4102
  }
4103
+ const lib = await loadAuditAnchor()
2547
4104
  const verify = store.verifyAudit()
2548
- console.log(`audit: ${verify.ok ? 'verified' : `BROKEN at seq ${verify.seq}`} (${verify.count ?? 0} entries)`)
2549
- if (!verify.ok) process.exitCode = 1
2550
- for (const row of store.listAudit(20)) {
2551
- console.log(`${row.seq}\t${row.at.slice(0, 19)}\t${row.action}\t${row.allowed ? 'allow' : 'deny'}\t${row.reason ?? ''}`)
4105
+ const head = lib.readAuditHead(store, { verifyChain: false })
4106
+ if (!head.ok) {
4107
+ if (asJson) console.log(JSON.stringify({ ok: false, integrity, code: head.code, errors: head.errors }, null, 2))
4108
+ else { console.error(`audit: cannot read the audit head (${head.code}): ${(head.errors ?? []).join('; ')}`); console.error(` hint: ${lib.describeAuditAnchorCode(head.code)}`) }
4109
+ process.exitCode = 1
4110
+ return
4111
+ }
4112
+ if (flags['write-anchor']) {
4113
+ const written = lib.writeAuditAnchor({ home: HOME, store, generator: `advisers/${VERSION}` })
4114
+ if (!written.ok) {
4115
+ if (asJson) console.log(JSON.stringify({ ok: false, code: written.code, errors: written.errors, warnings: written.warnings }, null, 2))
4116
+ else {
4117
+ console.error(`anchor: write FAILED (${written.code})`)
4118
+ for (const line of written.errors ?? []) console.error(` ${line}`)
4119
+ console.error(` hint: ${lib.describeAuditAnchorCode(written.code)}`)
4120
+ }
4121
+ process.exitCode = 1
4122
+ return
4123
+ }
4124
+ if (asJson) {
4125
+ console.log(JSON.stringify({ ok: true, path: written.path, anchor: written.anchor, keyed: written.keyed, keySource: written.keySource, warnings: written.warnings }, null, 2))
4126
+ return
4127
+ }
4128
+ console.log(`anchor: written ${written.path}`)
4129
+ console.log(`anchor: entries=${written.anchor.count} lastSeq=${written.anchor.lastSeq} head=${shortAuditHash(written.anchor.headHash)} keyed=${written.anchor.keyed ? 'hmac' : 'no'} (${written.keySource ?? 'none'})`)
4130
+ for (const warning of written.warnings ?? []) console.log(`warning: ${warning}`)
4131
+ return
4132
+ }
4133
+ if (hasExpect) {
4134
+ const expectedCount = flags['expect-count'] !== undefined ? flags['expect-count'] : null
4135
+ const check = lib.verifyExpectedAudit(store, { expectedCount, expectedHead: flags['expect-head'] ?? null })
4136
+ const ok = verify.ok === true && check.ok === true
4137
+ if (asJson) {
4138
+ console.log(JSON.stringify({
4139
+ ok,
4140
+ chain: { ok: verify.ok, count: verify.count ?? head.count, brokenAt: verify.ok ? null : verify.seq },
4141
+ head: { count: head.count, lastSeq: head.lastSeq, headHash: head.headHash },
4142
+ expectation: { ok: check.ok, code: check.code, expectedCount: check.expectedCount, expectedHead: check.expectedHead, errors: check.errors },
4143
+ }, null, 2))
4144
+ } else {
4145
+ console.log(verify.ok ? `audit: verified (${verify.count ?? head.count} entries) head=${shortAuditHash(head.headHash)}` : `audit: BROKEN at seq ${verify.seq}`)
4146
+ if (!verify.ok) console.error('expect: not evaluated (the audit chain itself is broken)')
4147
+ else if (check.ok) console.log(`expect: match (count=${check.count} head=${shortAuditHash(check.headHash)})`)
4148
+ else {
4149
+ console.error(`expect: FAIL (${check.code})`)
4150
+ for (const line of check.errors ?? []) console.error(` ${line}`)
4151
+ }
4152
+ }
4153
+ if (!ok) process.exitCode = 1
4154
+ return
2552
4155
  }
4156
+ // Default: chain status line + recorded-anchor comparison.
4157
+ const anchorCheck = lib.verifyAuditAgainstAnchor({ home: HOME, store, head, env: process.env })
4158
+ const anchorRed = anchorCheck.ok !== true && anchorCheck.status !== 'absent'
4159
+ const ok = verify.ok === true && !anchorRed
4160
+ const entries = store.listAudit(20).map((row) => ({ seq: row.seq, at: row.at, action: row.action, allowed: row.allowed, reason: row.reason }))
4161
+ if (asJson) {
4162
+ console.log(JSON.stringify({
4163
+ ok,
4164
+ integrity,
4165
+ chain: { ok: verify.ok, count: verify.count ?? head.count, brokenAt: verify.ok ? null : verify.seq },
4166
+ head: { count: head.count, lastSeq: head.lastSeq, headHash: head.headHash },
4167
+ anchor: {
4168
+ found: anchorCheck.found === true,
4169
+ status: anchorCheck.status,
4170
+ ok: anchorCheck.ok === true,
4171
+ code: anchorCheck.code ?? null,
4172
+ path: anchorCheck.path ?? null,
4173
+ count: anchorCheck.anchor?.count ?? null,
4174
+ lastSeq: anchorCheck.anchor?.lastSeq ?? null,
4175
+ headHash: anchorCheck.anchor?.headHash ?? null,
4176
+ keyed: anchorCheck.anchor?.keyed ?? null,
4177
+ hmacVerified: anchorCheck.hmacVerified === true,
4178
+ errors: anchorCheck.errors ?? [],
4179
+ warnings: anchorCheck.warnings ?? [],
4180
+ },
4181
+ entries,
4182
+ }, null, 2))
4183
+ } else {
4184
+ console.log(verify.ok
4185
+ ? `audit: verified (${verify.count ?? head.count} entries) head=${shortAuditHash(head.headHash)} lastSeq=${head.lastSeq}`
4186
+ : `audit: BROKEN at seq ${verify.seq} (${head.count} entries)`)
4187
+ console.log(`anchor: ${describeAnchorCheck(anchorCheck)}`)
4188
+ for (const warning of anchorCheck.warnings ?? []) console.log(`warning: ${warning}`)
4189
+ if (anchorRed) {
4190
+ for (const line of anchorCheck.errors ?? []) console.error(` ${line}`)
4191
+ console.error(` hint: ${lib.describeAuditAnchorCode(anchorCheck.code)}`)
4192
+ }
4193
+ if (verify.ok) {
4194
+ for (const row of entries) {
4195
+ console.log(`${row.seq}\t${row.at.slice(0, 19)}\t${row.action}\t${row.allowed ? 'allow' : 'deny'}\t${row.reason ?? ''}`)
4196
+ }
4197
+ }
4198
+ }
4199
+ if (!ok) process.exitCode = 1
2553
4200
  }
2554
4201
 
2555
- function printPrivacy(args = []) {
4202
+ async function printPrivacy(args = []) {
2556
4203
  ensureHome()
2557
4204
  const asJson = args.includes('--json')
2558
4205
  const prove = args.includes('--prove')
2559
4206
  const store = readStoreOrExit()
2560
4207
  let audit = null
2561
4208
  try { const v = store?.verifyAudit(); if (v) audit = { ok: v.ok, count: v.count ?? 0 } } catch {}
4209
+ // 0.3.0 P0-L2: report the audit tail anchor next to the chain. Absent is a
4210
+ // yellow state (no baseline was ever recorded), not a failure and not proof
4211
+ // of tampering; a mismatch is red because it means a tail deletion/rollback.
4212
+ let auditAnchor = null
4213
+ if (store) {
4214
+ try {
4215
+ const lib = await loadAuditAnchor()
4216
+ const head = lib.readAuditHead(store, { verifyChain: false })
4217
+ if (head.ok) {
4218
+ const check = lib.verifyAuditAgainstAnchor({ home: HOME, store, head, env: process.env })
4219
+ auditAnchor = {
4220
+ found: check.found === true,
4221
+ status: check.status,
4222
+ ok: check.ok === true,
4223
+ code: check.code ?? null,
4224
+ count: check.anchor?.count ?? null,
4225
+ lastSeq: check.anchor?.lastSeq ?? null,
4226
+ headHash: check.anchor?.headHash ?? null,
4227
+ keyed: check.anchor?.keyed ?? null,
4228
+ hmacVerified: check.hmacVerified === true,
4229
+ path: check.path ?? null,
4230
+ errors: check.errors ?? [],
4231
+ warnings: check.warnings ?? [],
4232
+ }
4233
+ } else {
4234
+ auditAnchor = { found: false, status: 'unavailable', ok: false, code: head.code ?? null, count: null, lastSeq: null, headHash: null, keyed: null, hmacVerified: false, path: null, errors: head.errors ?? [], warnings: [] }
4235
+ }
4236
+ } catch (error) {
4237
+ auditAnchor = { found: false, status: 'unavailable', ok: false, code: null, count: null, lastSeq: null, headHash: null, keyed: null, hmacVerified: false, path: null, errors: [String(error?.message ?? error)], warnings: [] }
4238
+ }
4239
+ }
2562
4240
  // Privacy audit P2-2: list every actual egress surface from the code base
2563
4241
  // instead of two hardcoded names, and never expose internal numbering.
2564
4242
  const egressSurfaces = [
@@ -2581,6 +4259,7 @@ function printPrivacy(args = []) {
2581
4259
  secret_matter: 'egress fail-closed for secrecy > 0 on the wired model paths (local rule layer)',
2582
4260
  at_rest_encryption: 'opt-in database vault (advisers vault seal); general data is not encrypted at rest',
2583
4261
  audit,
4262
+ auditAnchor,
2584
4263
  export: 'advisers export --all',
2585
4264
  delete: 'advisers purge <matter> --yes',
2586
4265
  }
@@ -2596,6 +4275,7 @@ function printPrivacy(args = []) {
2596
4275
  console.log(`secret: ${facts.secret_matter}`)
2597
4276
  console.log(`encryption: ${facts.at_rest_encryption}`)
2598
4277
  console.log(`audit: ${audit ? (audit.ok ? `verified (${audit.count} entries)` : 'BROKEN') : 'unavailable'}`)
4278
+ console.log(`anchor: ${privacyAnchorLine(auditAnchor)}`)
2599
4279
  console.log(`export: ${facts.export}`)
2600
4280
  console.log(`delete: ${facts.delete}`)
2601
4281
  if (prove) {
@@ -2611,11 +4291,31 @@ function printPrivacy(args = []) {
2611
4291
  console.log('self-checks(本地自检:结果只说明本机文件/配置与纯函数检查;不是第三方审计,也不证明运行时无出网)')
2612
4292
  let failed = 0
2613
4293
  for (const [name, ok, detail] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name} (${detail})`) }
4294
+ if (auditAnchor) {
4295
+ if (auditAnchor.found !== true) {
4296
+ console.log(`[WARN] audit anchor absent (local self-check: yellow, not a PASS — record a baseline with \`advisers audit --write-anchor\` so a later tail deletion is detectable)`)
4297
+ } else if (auditAnchor.ok !== true && auditAnchor.status !== 'grown') {
4298
+ failed++
4299
+ console.log(`[FAIL] audit anchor ${auditAnchor.code ?? auditAnchor.status} (local self-check: the audit tail is shorter/rewritten vs the recorded anchor; see \`advisers audit\`)`)
4300
+ }
4301
+ }
2614
4302
  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.')
2615
4303
  if (failed) process.exitCode = 1
2616
4304
  }
2617
4305
  }
2618
4306
 
4307
+ /** One-line audit-anchor status for `privacy` (yellow absent / red mismatch). */
4308
+ function privacyAnchorLine(anchor) {
4309
+ if (!anchor) return 'unavailable (JSON store or no audit chain)'
4310
+ if (anchor.found !== true) {
4311
+ if (anchor.status === 'unavailable') return `unavailable (${anchor.code ?? 'no audit head'})`
4312
+ return 'absent (yellow — run `advisers audit --write-anchor` to make future tail deletions detectable)'
4313
+ }
4314
+ if (anchor.status === 'match') return `match (count=${anchor.count} keyed=${anchor.keyed === true ? 'hmac' : 'unkeyed'})`
4315
+ if (anchor.status === 'grown') return `grown (anchor ${anchor.count} -> current; run \`advisers audit --write-anchor\` to refresh)`
4316
+ return `FAIL (${anchor.code ?? anchor.status}) — see \`advisers audit\``
4317
+ }
4318
+
2619
4319
  function printLinks() {
2620
4320
  const ledger = loadReadLedger({ links: {}, matters: {} })
2621
4321
  const rows = ledger.listLinks()
@@ -2733,7 +4433,7 @@ async function petBriefJsonSchema() {
2733
4433
  async function petBrief(args) {
2734
4434
  const {
2735
4435
  PET_BRIEF_DEFAULT_DISPLAY_POLICY, PET_BRIEF_DISPLAY_POLICIES, PET_BRIEF_MAX_ITEMS,
2736
- PET_BRIEF_MAX_LINE_LENGTH, PET_BRIEF_MAX_SUGGESTED_LINES, PET_BRIEF_MOODS,
4436
+ PET_BRIEF_MAX_LINE_LENGTH, PET_BRIEF_MAX_SUGGESTED_LINES, PET_BRIEF_MIN_CONFIDENCE, PET_BRIEF_MOODS,
2737
4437
  PET_BRIEF_SCHEMA_VERSION, PET_BRIEF_SOURCE, buildPetBrief, validatePetBrief, writePetBriefAtomic,
2738
4438
  } = await loadPetBrief()
2739
4439
  const { flags } = parseFlags(args)
@@ -2786,34 +4486,62 @@ async function petBrief(args) {
2786
4486
  const sealed = vaultSealedPath()
2787
4487
  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)')
2788
4488
  }
2789
- let snapshot
4489
+ let ledger
4490
+ let nameCandidates
2790
4491
  if (mode === 'json' || !existsSync(DB)) {
2791
4492
  const { readLedgerSnapshotReadOnly } = await import('../lib/pet-brief-store.js')
4493
+ let snapshot
2792
4494
  try {
2793
4495
  snapshot = readLedgerSnapshotReadOnly({ store: mode, dbPath: DB, statePath: STATE })
2794
4496
  } catch (error) {
2795
4497
  return fail(error?.code ?? 'E_STORE', error?.message ?? String(error))
2796
4498
  }
4499
+ ledger = Ledger.fromJSON(snapshot)
2797
4500
  } else {
2798
- // 0.2.3 P1-1: buildPetBrief only reads matters/commitments/facts, so the
2799
- // projection no longer pays for the full nine-table snapshot.
4501
+ // 0.3.0 P0-T2: buildPetBrief reads matters/commitments/facts only. The
4502
+ // narrow projections give it the same rows it used to get from whole
4503
+ // entities (top-N facts by the same comparator, open commitments with an
4504
+ // SQL-computed hasEvidence flag, the redactor name candidates) without
4505
+ // the full-entity mapping and without the status+rowid TEMP B-TREE spill.
2800
4506
  try {
2801
4507
  const store = openReadStore()
2802
- snapshot = store.read(() => ({
2803
- version: 1,
2804
- matters: store.loadMatters(),
2805
- commitments: store.loadCommitments(),
2806
- // buildPetBrief only ever reads listFacts(), i.e. confirmed + not
2807
- // expired/deleted; filtering status in SQL avoids mapping history rows.
2808
- facts: store.loadFacts({ status: 'confirmed' }),
2809
- }))
4508
+ const projected = store.read(() => {
4509
+ const matters = store.loadMatters()
4510
+ const secrecyOf = (matter) => {
4511
+ const level = Number(matter.secrecy ?? 0)
4512
+ return Number.isFinite(level) ? level : Number.POSITIVE_INFINITY
4513
+ }
4514
+ const publicMatterIds = matters.filter((matter) => matter.status === 'active' && secrecyOf(matter) < 2).map((matter) => matter.id)
4515
+ return {
4516
+ matters,
4517
+ commitments: store.projectCommitmentsForPetBrief(),
4518
+ facts: store.projectFactsForPetBrief({
4519
+ limit: PET_BRIEF_MAX_ITEMS,
4520
+ minConfidence: PET_BRIEF_MIN_CONFIDENCE,
4521
+ matterIds: publicMatterIds,
4522
+ }),
4523
+ names: [...new Set([
4524
+ ...store.projectCommitmentCreditorCandidates(),
4525
+ ...store.projectFactSubjectCandidates(),
4526
+ ])],
4527
+ }
4528
+ })
4529
+ ledger = {
4530
+ listMatters: (status) => status === undefined ? projected.matters : projected.matters.filter((matter) => matter.status === status),
4531
+ listCommitments: () => projected.commitments,
4532
+ listFacts: () => projected.facts,
4533
+ }
4534
+ nameCandidates = projected.names
2810
4535
  } catch (error) {
2811
4536
  const code = error?.code === 'E_SCHEMA_STALE' || error?.code === 'E_SCHEMA_NEWER' ? error.code : 'E_STORE'
2812
4537
  return fail(code, error?.message ?? String(error))
2813
4538
  }
2814
4539
  }
2815
- const ledger = Ledger.fromJSON(snapshot)
2816
- const brief = buildPetBrief(ledger, displayPolicy ? { now: Date.now(), displayPolicy } : { now: Date.now() })
4540
+ const brief = buildPetBrief(ledger, {
4541
+ now: Date.now(),
4542
+ ...(nameCandidates ? { nameCandidates } : {}),
4543
+ ...(displayPolicy ? { displayPolicy } : {}),
4544
+ })
2817
4545
  if (check) {
2818
4546
  const result = validatePetBrief(brief, validateOptions)
2819
4547
  console.log(JSON.stringify({ ok: result.ok, checked: 'generated', expiresAt: brief.expiresAt, counts: brief.counts, errors: result.errors, warnings: result.warnings }, null, 2))
@@ -2855,15 +4583,33 @@ function printPreferences() {
2855
4583
  }
2856
4584
 
2857
4585
  /**
2858
- * `advisers doctor [--check-db]` — local diagnostics.
4586
+ * `advisers doctor [--check-db] [--json]` — local diagnostics.
2859
4587
  *
2860
4588
  * Default is intentionally lightweight (0.2.3 Wave 1 / robustness P1-4):
2861
4589
  * opening the store validates the file header, instance lock and WAL; the O(db)
2862
4590
  * PRAGMA quick_check and O(index) FTS verification only run with --check-db,
2863
4591
  * together with WAL/backup/plaintext/temp-file checks. Any FAIL exits non-zero.
4592
+ *
4593
+ * 0.3.0 P0-D1 adds the recovery console:
4594
+ * doctor --repair [--dry-run|--yes] [--only lock,temp,wal,fts] [--json]
4595
+ * --dry-run (the default) only prints a plan; --yes takes the writer lock,
4596
+ * writes a safety backup, repairs the selected items, re-verifies, records one
4597
+ * `doctor.repair` audit row and a fresh audit anchor. Unsupported --only items
4598
+ * and unknown flags fail closed with E_USAGE instead of being ignored.
2864
4599
  */
2865
4600
  async function doctor(args = []) {
2866
- const checkDb = Array.isArray(args) && args.includes('--check-db')
4601
+ const parsed = parseStrictFlags(args, {
4602
+ booleans: ['check-db', 'json', 'repair', 'dry-run', 'yes'],
4603
+ values: ['only'],
4604
+ positional: false,
4605
+ })
4606
+ if (!parsed.ok) return usageFail(parsed.error, DOCTOR_USAGE)
4607
+ const flags = parsed.flags
4608
+ if (flags.repair === true) return doctorRepair(flags)
4609
+ if (flags['dry-run'] || flags.yes) return usageFail('--dry-run/--yes are only valid with --repair', DOCTOR_USAGE)
4610
+ if (flags.only !== undefined) return usageFail('--only is only valid with --repair', DOCTOR_USAGE)
4611
+ const checkDb = flags['check-db'] === true
4612
+ const asJson = flags.json === true
2867
4613
  const rows = []
2868
4614
  const check = (name, ok, detail = '') => rows.push({ name, ok, detail })
2869
4615
  const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(Number)
@@ -2961,6 +4707,24 @@ async function doctor(args = []) {
2961
4707
  : `state=${fts.state} tokenizer=${fts.tokenizer ?? '-'}${ftsOk ? '' : ` errors=${(fts.errors ?? []).slice(0, 2).join(' | ')}`}`)
2962
4708
  const walReport = report.wal ?? maintenanceStore.walReport()
2963
4709
  check('db-wal', walReport.ok === true, `journal=${walReport.journalMode ?? '?'} initial=${walReport.initial?.status ?? '?'} current=${walReport.current?.status ?? '?'}${walReport.ok ? '' : `; ${(report.errors ?? []).slice(0, 1).join('')}`}`)
4710
+ // 0.3.0 P0-L2: report the audit tail anchor next to the chain. No anchor
4711
+ // is yellow (no baseline was recorded), not a failure.
4712
+ try {
4713
+ const anchorLib = await loadAuditAnchor()
4714
+ const anchorHead = anchorLib.readAuditHead(maintenanceStore, { verifyChain: false })
4715
+ if (anchorHead.ok !== true) {
4716
+ check('db-anchor', false, `cannot read the audit head (${anchorHead.code ?? 'unknown'})`)
4717
+ } else {
4718
+ const anchorCheck = anchorLib.verifyAuditAgainstAnchor({ home: HOME, store: maintenanceStore, head: anchorHead, env: process.env })
4719
+ const yellow = anchorCheck.status === 'absent' || anchorCheck.status === 'grown'
4720
+ let detail
4721
+ if (anchorCheck.status === 'match') detail = `match (count=${anchorCheck.anchor?.count ?? '?'} keyed=${anchorCheck.anchor?.keyed === true ? 'hmac' : 'unkeyed'})`
4722
+ else if (anchorCheck.status === 'grown') detail = `grown (anchor ${anchorCheck.anchor?.count ?? '?'} -> current ${anchorCheck.head?.count ?? '?'}; run \`advisers audit --write-anchor\` to refresh)`
4723
+ else if (anchorCheck.status === 'absent') detail = 'absent (yellow: no baseline; run \`advisers audit --write-anchor\`)'
4724
+ else detail = `FAIL ${anchorCheck.code ?? anchorCheck.status}: ${(anchorCheck.errors ?? [])[0] ?? ''}`
4725
+ check('db-anchor', anchorCheck.ok === true || yellow, detail)
4726
+ }
4727
+ } catch (error) { check('db-anchor', false, String(error?.message ?? error)) }
2964
4728
  checkBackupReadable(check)
2965
4729
  } catch (error) {
2966
4730
  if (error?.code === 'E_DB_LOCKED') {
@@ -2981,24 +4745,343 @@ async function doctor(args = []) {
2981
4745
  } catch (error) {
2982
4746
  check('pull-temps', false, String(error?.message ?? error))
2983
4747
  }
2984
- const copies = plaintextDbCopies()
2985
- const detail = copies.length
2986
- ? `${copies.length} plaintext cop(ies)${sealed ? ' after seal' : ' (documented DB copies; purge with \`advisers vault seal --remove\`)'}: ${copies.slice(0, 6).map((file) => basename(file)).join(', ')}`
2987
- : 'none'
2988
- // A sealed vault plus leftover plaintext copies is a leak (FAIL); with a
2989
- // live plaintext DB these copies are documented backups (informational).
2990
- check('plaintext', sealed ? copies.length === 0 : true, detail)
4748
+ const copies = plaintextDbCopies()
4749
+ const detail = copies.length
4750
+ ? `${copies.length} plaintext cop(ies)${sealed ? ' after seal' : ' (documented DB copies; purge with \`advisers vault seal --remove\`)'}: ${copies.slice(0, 6).map((file) => basename(file)).join(', ')}`
4751
+ : 'none'
4752
+ // A sealed vault plus leftover plaintext copies is a leak (FAIL); with a
4753
+ // live plaintext DB these copies are documented backups (informational).
4754
+ check('plaintext', sealed ? copies.length === 0 : true, detail)
4755
+ }
4756
+ // P2-3 (0.2.1): probe resolvability instead of importing the office barrel
4757
+ // (222-573ms, and only needed to answer "is the peer installed?").
4758
+ let officeOk = false
4759
+ try { officeOk = Boolean(import.meta.resolve('advisers-office')) } catch {}
4760
+ if (!officeOk) officeOk = existsSync(new URL('../../office/dist/index.js', import.meta.url))
4761
+ check('office', officeOk, officeOk ? 'advisers-office resolvable' : 'npm i -g advisers-office@next, or ADVISERS_OFFICE_LOCAL=1 in checkout')
4762
+ check('policy', Boolean(StrictPolicyPack), StrictPolicyPack ? 'strict pack loaded' : 'policy pack missing')
4763
+ check('model', true, process.env.ADVISERS_API_KEY ? 'API key present (not tested)' : 'optional; ADVISERS_API_KEY not set')
4764
+ const ok = !rows.some((row) => !row.ok)
4765
+ if (asJson) {
4766
+ console.log(JSON.stringify({ ok, mode: 'diagnose', checks: rows }, null, 2))
4767
+ if (!ok) process.exitCode = 1
4768
+ return
4769
+ }
4770
+ for (const row of rows) console.log(`${row.ok ? 'PASS' : 'FAIL'} ${row.name} ${row.detail}`)
4771
+ if (!ok) process.exitCode = 1
4772
+ }
4773
+
4774
+ /* ---------------------------------------------------------------------------
4775
+ * 0.3.0 P0-D1: `doctor --repair` (recovery console).
4776
+ *
4777
+ * Registry (MVP, matching 04-0.3-research §4.2): lock / temp / wal / fts.
4778
+ * Invariants: dry-run is the default; apply takes the single-writer lock; a
4779
+ * safety backup of the live database is written BEFORE any mutation and a
4780
+ * backup failure aborts the whole repair (fail-closed); each run appends one
4781
+ * `doctor.repair` audit row and refreshes the audit anchor; the final step
4782
+ * re-verifies with quick_check + FTS integrity and exits non-zero on any
4783
+ * remaining failure. Audit reasons carry basenames only (no absolute paths).
4784
+ * `plaintext`/`backup` are intentionally not auto-repaired here: --only rejects
4785
+ * them (E_USAGE) instead of pretending to fix them.
4786
+ * ------------------------------------------------------------------------- */
4787
+
4788
+ const DOCTOR_REPAIR_ITEMS = ['lock', 'temp', 'wal', 'fts']
4789
+ const REPAIR_STALE_TEMP_MS = 60 * 60 * 1000
4790
+
4791
+ /** Parse/validate the --only list for doctor --repair. */
4792
+ function repairItemSelection(only) {
4793
+ if (only === undefined) return { ok: true, items: DOCTOR_REPAIR_ITEMS.slice() }
4794
+ const items = String(only).split(',').map((value) => value.trim()).filter(Boolean)
4795
+ if (!items.length) return { ok: false, error: '--only requires at least one item' }
4796
+ const unique = [...new Set(items)]
4797
+ const unknown = unique.filter((item) => !DOCTOR_REPAIR_ITEMS.includes(item))
4798
+ if (unknown.length) return { ok: false, error: `unsupported repair item(s): ${unknown.join(', ')} (supported: ${DOCTOR_REPAIR_ITEMS.join(', ')}) ' }`.trim() }
4799
+ return { ok: true, items: unique }
4800
+ }
4801
+
4802
+ function repairStamp() {
4803
+ return new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z')
4804
+ }
4805
+
4806
+ /**
4807
+ * Stale crash-residue scan (read-only): fs-safe temp files (".<name>.tmp-<pid>-…")
4808
+ * and staged sync-pull copies (".advisers-pull-verify-<pid>-…"). A live pid is
4809
+ * never touched; pull stages additionally must be older than the 1h stale window.
4810
+ */
4811
+ function scanRepairTempFiles() {
4812
+ const result = { candidates: [], errors: [] }
4813
+ for (const dir of [HOME, join(HOME, 'backups')]) {
4814
+ let names
4815
+ try { names = readdirSync(dir) } catch (error) { if (error?.code !== 'ENOENT') result.errors.push(`${basename(dir)}: ${error?.code ?? error?.message ?? error}`); continue }
4816
+ for (const name of names) {
4817
+ const file = join(dir, name)
4818
+ let info
4819
+ try { info = statSync(file) } catch { continue }
4820
+ if (!info.isFile()) continue
4821
+ let pid = null
4822
+ let stale = false
4823
+ if (name.startsWith('.advisers-pull-verify-')) {
4824
+ pid = Number.parseInt(name.slice('.advisers-pull-verify-'.length).split('-')[0], 10)
4825
+ stale = Date.now() - info.mtimeMs >= REPAIR_STALE_TEMP_MS
4826
+ } else {
4827
+ const match = /^\.(.+)\.tmp-(\d+)-/.exec(name)
4828
+ if (!match) continue
4829
+ pid = Number(match[2])
4830
+ stale = true
4831
+ }
4832
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) continue
4833
+ let alive = false
4834
+ try { process.kill(pid, 0); alive = true } catch (error) { alive = error?.code === 'EPERM' }
4835
+ if (alive || !stale) continue
4836
+ result.candidates.push({ path: file, name, pid, ageMs: Date.now() - info.mtimeMs })
4837
+ }
4838
+ }
4839
+ return result
4840
+ }
4841
+
4842
+ /** Cheap read-only FTS consistency probe (integrity-check itself needs a write). */
4843
+ function probeFtsReadOnly(store) {
4844
+ const probe = { ok: true, state: 'ok', issues: [] }
4845
+ try {
4846
+ const tables = new Set(store.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('turns_fts', 'summaries_fts')").all().map((row) => row.name))
4847
+ if (tables.size === 0) return { ok: true, state: 'degraded', issues: ['no FTS index table (search uses LIKE)'] }
4848
+ const triggers = new Set(store.db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger'").all().map((row) => row.name))
4849
+ for (const [table, source, needed] of [
4850
+ ['turns_fts', 'turns', ['turns_ai', 'turns_ad', 'turns_au']],
4851
+ ['summaries_fts', 'session_summaries', ['summaries_ai', 'summaries_ad', 'summaries_au']],
4852
+ ]) {
4853
+ if (!tables.has(table)) { probe.ok = false; probe.state = 'inconsistent'; probe.issues.push(`${table}: index table missing`); continue }
4854
+ const missing = needed.filter((name) => !triggers.has(name))
4855
+ if (missing.length) { probe.ok = false; probe.state = 'inconsistent'; probe.issues.push(`${table}: sync trigger(s) missing: ${missing.join(', ')}`) }
4856
+ try {
4857
+ const sourceCount = Number(store.db.prepare(`SELECT COUNT(*) AS n FROM ${source}`).get()?.n ?? 0)
4858
+ const indexCount = Number(store.db.prepare(`SELECT COUNT(*) AS n FROM ${table}_docsize`).get()?.n ?? 0)
4859
+ if (sourceCount !== indexCount) { probe.ok = false; probe.state = 'inconsistent'; probe.issues.push(`${table}: index has ${indexCount} row(s) for ${sourceCount} source row(s)`) }
4860
+ } catch (error) { probe.issues.push(`${table}: count probe failed (${error?.message ?? error})`) }
4861
+ }
4862
+ if (probe.issues.length && probe.ok) { probe.ok = false; probe.state = 'unknown' }
4863
+ } catch (error) { return { ok: false, state: 'unknown', issues: [String(error?.message ?? error)] } }
4864
+ return probe
4865
+ }
4866
+
4867
+ /** Read-only repair plan (never writes). */
4868
+ async function buildRepairPlan(items) {
4869
+ const plan = { ok: true, issues: [], blockers: [], errors: [], warnings: [] }
4870
+ if (items.includes('lock')) {
4871
+ try {
4872
+ const info = readInstanceLock(HOME)
4873
+ if (info) {
4874
+ if (info.record && !instanceLockIsStale(info)) {
4875
+ plan.blockers.push(`the writer lock is held by a live process (pid ${info.record.pid}${info.record.command ? ': ' + info.record.command : ''}); stop it before repairing`)
4876
+ } else if (instanceLockIsStale(info)) {
4877
+ plan.issues.push({ item: 'lock', action: 'remove the stale instance lock', detail: 'instance.lock' })
4878
+ }
4879
+ }
4880
+ } catch (error) { plan.errors.push(`cannot inspect the instance lock: ${error?.message ?? error}`) }
4881
+ }
4882
+ if (items.includes('temp')) {
4883
+ const temp = scanRepairTempFiles()
4884
+ for (const candidate of temp.candidates) plan.issues.push({ item: 'temp', action: 'remove a stale temp file left by a crashed process', detail: candidate.name })
4885
+ for (const error of temp.errors) plan.errors.push(error)
4886
+ }
4887
+ let walBad = false
4888
+ if (items.includes('wal')) {
4889
+ try {
4890
+ const wal = inspectWalStatus(DB)
4891
+ walBad = ['invalid', 'truncated', 'unreadable'].includes(String(wal?.status))
4892
+ if (walBad) plan.issues.push({ item: 'wal', action: `preserve and move aside the unusable WAL (status=${wal.status}${wal.reason ? ', ' + wal.reason : ''})`, detail: basename(wal.path) })
4893
+ } catch (error) { plan.errors.push(`cannot inspect the WAL: ${error?.message ?? error}`) }
4894
+ }
4895
+ if (items.includes('fts')) {
4896
+ try {
4897
+ if (existsSync(DB) && !walBad) {
4898
+ const readStore = openReadStoreLib(DB)
4899
+ try {
4900
+ const probe = probeFtsReadOnly(readStore)
4901
+ if (!probe.ok) plan.issues.push({ item: 'fts', action: `rebuild the FTS indexes (${probe.state})`, detail: probe.issues.slice(0, 2).join(' | ') })
4902
+ } finally { try { readStore.close() } catch {} }
4903
+ } else if (walBad) {
4904
+ plan.warnings.push('fts: detection deferred until the WAL item is repaired (read-only probe skipped)')
4905
+ }
4906
+ } catch (error) { plan.warnings.push(`fts: read-only probe skipped (${error?.code ?? error?.message ?? error})`) }
4907
+ }
4908
+ plan.ok = plan.blockers.length === 0 && plan.errors.length === 0
4909
+ return plan
4910
+ }
4911
+
4912
+ /** Safety backup before a repair mutation; a failure must abort the repair. */
4913
+ async function makeRepairBackup(walBad) {
4914
+ const lib = await loadBackup()
4915
+ const target = lib.backupPathFor({ home: HOME, tag: 'pre-repair' })
4916
+ let store = null
4917
+ if (!walBad) { try { store = openStore() } catch { store = null } }
4918
+ return lib.createBackup({
4919
+ dbPath: DB,
4920
+ targetPath: target,
4921
+ store,
4922
+ checkpoint: Boolean(store),
4923
+ verify: true,
4924
+ verifyChain: false,
4925
+ writeSha256: true,
4926
+ })
4927
+ }
4928
+
4929
+ /** Shared text/JSON reporting for a repair failure before any mutation. */
4930
+ function reportRepairFailure(result, asJson) {
4931
+ if (asJson) console.log(JSON.stringify({ ...result, ok: false }, null, 2))
4932
+ else {
4933
+ console.error(`repair: FAILED ${result.errors?.[0] ? '(' + result.errors[0] + ')' : ''}`)
4934
+ for (const error of result.errors ?? []) if (error !== result.errors[0]) console.error(` ${error}`)
4935
+ console.error(' nothing was changed; the live database is intact.')
4936
+ }
4937
+ process.exitCode = 1
4938
+ }
4939
+
4940
+ /**
4941
+ * `advisers doctor --repair` — plan (default) or apply the recovery actions.
4942
+ */
4943
+ async function doctorRepair(flags) {
4944
+ const asJson = flags.json === true
4945
+ if (flags['dry-run'] === true && flags.yes === true) return usageFail('--dry-run and --yes are mutually exclusive', DOCTOR_USAGE)
4946
+ const selection = repairItemSelection(flags.only)
4947
+ if (!selection.ok) return usageFail(selection.error, DOCTOR_USAGE)
4948
+ if (mode === 'json') return usageFail('doctor --repair requires the SQLite store (ADVISERS_STORE=sqlite)', DOCTOR_USAGE)
4949
+ const items = selection.items
4950
+ const apply = flags.yes === true && flags['dry-run'] !== true
4951
+ ensureHome()
4952
+ const plan = await buildRepairPlan(items)
4953
+ if (!apply) {
4954
+ const payload = { ok: plan.ok, mode: 'dry-run', only: items, issues: plan.issues, blockers: plan.blockers, errors: plan.errors, warnings: plan.warnings }
4955
+ if (asJson) console.log(JSON.stringify(payload, null, 2))
4956
+ else {
4957
+ console.log(`repair: dry-run (no changes) · only=${items.join(',')}`)
4958
+ if (!plan.issues.length && !plan.blockers.length) console.log('repair: nothing to do')
4959
+ for (const blocker of plan.blockers) console.error(`blocked: ${blocker}`)
4960
+ for (const issue of plan.issues) console.log(`plan: ${issue.item} — ${issue.action}${issue.detail ? ' [' + issue.detail + ']' : ''}`)
4961
+ for (const warning of plan.warnings) console.log(`warning: ${warning}`)
4962
+ for (const error of plan.errors) console.error(`error: ${error}`)
4963
+ if (plan.issues.length) console.log('next: advisers doctor --repair --yes (writes a safety backup, repairs, re-verifies and audits)')
4964
+ }
4965
+ if (!plan.ok) process.exitCode = 1
4966
+ return
4967
+ }
4968
+ if (!plan.issues.length && !plan.blockers.length && !plan.errors.length) {
4969
+ if (asJson) console.log(JSON.stringify({ ok: true, mode: 'apply', only: items, fixed: [], issues: [], note: 'nothing to do' }, null, 2))
4970
+ else console.log('repair: nothing to do (no selected issue detected)')
4971
+ return
4972
+ }
4973
+ const result = { ok: false, mode: 'apply', only: items, fixed: [], backup: null, errors: [], verify: null, audit: null, anchor: null }
4974
+ // 1) Stale lock first: the writer lock below would otherwise wait/fail.
4975
+ if (items.includes('lock')) {
4976
+ try {
4977
+ const info = readInstanceLock(HOME)
4978
+ if (info) {
4979
+ if (info.record && !instanceLockIsStale(info)) {
4980
+ result.errors.push(`the writer lock is held by a live process (pid ${info.record.pid}${info.record.command ? ': ' + info.record.command : ''}); stop it and retry`)
4981
+ return reportRepairFailure(result, asJson)
4982
+ }
4983
+ rmWithRetrySync(info.file)
4984
+ result.fixed.push('lock')
4985
+ }
4986
+ } catch (error) { result.errors.push(`lock: ${error?.message ?? error}`); return reportRepairFailure(result, asJson) }
4987
+ }
4988
+ try { ensureInstanceLock() } catch (error) { return reportMaintenanceFailure(error, asJson, 'repair') }
4989
+ // 2) Safety backup before opening/mutating the database (every repair item per
4990
+ // 04-0.3-research §4.2). Abort on failure: fail-closed, nothing is changed.
4991
+ if (existsSync(DB)) {
4992
+ const backup = await makeRepairBackup(plan.issues.some((issue) => issue.item === 'wal'))
4993
+ if (!backup.ok) {
4994
+ result.errors.push(...(backup.errors ?? [`safety backup failed (${backup.code ?? 'unknown'})`]))
4995
+ return reportRepairFailure(result, asJson)
4996
+ }
4997
+ result.backup = backup.path
4998
+ }
4999
+ // 3) WAL: preserve the unusable sidecar, keep the main database, never touch it.
5000
+ if (items.includes('wal') && plan.issues.some((issue) => issue.item === 'wal')) {
5001
+ try {
5002
+ const wal = inspectWalStatus(DB)
5003
+ if (['invalid', 'truncated', 'unreadable'].includes(String(wal?.status))) {
5004
+ const quarantined = `${DB}${WAL_CORRUPT_SUFFIX}${repairStamp()}`
5005
+ renameWithRetrySync(wal.path, quarantined)
5006
+ try { if (existsSync(DB + '-shm')) rmWithRetrySync(DB + '-shm') } catch {}
5007
+ result.fixed.push('wal')
5008
+ result.walQuarantined = basename(quarantined)
5009
+ }
5010
+ } catch (error) { result.errors.push(`wal: ${error?.message ?? error}`) }
5011
+ }
5012
+ // 4) Stale crash residue.
5013
+ if (items.includes('temp')) {
5014
+ const temp = scanRepairTempFiles()
5015
+ for (const candidate of temp.candidates) {
5016
+ try { rmWithRetrySync(candidate.path); result.fixed.push('temp') } catch (error) { result.errors.push(`temp ${candidate.name}: ${error?.message ?? error}`) }
5017
+ }
5018
+ }
5019
+ // 5) FTS via a writable store (integrity-check/rebuild need writes).
5020
+ let store = null
5021
+ try { store = openStore() } catch (error) { result.errors.push(`sqlite: ${error?.message ?? error}`) }
5022
+ if (store && items.includes('fts')) {
5023
+ try {
5024
+ const before = store.verifyFtsIntegrity()
5025
+ if (!before.ok) {
5026
+ store.db.exec('BEGIN IMMEDIATE')
5027
+ try {
5028
+ store._setupFts()
5029
+ store.db.exec('COMMIT')
5030
+ } catch (error) {
5031
+ try { store.db.exec('ROLLBACK') } catch {}
5032
+ throw error
5033
+ }
5034
+ const after = store.verifyFtsIntegrity()
5035
+ if (!after.ok) throw new Error(`FTS indexes still inconsistent after the rebuild: ${(after.errors ?? []).join('; ')}`)
5036
+ store._ftsBroken = false
5037
+ store.ftsIntegrityWarning = null
5038
+ result.fixed.push('fts')
5039
+ }
5040
+ } catch (error) { result.errors.push(`fts: ${error?.message ?? error}`) }
5041
+ }
5042
+ // 6) Re-verify, audit, refresh the anchor.
5043
+ try {
5044
+ const finalStore = store ?? openStore()
5045
+ const verifyReport = finalStore.integrityReport({ quickCheck: true, fts: true })
5046
+ const auditCheck = finalStore.verifyAudit()
5047
+ const fixedNow = [...new Set(result.fixed)]
5048
+ let auditRow = null
5049
+ if (fixedNow.length) {
5050
+ auditRow = finalStore.appendAudit({
5051
+ actor: 'local',
5052
+ action: 'doctor.repair',
5053
+ allowed: result.errors.length === 0,
5054
+ reason: `only=${items.join('+')};fixed=${fixedNow.join('+')};backup=${result.backup ? basename(result.backup) : 'none'}`,
5055
+ })
5056
+ }
5057
+ let anchorWrite = null
5058
+ if (auditRow) {
5059
+ const anchorLib = await loadAuditAnchor()
5060
+ anchorWrite = anchorLib.writeAuditAnchor({ home: HOME, store: finalStore, generator: `advisers/${VERSION}` })
5061
+ }
5062
+ result.audit = auditRow
5063
+ result.anchor = anchorWrite ? { ok: anchorWrite.ok === true, code: anchorWrite.code ?? null, path: anchorWrite.path ?? null, count: anchorWrite.anchor?.count ?? null } : null
5064
+ result.verify = {
5065
+ quickCheck: verifyReport.quickCheck?.verdict ?? null,
5066
+ fts: verifyReport.fts?.state ?? null,
5067
+ audit: { ok: auditCheck.ok === true, count: auditCheck.count ?? 0 },
5068
+ }
5069
+ result.ok = result.errors.length === 0 && verifyReport.ok === true && auditCheck.ok === true && (anchorWrite === null || anchorWrite.ok === true) && result.fixed.length > 0
5070
+ } catch (error) {
5071
+ result.errors.push(`verification: ${error?.message ?? error}`)
5072
+ result.ok = false
2991
5073
  }
2992
- // P2-3 (0.2.1): probe resolvability instead of importing the office barrel
2993
- // (222-573ms, and only needed to answer "is the peer installed?").
2994
- let officeOk = false
2995
- try { officeOk = Boolean(import.meta.resolve('advisers-office')) } catch {}
2996
- if (!officeOk) officeOk = existsSync(new URL('../../office/dist/index.js', import.meta.url))
2997
- check('office', officeOk, officeOk ? 'advisers-office resolvable' : 'npm i -g advisers-office@next, or ADVISERS_OFFICE_LOCAL=1 in checkout')
2998
- check('policy', Boolean(StrictPolicyPack), StrictPolicyPack ? 'strict pack loaded' : 'policy pack missing')
2999
- check('model', true, process.env.ADVISERS_API_KEY ? 'API key present (not tested)' : 'optional; ADVISERS_API_KEY not set')
3000
- for (const row of rows) console.log(`${row.ok ? 'PASS' : 'FAIL'} ${row.name} ${row.detail}`)
3001
- if (rows.some((r) => !r.ok)) process.exitCode = 1
5074
+ if (asJson) console.log(JSON.stringify(result, null, 2))
5075
+ else {
5076
+ console.log(`repair: ${result.ok ? 'done' : 'INCOMPLETE'} · fixed=${[...new Set(result.fixed)].join(',') || 'none'}${result.backup ? ' · backup=' + result.backup : ''}`)
5077
+ if (result.verify) {
5078
+ console.log(`verify: quick_check=${result.verify.quickCheck ?? '?'} fts=${result.verify.fts ?? '?'} audit=${result.verify.audit.ok ? 'verified(' + result.verify.audit.count + ')' : 'BROKEN'}${result.anchor ? ' anchor=' + (result.anchor.ok ? 'written' : 'FAIL ' + result.anchor.code) : ''}`)
5079
+ }
5080
+ for (const warning of plan.warnings) console.log(`warning: ${warning}`)
5081
+ for (const error of result.errors) console.error(`error: ${error}`)
5082
+ if (result.ok) console.log('next: advisers doctor --check-db')
5083
+ }
5084
+ if (!result.ok) process.exitCode = 1
3002
5085
  }
3003
5086
 
3004
5087
  function init() {
@@ -3023,6 +5106,9 @@ function printStatus(asJson = false) {
3023
5106
  store: mode === 'sqlite' ? { type: 'sqlite', path: DB } : { type: mode, path: STATE },
3024
5107
  model: modelLabel(),
3025
5108
  soul: existsSync(SOUL) ? 'present' : 'not initialized',
5109
+ // Additive 0.3.0 discovery field: one call tells a consumer which contract
5110
+ // versions this CLI implements (contracts/versions-v1.json discovery.expected).
5111
+ contracts: { ...CONTRACTS_DISCOVERY },
3026
5112
  }
3027
5113
  if (mode === 'json') {
3028
5114
  // Legacy JSON store: the snapshot is small, keep the historical behaviour.
@@ -3033,6 +5119,9 @@ function printStatus(asJson = false) {
3033
5119
  data.links = ledger.listLinks().length
3034
5120
  data.sessions = 0
3035
5121
  data.deliveries = 0
5122
+ // 0.3.0 additive: the JSON store carries no customer tables.
5123
+ data.clients = 0
5124
+ data.projects = 0
3036
5125
  } else {
3037
5126
  // P1-2 (0.2.2): COUNT-only status. The old path loaded all 9 tables just to
3038
5127
  // count four of them (664ms / 352MB RSS at 50k rows in the round-2 audit).
@@ -3048,6 +5137,12 @@ function printStatus(asJson = false) {
3048
5137
  links: store.countLinks({ excludeRejected: true }),
3049
5138
  sessions: store.countSessions(),
3050
5139
  deliveries: store.countDeliveries(),
5140
+ // 0.3.0 additive: live customer/project counts. Additive keys only, so the
5141
+ // frozen status v1 shape keeps its meaning (contracts/cli/status-v1.json).
5142
+ // The store's customer CRUD has no count helper; these are COUNT-only
5143
+ // queries on the same read snapshot (no row materialisation).
5144
+ clients: Number(store.db.prepare("SELECT COUNT(*) AS n FROM clients WHERE status = 'active' AND deleted_at IS NULL").get()?.n ?? 0),
5145
+ projects: Number(store.db.prepare("SELECT COUNT(*) AS n FROM projects WHERE status = 'active' AND deleted_at IS NULL").get()?.n ?? 0),
3051
5146
  usage: store.sumModelUsage(),
3052
5147
  }))
3053
5148
  data.matters = counts.matters
@@ -3056,6 +5151,8 @@ function printStatus(asJson = false) {
3056
5151
  data.links = counts.links
3057
5152
  data.sessions = counts.sessions
3058
5153
  data.deliveries = counts.deliveries
5154
+ data.clients = counts.clients
5155
+ data.projects = counts.projects
3059
5156
  const usage = counts.usage
3060
5157
  if (usage.calls) data.modelUsage = usage
3061
5158
  }
@@ -3072,6 +5169,8 @@ function printStatus(asJson = false) {
3072
5169
  console.log(`links ${data.links}`)
3073
5170
  if (data.sessions != null) console.log(`sessions ${data.sessions}`)
3074
5171
  if (data.deliveries != null) console.log(`deliveries ${data.deliveries}`)
5172
+ if (data.clients != null) console.log(`clients ${data.clients}`)
5173
+ if (data.projects != null) console.log(`projects ${data.projects}`)
3075
5174
  if (data.modelUsage) console.log(`model calls ${data.modelUsage.calls} · tokens ${data.modelUsage.total_tokens} · reasoning ${data.modelUsage.reasoning_tokens}`)
3076
5175
  console.log(`soul ${data.soul}`)
3077
5176
  }
@@ -3268,7 +5367,11 @@ async function runTurn(options) {
3268
5367
  }
3269
5368
  }
3270
5369
 
3271
- async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [], allowPaths = [] }) {
5370
+ async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [], allowPaths = [], renderWidth = null }) {
5371
+ // 0.3.0 Wave 3 (plan 26 §4.1): internal process lines ([tool]/[attach]/[compact])
5372
+ // are hidden by default; ADVISERS_PROGRESS=1 (or /debug) is the explicit
5373
+ // opt-in. Results, confirmations and failures are never gated.
5374
+ const showProgress = debug || process.env.ADVISERS_PROGRESS === '1'
3272
5375
  const result = await runtime.ingest({
3273
5376
  linkId: 'cli',
3274
5377
  accountId: 'local',
@@ -3316,9 +5419,11 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
3316
5419
  const attachment = await attachmentLib.extractAttachment(file, { cwd: process.cwd() })
3317
5420
  extracted.push(attachment)
3318
5421
  if (attachment?.text) untrusted.push({ label: 'attachment:' + attachment.name, text: attachment.text })
3319
- console.log(`[attach] ${attachment.name} (${attachment.text.length} chars${attachment.truncated ? ', truncated' : ''})`)
5422
+ if (showProgress) console.log(`[attach] ${sanitizeConsoleText(attachment.name, { max: 200 })}`)
3320
5423
  } catch (error) {
3321
- console.log(`[attach] ${file}: ${error.message}`)
5424
+ // An unreadable attachment is a failure, not process noise: keep it
5425
+ // visible even when internal progress is hidden; sanitise path/message.
5426
+ console.error(sanitizeConsoleText('附件无法读取:' + file + ':' + (error?.message ?? error), { max: 2000 }))
3322
5427
  }
3323
5428
  }
3324
5429
  const agentText = text
@@ -3353,7 +5458,7 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
3353
5458
  })
3354
5459
  const prompt = pins ? `${context.prompt}\n<session-pins>\n${pins}\n</session-pins>` : context.prompt
3355
5460
  const fitted = fitHistory({ system: prompt, summary: history.summary, history: history.turns, current: agentText, maxTokens: Number(process.env.ADVISERS_CONTEXT_TOKENS || 12000) })
3356
- if (fitted.trimmed) console.log(`[compact] 裁剪 ${fitted.trimmed} 轮旧历史`)
5461
+ if (fitted.trimmed && showProgress) console.log(`[compact] 裁剪 ${fitted.trimmed} 轮旧历史`)
3357
5462
  const { runAgent } = await loadAgent()
3358
5463
  // 0.2.3 Wave 1 default workspace: agent file tools are confined to a 0700
3359
5464
  // directory under ADVISERS_HOME, not to whatever directory the CLI was
@@ -3384,7 +5489,7 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
3384
5489
  force: process.env.ADVISERS_FORCE === '1',
3385
5490
  confirm,
3386
5491
  effort: process.env.ADVISERS_THINKING_EFFORT,
3387
- onTool: (name) => { if (debug || process.env.ADVISERS_PROGRESS !== '0') console.log(`[tool] ${name}`) },
5492
+ onTool: (name) => { if (showProgress) console.log('[tool] ' + sanitizeConsoleText(name, { max: 120 })) },
3388
5493
  onToolAction: auditToolAction,
3389
5494
  })
3390
5495
  // 0.2.3 Wave 1: consume the structured warnings (they used to be discarded)
@@ -3403,20 +5508,30 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
3403
5508
  recordTurn(conversationId, 'user', text)
3404
5509
  recordTurn(conversationId, 'assistant', reply || '')
3405
5510
  await maybeSummarize(conversationId, { apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL, ledger })
3406
- if (reply) console.log(reply)
5511
+ if (reply) {
5512
+ // 0.3.0 Wave 3: the REPL renders model output through the display kernel -
5513
+ // strip terminal control/bidi from the model, then fold at the display width
5514
+ // (CJK counts as two columns) so a long Chinese paragraph cannot mangle the
5515
+ // terminal. chat/one-shot keeps its historical bytes (renderWidth is null).
5516
+ if (Number.isInteger(renderWidth) && renderWidth > 0) {
5517
+ const tuiKernel = await loadTui()
5518
+ const display = tuiKernel.sanitizeDisplay(reply, { expandTabs: true })
5519
+ for (const line of tuiKernel.wrap(display, renderWidth)) console.log(line)
5520
+ } else console.log(reply)
5521
+ }
3407
5522
  const uniqueArtifacts = [...new Set(artifacts)]
3408
5523
  if (uniqueArtifacts.length) {
3409
5524
  for (const file of uniqueArtifacts) {
3410
5525
  let bytes = 0
3411
5526
  try { bytes = statSync(file).size } catch {}
3412
- console.log(`[完成] ${text.replace(/\s+/g, ' ').slice(0, 48)} -> ${file}(${bytes} B)`)
5527
+ console.log(`[完成] ${sanitizeConsoleText(text.replace(/\s+/g, ' ').slice(0, 48), { max: 48 })} -> ${sanitizeConsoleText(file, { max: 240 })}(${bytes} B)`)
3413
5528
  }
3414
5529
  const structural = toolLog.filter((t) => t.name === 'office_build' || t.name === 'office_template')
3415
5530
  if (structural.length && structural.every((t) => t.ok && !(t.payload?.missing?.length))) console.log('校验:结构通过(内容未逐字核对)')
3416
5531
  else if (structural.length) console.log('校验:未通过,文件保留但未记成完成')
3417
5532
  else console.log('校验:文本已保存')
3418
5533
  console.log('下一步:打开确认;要改哪段直接说')
3419
- for (const file of uniqueArtifacts) console.log(`[file] ${file}`)
5534
+ for (const file of uniqueArtifacts) console.log('[file] ' + sanitizeConsoleText(file, { max: 240 }))
3420
5535
  }
3421
5536
  if (artifacts.length) {
3422
5537
  try {
@@ -3503,6 +5618,9 @@ async function chat(args) {
3503
5618
  }
3504
5619
 
3505
5620
  async function repl({ allowPaths = [] } = {}) {
5621
+ const tuiKernel = await loadTui()
5622
+ const policy = await getOutputPolicy()
5623
+ const width = tuiKernel.clampColumns(process.stdout.columns)
3506
5624
  const readline = await import('node:readline/promises')
3507
5625
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout, historySize: 100 })
3508
5626
  const ledger = loadLedger()
@@ -3511,16 +5629,37 @@ async function repl({ allowPaths = [] } = {}) {
3511
5629
  let debug = process.env.ADVISERS_DEBUG === '1'
3512
5630
  let pendingFiles = []
3513
5631
  let lastTask
3514
- console.log('advisers · local')
3515
- if (process.env.ADVISERS_DEBUG === '1') {
3516
- console.log(`model: ${modelLabel()}`)
3517
- console.log(`home: ${HOME}`)
5632
+ // 0.3.0 Wave 3 (plan 26 §4.4/§6.1): one status line from the render kernel
5633
+ // replaces the "advisers · local" banner. Counts come from the already-loaded
5634
+ // ledger, so the status line costs no extra store read.
5635
+ const nowMs = Date.now()
5636
+ const today = localDayOf(nowMs)
5637
+ let dueToday = 0
5638
+ let overdueCount = 0
5639
+ for (const commitment of ledger.openCommitments()) {
5640
+ if (!commitment.dueAt) continue
5641
+ const ms = Date.parse(commitment.dueAt)
5642
+ if (Number.isNaN(ms)) continue
5643
+ const day = localDayOf(ms)
5644
+ if (ms < nowMs && day !== today) overdueCount += 1
5645
+ else if (day === today) dueToday += 1
5646
+ }
5647
+ const localMode = !process.env.ADVISERS_API_KEY || process.env.ADVISERS_NO_MODEL === '1'
5648
+ console.log(tuiKernel.renderStatus({
5649
+ kind: 'idle',
5650
+ today: { due: dueToday, overdue: overdueCount },
5651
+ local: localMode,
5652
+ model: localMode ? null : (process.env.ADVISERS_MODEL || 'deepseek-flash'),
5653
+ hint: '/help',
5654
+ }, { width, color: policy.color, accessible: policy.accessible }))
5655
+ if (debug) {
5656
+ console.log('model: ' + sanitizeConsoleText(modelLabel(), { max: 240 }))
5657
+ console.log('home: ' + sanitizeConsoleText(HOME, { max: 240 }))
3518
5658
  }
3519
5659
  try {
3520
5660
  const latest = dbStore()?.listSessions(1)[0]
3521
5661
  await printOpening(latest?.conversationId ?? conversationId)
3522
5662
  } catch {}
3523
- console.log('/help for commands, /quit to leave')
3524
5663
 
3525
5664
  const runTask = async (taskText, files = [], { skipPlan = false } = {}) => {
3526
5665
  const brief = runtime.brief(taskText)
@@ -3535,7 +5674,7 @@ async function repl({ allowPaths = [] } = {}) {
3535
5674
  }
3536
5675
  lastTask = { text: taskText, files: [...files] }
3537
5676
  try {
3538
- const question = await runTurn({ runtime, ledger, text: taskText, conversationId, debug, confirm, attachments: files, allowPaths })
5677
+ const question = await runTurn({ runtime, ledger, text: taskText, conversationId, debug, confirm, attachments: files, allowPaths, renderWidth: width })
3539
5678
  saveLedger(ledger)
3540
5679
  pendingFiles = []
3541
5680
  if (question) {
@@ -3546,13 +5685,21 @@ async function repl({ allowPaths = [] } = {}) {
3546
5685
  return
3547
5686
  }
3548
5687
  if (answer.trim()) {
3549
- await runTurn({ runtime, ledger, text: `${taskText}\n补充:${answer.trim()}`, conversationId, debug, confirm, attachments: files, allowPaths })
5688
+ await runTurn({ runtime, ledger, text: `${taskText}\n补充:${answer.trim()}`, conversationId, debug, confirm, attachments: files, allowPaths, renderWidth: width })
3550
5689
  saveLedger(ledger)
3551
5690
  }
3552
5691
  }
3553
5692
  } catch (error) {
3554
- console.error(`[没做成] ${error.message}`)
3555
- console.error('已保留:任务和会话;没有丢文件。下一步:/retry 重试。')
5693
+ // 0.3.0 Wave 3: the failure block goes through the render kernel so it has
5694
+ // the stable prefix/code shape, is sanitised and wraps at the display width.
5695
+ const lines = tuiKernel.renderError({
5696
+ title: '任务失败',
5697
+ reason: friendlyError(error),
5698
+ kept: '任务和会话;没有丢文件',
5699
+ next: '/retry 重试',
5700
+ code: typeof error?.code === 'string' ? error.code : undefined,
5701
+ }, { width, color: policy.color, accessible: policy.accessible })
5702
+ for (const line of lines) console.error(line)
3556
5703
  }
3557
5704
  }
3558
5705
 
@@ -3870,11 +6017,42 @@ async function exportLedger(all = false, options = {}) {
3870
6017
  store = readStoreOrExit()
3871
6018
  ledger = store.read(() => store.load())
3872
6019
  }
6020
+ // 0.3.0 P0-L2: `export --all` carries a top-level audit anchor so an exported
6021
+ // snapshot can be compared against the live audit tail later. The anchor is a
6022
+ // local HMAC checkpoint (never third-party attestation) and is built from the
6023
+ // same read snapshot the export uses.
6024
+ let builtAnchor = null
6025
+ if (all && mode !== 'json' && store) {
6026
+ try {
6027
+ const anchorLib = await loadAuditAnchor()
6028
+ builtAnchor = anchorLib.buildAuditAnchorForStore({ store, home: HOME, generator: `advisers/${VERSION}` })
6029
+ if (!builtAnchor.ok) {
6030
+ const detail = (builtAnchor.errors ?? []).join('; ')
6031
+ if (options.out) console.error(`warning: audit anchor unavailable for this export (${builtAnchor.code ?? 'unknown'}): ${detail}`)
6032
+ }
6033
+ } catch (error) {
6034
+ if (options.out) console.error(`warning: audit anchor unavailable for this export: ${error?.message ?? error}`)
6035
+ }
6036
+ }
3873
6037
  const payload = all ? (() => {
3874
- const tables = ['sessions', 'turns', 'session_summaries', 'summary_versions', 'deliveries', 'nudges', 'task_runs', 'audit', 'memory_candidates', 'permit_consumed']
3875
- const data = {}
3876
- for (const table of tables) data[table] = store ? store.db.prepare(`SELECT * FROM ${table}`).all() : []
3877
- return { version: VERSION, exportedAt: now(), ledger, data }
6038
+ // 0.3.0: DATA_TABLES is the single, store-owned list (the v21 customer
6039
+ // tables included). Do not hand-maintain a second list here: a table that
6040
+ // was missing from this list used to be invisible until an import dropped
6041
+ // it, which is exactly the "export succeeds, import loses data" bug.
6042
+ const data = store && typeof store.exportDataTables === 'function'
6043
+ ? store.exportDataTables()
6044
+ : Object.fromEntries(DATA_TABLES.map((table) => [table, []]))
6045
+ return {
6046
+ version: VERSION,
6047
+ // Additive 0.3.0: physical schema of the source database. import --replace
6048
+ // refuses an export written by a newer CLI (fail closed) instead of
6049
+ // dropping columns it does not understand; legacy exports omit the key.
6050
+ ...(store ? { schemaVersion: store.schemaVersion() } : {}),
6051
+ exportedAt: now(),
6052
+ ledger,
6053
+ data,
6054
+ auditAnchor: builtAnchor?.ok ? builtAnchor.anchor : null,
6055
+ }
3878
6056
  })() : ledger
3879
6057
  let text = JSON.stringify(payload, null, 2)
3880
6058
  if (options.encrypted) {
@@ -3895,8 +6073,167 @@ async function exportLedger(all = false, options = {}) {
3895
6073
  return
3896
6074
  }
3897
6075
  store?.appendAudit({ actor: 'local', action: options.encrypted ? 'export.encrypted' : 'export', allowed: true, reason: basename(options.out) })
3898
- console.log(`wrote ${options.out}${options.encrypted ? ' (AES-256-GCM)' : ''}`)
3899
- } else console.log(text)
6076
+ // Refresh $ADVISERS_HOME/audit-anchor.json after the extra audit row (P0-L2).
6077
+ if (all && mode !== 'json' && store) {
6078
+ try {
6079
+ const anchorLib = await loadAuditAnchor()
6080
+ const written = anchorLib.writeAuditAnchor({ home: HOME, store, generator: `advisers/${VERSION}` })
6081
+ if (!written.ok) console.error(`warning: could not refresh the audit anchor (${written.code ?? 'unknown'})`)
6082
+ } catch (error) { console.error(`warning: could not refresh the audit anchor: ${error?.message ?? error}`) }
6083
+ }
6084
+ console.log(`wrote ${options.out}${options.encrypted ? ' (AES-256-GCM)' : ''}${all && builtAnchor?.ok ? ' + audit anchor' : ''}`)
6085
+ } else {
6086
+ console.log(text)
6087
+ // `export --all` also refreshes the local anchor baseline (stdout stays pure
6088
+ // JSON); a failure is reported only for the file variant above.
6089
+ if (all && builtAnchor?.ok) {
6090
+ try {
6091
+ const anchorLib = await loadAuditAnchor()
6092
+ anchorLib.writeAuditAnchor({ home: HOME, head: builtAnchor.head, generator: `advisers/${VERSION}` })
6093
+ } catch {}
6094
+ }
6095
+ }
6096
+ }
6097
+
6098
+ /* ---------------------------------------------------------------------------
6099
+ * 0.3.0 import --replace parity for the SQLite-only customer tables.
6100
+ *
6101
+ * export --all carries clients/projects/client_notes; import restores them in
6102
+ * the SAME transaction as the ledger, so a failed import changes nothing. The
6103
+ * matter ownership (which already travels in the wire snapshot) and the restored
6104
+ * entities are validated against each other, and any delivery lineage snapshot
6105
+ * that would dangle is re-pointed or cleared and counted. The audit table is
6106
+ * deliberately NOT replaced: the local hash chain is signed with this HOME's
6107
+ * audit key, so importing another HOME's rows would fail verification.
6108
+ * ------------------------------------------------------------------------- */
6109
+ const CUSTOMER_IMPORT_TABLES = ['clients', 'projects', 'client_notes']
6110
+ const CUSTOMER_IMPORT_MAX_ROWS = 20000
6111
+
6112
+ function importDataError(message) {
6113
+ return customerError('E_JSON_INVALID', message)
6114
+ }
6115
+
6116
+ /** Validate the shape of payload.data before any write happens. */
6117
+ function prepareCustomerImport(payloadData) {
6118
+ if (!payloadData || typeof payloadData !== 'object' || Array.isArray(payloadData)) return null
6119
+ const present = CUSTOMER_IMPORT_TABLES.filter((table) => Object.prototype.hasOwnProperty.call(payloadData, table))
6120
+ if (!present.length) return null
6121
+ const tables = {}
6122
+ for (const table of CUSTOMER_IMPORT_TABLES) {
6123
+ const rows = Object.prototype.hasOwnProperty.call(payloadData, table) ? payloadData[table] : []
6124
+ if (!Array.isArray(rows)) throw importDataError('import data.' + table + ' must be an array')
6125
+ if (rows.length > CUSTOMER_IMPORT_MAX_ROWS) throw importDataError('import data.' + table + ' has too many rows (max ' + CUSTOMER_IMPORT_MAX_ROWS + ')')
6126
+ for (let index = 0; index < rows.length; index += 1) {
6127
+ const row = rows[index]
6128
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw importDataError('import data.' + table + '[' + index + '] must be an object')
6129
+ }
6130
+ tables[table] = rows
6131
+ }
6132
+ return tables
6133
+ }
6134
+
6135
+ /** Column metadata of one table (the table name comes from a fixed list). */
6136
+ function customerTableColumns(store, table) {
6137
+ return store.db.prepare('PRAGMA table_info(' + table + ')').all().map((row) => ({
6138
+ name: row.name,
6139
+ notnull: Number(row.notnull) === 1,
6140
+ hasDefault: row.dflt_value !== null,
6141
+ pk: Number(row.pk) > 0,
6142
+ }))
6143
+ }
6144
+
6145
+ /** Wholesale replace one customer table: strict container, no unknown columns. */
6146
+ function replaceCustomerTable(store, table, rows) {
6147
+ const columns = customerTableColumns(store, table)
6148
+ const allowed = new Map(columns.map((column) => [column.name, column]))
6149
+ const required = columns.filter((column) => column.notnull && !column.hasDefault && !column.pk).map((column) => column.name)
6150
+ store.db.prepare('DELETE FROM ' + table).run()
6151
+ for (let index = 0; index < rows.length; index += 1) {
6152
+ const row = rows[index]
6153
+ const names = []
6154
+ for (const name of Object.keys(row)) {
6155
+ if (!allowed.has(name)) throw importDataError('import data.' + table + '[' + index + '] has unknown column ' + name)
6156
+ names.push(name)
6157
+ }
6158
+ for (const name of required) {
6159
+ if (!Object.prototype.hasOwnProperty.call(row, name)) throw importDataError('import data.' + table + '[' + index + '] is missing column ' + name)
6160
+ }
6161
+ if (!names.length) throw importDataError('import data.' + table + '[' + index + '] has no columns')
6162
+ store.db.prepare('INSERT INTO ' + table + ' (' + names.join(',') + ') VALUES (' + names.map(() => '?').join(',') + ')')
6163
+ .run(...names.map((name) => row[name] === undefined ? null : row[name]))
6164
+ }
6165
+ return rows.length
6166
+ }
6167
+
6168
+ /**
6169
+ * Restore the customer tables and keep the database referentially coherent.
6170
+ * Runs INSIDE the import transaction: any throw rolls the ledger + tables back.
6171
+ */
6172
+ function applyCustomerImport(store, tables) {
6173
+ const clientCount = replaceCustomerTable(store, 'clients', tables.clients)
6174
+ const projectCount = replaceCustomerTable(store, 'projects', tables.projects)
6175
+ const noteCount = replaceCustomerTable(store, 'client_notes', tables.client_notes)
6176
+ const clientRows = new Map(store.db.prepare('SELECT id FROM clients').all().map((row) => [row.id, true]))
6177
+ const projectRows = new Map(store.db.prepare('SELECT id, client_id FROM projects').all().map((row) => [row.id, row]))
6178
+ const matterRows = new Map(store.db.prepare('SELECT id, client_id, project_id FROM matters').all().map((row) => [row.id, row]))
6179
+ for (const project of projectRows.values()) {
6180
+ if (!clientRows.has(project.client_id)) throw importDataError('import data.projects references a missing client: ' + String(project.client_id))
6181
+ }
6182
+ for (const matter of matterRows.values()) {
6183
+ if (matter.client_id !== null && matter.client_id !== undefined && !clientRows.has(matter.client_id)) {
6184
+ throw importDataError('import ledger matter ' + matter.id + ' references a missing client')
6185
+ }
6186
+ if (matter.project_id !== null && matter.project_id !== undefined) {
6187
+ const project = projectRows.get(matter.project_id)
6188
+ if (!project) throw importDataError('import ledger matter ' + matter.id + ' references a missing project')
6189
+ if (matter.client_id === null || matter.client_id === undefined || project.client_id !== matter.client_id) {
6190
+ throw importDataError('import ledger matter ' + matter.id + ' belongs to a project of another client')
6191
+ }
6192
+ }
6193
+ }
6194
+ for (const note of store.db.prepare('SELECT id, client_id, project_id, matter_id FROM client_notes').all()) {
6195
+ if (!clientRows.has(note.client_id)) throw importDataError('import data.client_notes references a missing client')
6196
+ if (note.project_id !== null && note.project_id !== undefined) {
6197
+ const project = projectRows.get(note.project_id)
6198
+ if (!project || project.client_id !== note.client_id) throw importDataError('import data.client_notes references a project of another client')
6199
+ }
6200
+ if (note.matter_id !== null && note.matter_id !== undefined) {
6201
+ const matter = matterRows.get(note.matter_id)
6202
+ if (!matter) throw importDataError('import data.client_notes references a missing matter')
6203
+ if (matter.client_id !== null && matter.client_id !== undefined && matter.client_id !== note.client_id) {
6204
+ throw importDataError('import data.client_notes references a matter of another client')
6205
+ }
6206
+ }
6207
+ }
6208
+ // Delivery lineage snapshots may point at entities this HOME never had:
6209
+ // re-point when a project/matter still resolves, otherwise clear the snapshot
6210
+ // (never keep a dangling id) and report the reconciled row count.
6211
+ let reconciledDeliveries = 0
6212
+ for (const delivery of store.db.prepare('SELECT id, client_id, project_id, matter_id FROM deliveries').all()) {
6213
+ let clientId = delivery.client_id ?? null
6214
+ let projectId = delivery.project_id ?? null
6215
+ const before = String(clientId) + ':' + String(projectId)
6216
+ if (projectId !== null) {
6217
+ const project = projectRows.get(projectId)
6218
+ if (!project) { clientId = null; projectId = null }
6219
+ else clientId = project.client_id
6220
+ } else if (clientId !== null && !clientRows.has(clientId)) {
6221
+ clientId = null
6222
+ }
6223
+ if (projectId === null && clientId === null && delivery.matter_id !== null && delivery.matter_id !== undefined) {
6224
+ const matter = matterRows.get(delivery.matter_id)
6225
+ if (matter && matter.client_id !== null && matter.client_id !== undefined && clientRows.has(matter.client_id)) {
6226
+ clientId = matter.client_id
6227
+ const project = matter.project_id === null || matter.project_id === undefined ? undefined : projectRows.get(matter.project_id)
6228
+ if (project && project.client_id === clientId) projectId = project.id
6229
+ }
6230
+ }
6231
+ if (before !== String(clientId) + ':' + String(projectId)) {
6232
+ store.db.prepare('UPDATE deliveries SET client_id = ?, project_id = ? WHERE id = ?').run(clientId, projectId, delivery.id)
6233
+ reconciledDeliveries += 1
6234
+ }
6235
+ }
6236
+ return { clients: clientCount, projects: projectCount, clientNotes: noteCount, reconciledDeliveries: reconciledDeliveries }
3900
6237
  }
3901
6238
 
3902
6239
  async function importLedger(file, { replace = false } = {}) {
@@ -3914,8 +6251,50 @@ async function importLedger(file, { replace = false } = {}) {
3914
6251
  } catch (error) { console.error(`import failed: ${error.message}`); process.exitCode = 1; return }
3915
6252
  const data = payload?.ledger ?? payload
3916
6253
  if (!data || !Array.isArray(data.matters)) { console.error('import file does not contain an Advisers ledger'); process.exitCode = 1; return }
6254
+ // 0.3.0: an export --all records its physical schema version. A newer database
6255
+ // must be imported by a newer CLI (same fail-closed rule as E_SCHEMA_NEWER on
6256
+ // open); a legacy export without the key is accepted exactly as before.
6257
+ if (payload && typeof payload === 'object' && payload.schemaVersion !== undefined) {
6258
+ const incomingSchema = payload.schemaVersion
6259
+ if (!Number.isInteger(incomingSchema) || incomingSchema < 0) {
6260
+ console.error('import failed: E_JSON_INVALID: export schemaVersion must be a non-negative integer')
6261
+ process.exitCode = 1
6262
+ return
6263
+ }
6264
+ if (incomingSchema > SCHEMA_VERSION) {
6265
+ console.error('import failed: E_SCHEMA_NEWER: the export uses database schema v' + incomingSchema + ' but this CLI expects v' + SCHEMA_VERSION + '; upgrade advisers first. The ledger was NOT replaced.')
6266
+ process.exitCode = 1
6267
+ return
6268
+ }
6269
+ }
6270
+ // Validate the customer-table payload shape BEFORE any write; the restore
6271
+ // itself runs inside the import transaction and rolls back on a bad reference.
6272
+ let customerImport = null
6273
+ try { customerImport = prepareCustomerImport(payload?.data) } catch (error) {
6274
+ console.error('import failed: ' + error.message)
6275
+ process.exitCode = 1
6276
+ return
6277
+ }
3917
6278
  await requireTosReaccept({ scope: 'import', subject: basename(file), action: 'import --replace' })
3918
6279
  ensureHome()
6280
+ // 0.3.0 Wave 3 (plan 26 §4.5/§10.5): --replace is the confirmation, so state
6281
+ // the irreversible consequence and the recovery copy BEFORE any write happens.
6282
+ const incoming = {
6283
+ matters: data.matters.length,
6284
+ commitments: Array.isArray(data.commitments) ? data.commitments.length : 0,
6285
+ facts: Array.isArray(data.facts) ? data.facts.length : 0,
6286
+ preferences: Array.isArray(data.preferences) ? data.preferences.length : 0,
6287
+ }
6288
+ if (customerImport) {
6289
+ incoming.clients = customerImport.clients.length
6290
+ incoming.projects = customerImport.projects.length
6291
+ incoming.clientNotes = customerImport.client_notes.length
6292
+ }
6293
+ const importBackupFile = mode === 'sqlite' ? join(HOME, 'import-backup-' + Date.now() + '.db') : null
6294
+ console.log('! 需要确认:整库替换本地账本(不是合并)')
6295
+ console.log(' 写入:' + incoming.matters + ' 个事项 / ' + incoming.commitments + ' 条承诺 / ' + incoming.facts + ' 条事实 / ' + incoming.preferences + ' 条偏好' + (customerImport ? ' / ' + incoming.clients + ' 个客户 / ' + incoming.projects + ' 个项目 / ' + incoming.clientNotes + ' 条客户备注' : ''))
6296
+ console.log(' 备份:' + (importBackupFile ?? '(JSON store:无数据库备份,旧 state.json 会被覆盖)'))
6297
+ console.log(' 不可撤销:替换后只能用上面的备份恢复;' + (customerImport ? '客户/项目/备注表按导出恢复,其余 SQLite-only 表不会合并。' : '未导入的 SQLite-only 表不会被保留。'))
3919
6298
  // import replaces the ledger wholesale; serialize it with every other store
3920
6299
  // user (P0-1) before copying the pre-import backup and writing.
3921
6300
  ensureInstanceLock()
@@ -3935,7 +6314,7 @@ async function importLedger(file, { replace = false } = {}) {
3935
6314
  // 0.2.3 Wave 1: the pre-import backup is plaintext data. Copy with retry
3936
6315
  // and fsync it; if the backup cannot be made, refuse to replace the ledger
3937
6316
  // (never proceed without a recovery copy).
3938
- const backupFile = join(HOME, `import-backup-${Date.now()}.db`)
6317
+ const backupFile = importBackupFile ?? join(HOME, 'import-backup-' + Date.now() + '.db')
3939
6318
  copyFileWithRetrySync(DB, backupFile)
3940
6319
  fsyncFileSync(backupFile)
3941
6320
  try { chmodSync(backupFile, 0o600) } catch {}
@@ -3947,41 +6326,437 @@ async function importLedger(file, { replace = false } = {}) {
3947
6326
  }
3948
6327
  try {
3949
6328
  const ledger = Ledger.fromJSON(data, LOCAL_PORTS)
3950
- saveLedgerWithAudit(ledger, { actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) })
6329
+ const audit = { actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) }
6330
+ let customerReport = null
6331
+ if (customerImport && mode === 'sqlite') {
6332
+ // One transaction: the nine ledger tables, the three customer tables and
6333
+ // their cross-reference validation. A bad reference throws and rolls the
6334
+ // whole replace back; the pre-import backup remains as a second net.
6335
+ openStore().saveWithAudit(ledger.toJSON(), audit, (innerStore) => {
6336
+ customerReport = applyCustomerImport(innerStore, customerImport)
6337
+ })
6338
+ } else {
6339
+ saveLedgerWithAudit(ledger, audit)
6340
+ }
3951
6341
  console.log(`imported ${data.matters.length} matters, ${data.commitments?.length ?? 0} commitments`)
3952
- if (payload?.data) console.error('note: SQLite-only tables in the import were not merged; ledger was replaced.')
6342
+ if (customerReport) {
6343
+ console.log('restored clients=' + customerReport.clients + ' projects=' + customerReport.projects + ' client_notes=' + customerReport.clientNotes + (customerReport.reconciledDeliveries ? ' · delivery lineage reconciled=' + customerReport.reconciledDeliveries : ''))
6344
+ console.error('note: ledger + customer tables were replaced; other SQLite-only tables in the export (sessions/turns/deliveries/nudges/audit/...) were not merged.')
6345
+ } else if (payload?.data) {
6346
+ console.error('note: SQLite-only tables in the import were not merged; ledger was replaced.')
6347
+ }
3953
6348
  } catch (error) { console.error(`import failed: ${error.message}`); process.exitCode = 1 }
3954
6349
  }
3955
6350
 
3956
- function backup(file) {
3957
- if (!file) { console.error('usage: advisers backup <path.db>'); process.exitCode = 1; return }
6351
+ /* ---------------------------------------------------------------------------
6352
+ * 0.3.0 P0-D2: backup rotation, backup listing/verification and restore.
6353
+ *
6354
+ * `backup <path>` keeps the 0.2.x explicit-copy behaviour (that path is never
6355
+ * rotated), while `backup` with no path writes a managed
6356
+ * $ADVISERS_HOME/backups/state-<UTC>-<tag>.db with .sha256 + .anchor.json
6357
+ * sidecars. Every copy is verified (quick_check/schema/audit head/sampled row
6358
+ * counts) before it is installed. `backup --keep` plans a GFS rotation and
6359
+ * deletes nothing unless --apply is passed; managed rotation only ever touches
6360
+ * <HOME>/backups. `backups verify` re-checks every managed backup read-only.
6361
+ * `restore` plans first (default) and only applies with --yes: safety
6362
+ * pre-restore backup, atomic install of a verified copy, post-install
6363
+ * verification with rollback, audit row `db.restore` and a fresh anchor.
6364
+ * ------------------------------------------------------------------------- */
6365
+
6366
+ /** Report a lib operation failure (backup/restore) with code + actionable hint. */
6367
+ async function reportBackupFailure(result, asJson, label) {
6368
+ const lib = await loadBackup()
6369
+ const code = result?.code ?? null
6370
+ const hint = code ? lib.describeBackupCode(code) : null
6371
+ if (asJson) {
6372
+ console.log(JSON.stringify({ ok: false, label, code, errors: result?.errors ?? [], warnings: result?.warnings ?? [], hint: hint ?? undefined, originalIntact: result?.originalIntact, rolledBack: result?.rolledBack, preRestoreBackup: result?.preRestoreBackup ?? undefined }, null, 2))
6373
+ } else {
6374
+ console.error(`${label}: FAILED${code ? ' (' + code + ')' : ''}`)
6375
+ for (const error of result?.errors ?? []) console.error(` ${error}`)
6376
+ if (hint) console.error(` hint: ${hint}`)
6377
+ if (result?.originalIntact === true) console.error(' the live database was not replaced.')
6378
+ if (result?.rolledBack === true) console.error(' the pre-restore backup was rolled back.')
6379
+ if (result?.preRestoreBackup) console.error(` pre-restore backup kept at ${result.preRestoreBackup}`)
6380
+ }
6381
+ process.exitCode = 1
6382
+ }
6383
+
6384
+ /**
6385
+ * Refresh $ADVISERS_HOME/audit-anchor.json after a backup (P0-L2). The backup
6386
+ * command deliberately writes no audit row of its own: the anchor then equals
6387
+ * the just-created backup's audit head, so restoring that backup immediately is
6388
+ * an anchor "match" (not a suspicious rollback). Audit rows are appended by
6389
+ * commands that change the ledger (restore/doctor.repair/audit --rebuild-fts).
6390
+ */
6391
+ async function refreshAuditAnchor(store) {
6392
+ if (!store) return { ok: false, code: null, errors: ['no writable store'] }
6393
+ try {
6394
+ const anchorLib = await loadAuditAnchor()
6395
+ return anchorLib.writeAuditAnchor({ home: HOME, store, generator: `advisers/${VERSION}` })
6396
+ } catch (error) {
6397
+ return { ok: false, code: error?.code ?? null, errors: [String(error?.message ?? error)] }
6398
+ }
6399
+ }
6400
+
6401
+ function printBackupCreated(created, asJson) {
6402
+ const rotation = created.rotation
6403
+ if (asJson) {
6404
+ console.log(JSON.stringify({
6405
+ ok: true,
6406
+ path: created.path,
6407
+ bytes: created.bytes,
6408
+ sha256: created.sha256,
6409
+ audit: created.audit ? { count: created.audit.count, lastSeq: created.audit.lastSeq, headHash: created.audit.headHash } : null,
6410
+ sidecars: created.sidecars,
6411
+ rotation: rotation ? { dryRun: rotation.dryRun, kept: rotation.kept, wouldDelete: rotation.wouldDelete, deleted: rotation.deleted, errors: rotation.errors } : null,
6412
+ warnings: created.warnings ?? [],
6413
+ }, null, 2))
6414
+ return
6415
+ }
6416
+ console.log(`backup: ${created.path} (${formatBytes(created.bytes)}, sha256=${String(created.sha256 ?? '').slice(0, 12)}…)`)
6417
+ if (created.audit) console.log(`backup: audit entries=${created.audit.count} head=${shortAuditHash(created.audit.headHash)}`)
6418
+ console.log(`backup: sidecars sha256=${created.sidecars?.sha256 ? 'yes' : 'no'} anchor=${created.sidecars?.anchor ? 'yes' : 'no'}`)
6419
+ for (const warning of created.warnings ?? []) console.log(`warning: ${warning}`)
6420
+ if (rotation) {
6421
+ if (rotation.dryRun) console.log(`rotation: dry-run would delete ${rotation.wouldDelete.length} backup(s)${rotation.wouldDelete.length ? ': ' + rotation.wouldDelete.map((file) => basename(file)).join(', ') : ''}`)
6422
+ else console.log(`rotation: deleted ${rotation.deleted?.length ?? 0} backup(s)`)
6423
+ }
6424
+ }
6425
+
6426
+ /**
6427
+ * `advisers backup` — explicit copy, managed backup, or a managed backup +
6428
+ * GFS/keep-N rotation plan (dry-run unless --apply).
6429
+ */
6430
+ async function backupCommand(args = []) {
6431
+ const parsed = parseStrictFlags(args, {
6432
+ booleans: ['dry-run', 'apply', 'json'],
6433
+ values: ['out', 'tag', 'keep'],
6434
+ positional: true,
6435
+ })
6436
+ if (!parsed.ok) return usageFail(parsed.error, BACKUP_USAGE)
6437
+ const { flags, positional } = parsed
6438
+ if (positional.length > 1) return usageFail('backup accepts at most one explicit path', BACKUP_USAGE)
6439
+ if (positional.length === 1 && flags.out !== undefined) return usageFail('pass either an explicit path or --out, not both', BACKUP_USAGE)
6440
+ if (flags.apply === true && flags['dry-run'] === true) return usageFail('--apply and --dry-run are mutually exclusive', BACKUP_USAGE)
6441
+ if (flags.apply === true && flags.keep === undefined) return usageFail('--apply requires --keep (it only applies the rotation plan)', BACKUP_USAGE)
6442
+ const asJson = flags.json === true
6443
+ const sealed = vaultSealedPath()
6444
+ if (sealed) {
6445
+ if (asJson) console.log(JSON.stringify({ ok: false, code: 'E_VAULT_SEALED', errors: [`cannot back up a sealed database (${sealed}); run advisers vault unseal first`] }, null, 2))
6446
+ else {
6447
+ console.error(`advisers: E_VAULT_SEALED — cannot back up a sealed database (${sealed}).`)
6448
+ console.error('Run `advisers vault unseal` first; the sealed file itself is already an encrypted backup.')
6449
+ }
6450
+ process.exitCode = 1
6451
+ return
6452
+ }
6453
+ if (mode === 'json') return usageFail('backup requires the SQLite store (ADVISERS_STORE=sqlite)', BACKUP_USAGE)
6454
+ const lib = await loadBackup()
6455
+ if (flags.keep !== undefined) {
6456
+ const normalized = lib.normalizeKeepPolicy(flags.keep)
6457
+ if (!normalized.ok) return usageFail(`invalid --keep: ${normalized.error}`, BACKUP_USAGE)
6458
+ }
6459
+ if (flags.tag !== undefined) {
6460
+ const tagCheck = lib.normalizeBackupTag(flags.tag)
6461
+ if (!tagCheck.ok) return usageFail(`invalid --tag: ${tagCheck.error}`, BACKUP_USAGE)
6462
+ }
6463
+ const explicitPath = flags.out !== undefined ? String(flags.out) : positional[0]
6464
+ if (explicitPath !== undefined && (flags.keep !== undefined || flags.apply === true)) {
6465
+ return usageFail('an explicit backup path never participates in rotation; drop --keep/--apply or use a managed backup', BACKUP_USAGE)
6466
+ }
6467
+ ensureHome()
6468
+ let store
6469
+ try { store = openStore() } catch (error) { return reportMaintenanceFailure(error, asJson, 'backup') }
6470
+ if (explicitPath !== undefined) {
6471
+ const created = lib.createBackup({
6472
+ dbPath: DB,
6473
+ targetPath: explicitPath,
6474
+ store,
6475
+ checkpoint: true,
6476
+ verify: true,
6477
+ verifyChain: true,
6478
+ writeSha256: true,
6479
+ overwrite: true,
6480
+ })
6481
+ if (!created.ok) return reportBackupFailure(created, asJson, 'backup')
6482
+ if (created.audit) {
6483
+ const anchored = lib.writeBackupAnchorSidecar({ backupPath: created.path, head: created.audit, home: HOME })
6484
+ if (anchored.ok) created.sidecars.anchor = anchored.anchorPath
6485
+ else (created.warnings ??= []).push(anchored.errors?.[0] ?? 'could not write the audit anchor sidecar')
6486
+ }
6487
+ const anchor = await refreshAuditAnchor(store)
6488
+ if (!anchor.ok) (created.warnings ??= []).push(`could not refresh the audit anchor (${anchor.code ?? 'unknown'})`)
6489
+ printBackupCreated(created, asJson)
6490
+ if (!asJson && created.warnings?.length) {
6491
+ for (const warning of created.warnings.slice(-1)) console.log(`warning: ${warning}`)
6492
+ }
6493
+ if (!asJson) console.log(anchor.ok ? `anchor: refreshed (count=${anchor.anchor?.count ?? '?'})` : `warning: audit anchor not refreshed (${anchor.code ?? 'unknown'})`)
6494
+ return
6495
+ }
6496
+ // Managed backup. Plain --dry-run (no --keep) is a read-only plan.
6497
+ if (flags['dry-run'] === true && flags.keep === undefined) {
6498
+ const target = lib.backupPathFor({ home: HOME, tag: flags.tag ?? null })
6499
+ const listed = lib.listBackups({ home: HOME })
6500
+ const rotation = lib.planBackupRotation({ entries: listed.entries ?? [], keep: undefined })
6501
+ if (asJson) console.log(JSON.stringify({ ok: true, mode: 'dry-run', wouldCreate: target, rotation: { kept: rotation.kept?.map((entry) => entry.path), wouldDelete: rotation.wouldDelete } }, null, 2))
6502
+ else {
6503
+ console.log(`backup: dry-run would create ${target}`)
6504
+ console.log(`rotation: dry-run would keep ${rotation.kept?.length ?? 0} backup(s), delete ${rotation.wouldDelete?.length ?? 0}`)
6505
+ }
6506
+ return
6507
+ }
6508
+ const created = lib.createManagedBackup({
6509
+ home: HOME,
6510
+ dbPath: DB,
6511
+ store,
6512
+ tag: flags.tag ?? null,
6513
+ keep: flags.keep !== undefined ? flags.keep : null,
6514
+ rotate: flags.keep !== undefined,
6515
+ rotateDryRun: flags.apply !== true,
6516
+ verifyChain: true,
6517
+ })
6518
+ if (!created.ok) return reportBackupFailure(created, asJson, 'backup')
6519
+ const anchor = await refreshAuditAnchor(store)
6520
+ if (!anchor.ok) (created.warnings ??= []).push(`could not refresh the audit anchor (${anchor.code ?? 'unknown'})`)
6521
+ if (asJson) {
6522
+ const payload = {
6523
+ ok: true,
6524
+ path: created.path,
6525
+ bytes: created.bytes,
6526
+ sha256: created.sha256,
6527
+ audit: created.audit ? { count: created.audit.count, lastSeq: created.audit.lastSeq, headHash: created.audit.headHash } : null,
6528
+ sidecars: created.sidecars,
6529
+ rotation: created.rotation ? { dryRun: created.rotation.dryRun, wouldDelete: created.rotation.wouldDelete, deleted: created.rotation.deleted, errors: created.rotation.errors } : null,
6530
+ warnings: created.warnings ?? [],
6531
+ anchor: anchor.ok ? { ok: true, count: anchor.anchor?.count ?? null } : { ok: false, code: anchor.code ?? null },
6532
+ }
6533
+ console.log(JSON.stringify(payload, null, 2))
6534
+ return
6535
+ }
6536
+ console.log(`backup: ${created.path} (${formatBytes(created.bytes)}, sha256=${String(created.sha256 ?? '').slice(0, 12)}…)`)
6537
+ if (created.audit) console.log(`backup: audit entries=${created.audit.count} head=${shortAuditHash(created.audit.headHash)}`)
6538
+ console.log(`backup: sidecars sha256=${created.sidecars?.sha256 ? 'yes' : 'no'} anchor=${created.sidecars?.anchor ? 'yes' : 'no'}`)
6539
+ for (const warning of created.warnings ?? []) console.log(`warning: ${warning}`)
6540
+ const rotation = created.rotation
6541
+ if (rotation) {
6542
+ if (rotation.dryRun) console.log(`rotation: dry-run would delete ${rotation.wouldDelete?.length ?? 0} backup(s)${rotation.wouldDelete?.length ? ': ' + rotation.wouldDelete.map((file) => basename(file)).join(', ') : ''} (pass --apply to delete)`)
6543
+ else console.log(`rotation: deleted ${rotation.deleted?.length ?? 0} backup(s)`)
6544
+ for (const error of rotation.errors ?? []) console.error(`rotation error: ${error}`)
6545
+ }
6546
+ console.log(anchor.ok ? `anchor: refreshed (count=${anchor.anchor?.count ?? '?'})` : `warning: audit anchor not refreshed (${anchor.code ?? 'unknown'})`)
6547
+ }
6548
+
6549
+ /** `advisers backups ls|verify` — read-only inspection of <HOME>/backups. */
6550
+ async function backupsCommand(args = []) {
6551
+ const sub = args[0]
6552
+ const rest = args.slice(1)
6553
+ if (!sub || sub === 'help' || sub === '--help') { console.log(BACKUPS_USAGE); if (!sub) process.exitCode = 1; return }
6554
+ if (sub !== 'ls' && sub !== 'verify') return usageFail(`unknown backups subcommand: ${sub}`, BACKUPS_USAGE)
6555
+ const parsed = parseStrictFlags(rest, { booleans: ['json'], values: ['limit'], positional: false })
6556
+ if (!parsed.ok) return usageFail(parsed.error, BACKUPS_USAGE)
6557
+ const { flags } = parsed
6558
+ const asJson = flags.json === true
6559
+ let limit = 100
6560
+ if (flags.limit !== undefined) {
6561
+ limit = Number(flags.limit)
6562
+ if (!Number.isInteger(limit) || limit < 1) return usageFail('--limit requires a positive integer', BACKUPS_USAGE)
6563
+ }
6564
+ const lib = await loadBackup()
6565
+ if (mode === 'json') return usageFail('backups requires the SQLite store (ADVISERS_STORE=sqlite)', BACKUPS_USAGE)
6566
+ ensureHome()
6567
+ if (sub === 'ls') {
6568
+ const listed = lib.listBackups({ home: HOME })
6569
+ if (!listed.ok) { console.error(`backups ls: FAILED (${listed.errors?.[0] ?? 'unknown'})`); process.exitCode = 1; return }
6570
+ const entries = listed.entries.slice(0, limit)
6571
+ if (asJson) {
6572
+ console.log(JSON.stringify({ ok: true, dir: listed.dir, count: entries.length, total: listed.entries.length, entries: entries.map((entry) => ({ name: entry.name, path: entry.path, tag: entry.tag, createdAt: entry.createdAt, bytes: entry.size, sidecars: entry.sidecars })) }, null, 2))
6573
+ return
6574
+ }
6575
+ if (!entries.length) { console.log(`backups: none in ${listed.dir}`); return }
6576
+ console.log(`backups: ${listed.entries.length} in ${listed.dir} (newest first)`)
6577
+ for (const entry of entries) {
6578
+ console.log(`${entry.name}\t${formatBytes(entry.size)}\t${entry.createdAt}\tsha256=${entry.sidecars.sha256 ? 'yes' : 'no'}\tanchor=${entry.sidecars.anchor ? 'yes' : 'no'}`)
6579
+ }
6580
+ return
6581
+ }
6582
+ const verified = lib.verifyBackups({ home: HOME, limit })
6583
+ if (asJson) {
6584
+ console.log(JSON.stringify({
6585
+ ok: verified.ok,
6586
+ dir: verified.dir,
6587
+ count: verified.count,
6588
+ results: verified.results.map((row) => ({
6589
+ name: row.name,
6590
+ path: row.path,
6591
+ ok: row.ok,
6592
+ schemaVersion: row.inspection?.schemaVersion ?? null,
6593
+ auditCount: row.inspection?.audit?.count ?? null,
6594
+ errors: [...(row.inspection?.errors ?? []), ...(row.sidecars?.errors ?? [])],
6595
+ })),
6596
+ errors: verified.errors,
6597
+ warnings: verified.warnings,
6598
+ }, null, 2))
6599
+ } else if (!verified.results.length) {
6600
+ console.log(`backups: none in ${verified.dir}`)
6601
+ } else {
6602
+ for (const row of verified.results) {
6603
+ const detail = row.ok
6604
+ ? `schema=v${row.inspection?.schemaVersion ?? '?'} audit=${row.inspection?.audit?.count ?? '?'}`
6605
+ : `${[...(row.inspection?.errors ?? []), ...(row.sidecars?.errors ?? [])][0] ?? 'failed'}`
6606
+ console.log(`${row.ok ? 'PASS' : 'FAIL'} ${row.name} ${detail}`)
6607
+ }
6608
+ console.log(`backups: ${verified.results.length} checked, ${verified.results.filter((row) => !row.ok).length} failed`)
6609
+ }
6610
+ if (!verified.ok) process.exitCode = 1
6611
+ }
6612
+
6613
+ /**
6614
+ * `advisers restore <backup-file>` — plan by default, apply only with --yes.
6615
+ * The whole flow is fail-safe: planRestore validates the backup + anchors
6616
+ * before anything is touched; restoreBackup writes a pre-restore safety copy,
6617
+ * installs the verified backup atomically, re-verifies and rolls back on
6618
+ * failure. On success the store is reopened, `db.restore` is audited and a
6619
+ * fresh anchor is written.
6620
+ */
6621
+ async function restoreCommand(args = []) {
6622
+ const parsed = parseStrictFlags(args, {
6623
+ booleans: ['dry-run', 'yes', 'allow-anchor-behind', 'allow-broken-audit-chain', 'json'],
6624
+ positional: true,
6625
+ })
6626
+ if (!parsed.ok) return usageFail(parsed.error, RESTORE_USAGE)
6627
+ const { flags, positional } = parsed
6628
+ if (positional.length !== 1) return usageFail('restore requires exactly one backup file', RESTORE_USAGE)
6629
+ if (flags.yes === true && flags['dry-run'] === true) return usageFail('--yes and --dry-run are mutually exclusive', RESTORE_USAGE)
6630
+ const asJson = flags.json === true
3958
6631
  const sealed = vaultSealedPath()
3959
6632
  if (sealed) {
3960
- console.error(`advisers: E_VAULT_SEALED — cannot back up a sealed database (${sealed}).`)
3961
- console.error('Run `advisers vault unseal` first; the sealed file itself is already an encrypted backup.')
6633
+ if (asJson) console.log(JSON.stringify({ ok: false, code: 'E_VAULT_SEALED', errors: [`the ledger is sealed (${sealed}); run advisers vault unseal first`] }, null, 2))
6634
+ else {
6635
+ console.error(`advisers: E_VAULT_SEALED — cannot restore into a sealed home (${sealed}).`)
6636
+ console.error('Run `advisers vault unseal` first, then retry the restore.')
6637
+ }
6638
+ process.exitCode = 1
6639
+ return
6640
+ }
6641
+ if (mode === 'json') return usageFail('restore requires the SQLite store (ADVISERS_STORE=sqlite)', RESTORE_USAGE)
6642
+ ensureHome()
6643
+ let backupPath = positional[0]
6644
+ if (!existsSync(backupPath) && !isAbsolute(backupPath)) {
6645
+ const candidate = join(HOME, 'backups', backupPath)
6646
+ if (existsSync(candidate)) backupPath = candidate
6647
+ }
6648
+ const lib = await loadBackup()
6649
+ const options = {
6650
+ allowAnchorBehind: flags['allow-anchor-behind'] === true,
6651
+ allowBrokenAuditChain: flags['allow-broken-audit-chain'] === true,
6652
+ }
6653
+ const plan = lib.planRestore({ backupPath, dbPath: DB, home: HOME, key: undefined, ...options })
6654
+ if (!plan.ok) {
6655
+ if (asJson) {
6656
+ const hint = plan.code ? lib.describeBackupCode(plan.code) : null
6657
+ console.log(JSON.stringify({ ok: false, mode: 'dry-run', code: plan.code ?? null, codes: plan.codes ?? [], errors: plan.errors ?? [], warnings: plan.warnings ?? [], hint: hint ?? undefined }, null, 2))
6658
+ } else {
6659
+ console.error(`restore: plan FAILED${plan.code ? ' (' + plan.code + ')' : ''}`)
6660
+ for (const error of plan.errors ?? []) console.error(` ${error}`)
6661
+ if (plan.code) console.error(` hint: ${lib.describeBackupCode(plan.code)}`)
6662
+ console.error(' nothing was changed.')
6663
+ }
3962
6664
  process.exitCode = 1
3963
6665
  return
3964
6666
  }
3965
- const store = openStore()
3966
- const checkpoint = store.checkpoint()
3967
- if (checkpoint.busy) { console.error('backup failed: database is busy (another advisers process is writing); close it and retry'); process.exitCode = 1; return }
3968
- mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
3969
- // 0.2.3 Wave 1: retry transient Windows locks and fsync the copy before
3970
- // reporting success (a crash right after a plain copy can lose the backup).
3971
- const existed = existsSync(file)
6667
+ const backupInfo = plan.inspection
6668
+ const anchor = plan.anchorVerification
6669
+ const anchorLine = !plan.anchor
6670
+ ? 'absent (yellow: no audit anchor found — the backup cannot be checked against a baseline)'
6671
+ : anchor?.ok === false
6672
+ ? `FAIL (${anchor.code})`
6673
+ : anchor
6674
+ ? `${anchor.status} (anchor count=${anchor.anchorCount ?? '?'} backup count=${anchor.count ?? '?'}${options.allowAnchorBehind ? ', anchor-behind allowed' : ''})`
6675
+ : 'present (not comparable: the backup has no readable audit head)'
6676
+ const apply = flags.yes === true
6677
+ if (!apply) {
6678
+ if (asJson) {
6679
+ console.log(JSON.stringify({
6680
+ ok: true,
6681
+ mode: 'dry-run',
6682
+ backup: { path: plan.path, bytes: backupInfo.size, schemaVersion: backupInfo.schemaVersion, schemaStatus: backupInfo.schemaStatus, audit: backupInfo.audit ? { count: backupInfo.audit.count, lastSeq: backupInfo.audit.lastSeq, headHash: backupInfo.audit.headHash } : null, chainVerified: backupInfo.chainVerified === true },
6683
+ target: DB,
6684
+ anchor: plan.anchor ? { present: true, status: anchor?.status ?? null, ok: anchor?.ok ?? null, code: anchor?.code ?? null } : { present: false, status: 'absent' },
6685
+ sidecarAnchor: plan.sidecarAnchor ? { present: true, ok: plan.sidecarAnchor.verification?.ok === true } : { present: false },
6686
+ steps: plan.steps,
6687
+ warnings: plan.warnings,
6688
+ }, null, 2))
6689
+ return
6690
+ }
6691
+ console.log(`restore: dry-run (no changes) — ${basename(plan.path)}`)
6692
+ console.log(`backup: ${formatBytes(backupInfo.size)} schema=v${backupInfo.schemaVersion ?? '?'} (${backupInfo.schemaStatus}) audit=${backupInfo.audit ? backupInfo.audit.count + ' entries, chain=' + (backupInfo.chainVerified ? 'verified' : 'not verified') : 'no audit table'}`)
6693
+ console.log(`anchor: ${anchorLine}`)
6694
+ if (plan.sidecarAnchor) console.log(`sidecar: ${basename(lib.backupAnchorPath(plan.path))} ${plan.sidecarAnchor.verification?.ok === true ? 'match' : 'mismatch'}`)
6695
+ for (const step of plan.steps) console.log(`step: ${step}`)
6696
+ for (const warning of plan.warnings) console.log(`warning: ${warning}`)
6697
+ console.log('next: advisers restore ' + basename(plan.path) + ' --yes')
6698
+ return
6699
+ }
6700
+ let lock
6701
+ try { lock = ensureInstanceLock() } catch (error) { return reportMaintenanceFailure(error, asJson, 'restore') }
6702
+ let store = null
6703
+ if (existsSync(DB)) {
6704
+ try { store = openStore() } catch (error) { return reportMaintenanceFailure(error, asJson, 'restore') }
6705
+ }
6706
+ const restored = lib.restoreBackup({ plan, dbPath: DB, store, home: HOME, key: undefined, ...options })
6707
+ if (!restored.ok) {
6708
+ activeStore = undefined
6709
+ try { releaseInstanceLock() } catch {}
6710
+ return reportBackupFailure(restored, asJson, 'restore')
6711
+ }
6712
+ // Reopen the restored database and record the restore (the library never
6713
+ // writes audit rows itself; the caller owns the post-restore audit/anchor).
6714
+ activeStore = undefined
6715
+ let auditRow = null
6716
+ let anchorWrite = null
6717
+ let reopened = null
3972
6718
  try {
3973
- copyFileWithRetrySync(DB, file)
3974
- fsyncFileSync(file)
3975
- chmodSync(file, 0o600)
6719
+ reopened = openStore()
6720
+ auditRow = reopened.appendAudit({
6721
+ actor: 'local',
6722
+ action: 'db.restore',
6723
+ allowed: true,
6724
+ reason: `from=${basename(restored.restoredFrom)};preRestore=${restored.preRestoreBackup ? basename(restored.preRestoreBackup) : 'none'};allowAnchorBehind=${options.allowAnchorBehind ? 1 : 0};schema=v${restored.schemaVersion ?? '?'};auditCount=${restored.audit?.count ?? '?'}`,
6725
+ })
6726
+ const anchorLib = await loadAuditAnchor()
6727
+ anchorWrite = anchorLib.writeAuditAnchor({ home: HOME, store: reopened, generator: `advisers/${VERSION}` })
3976
6728
  } catch (error) {
3977
- // Only remove the target when this command created it: a pre-existing
3978
- // backup must never be destroyed just because a new copy failed.
3979
- if (!existed) { try { rmWithRetrySync(file) } catch {} }
3980
- console.error(`backup failed: ${describeFsError(error, { action: 'copying the database to', target: file })}`)
6729
+ if (asJson) console.log(JSON.stringify({ ok: false, mode: 'apply', restored: true, code: error?.code ?? null, errors: [`the backup was installed but reopening/recording it failed: ${error?.message ?? error}`], preRestoreBackup: restored.preRestoreBackup ?? null }, null, 2))
6730
+ else {
6731
+ console.error(`advisers: the backup was installed but reopening/recording it failed: ${error?.message ?? error}`)
6732
+ console.error(` Next: run 'advisers doctor --check-db'; the pre-restore backup is at ${restored.preRestoreBackup ?? '(none)'}.`)
6733
+ }
3981
6734
  process.exitCode = 1
3982
6735
  return
3983
6736
  }
3984
- console.log(`backup: ${file}`)
6737
+ if (asJson) {
6738
+ console.log(JSON.stringify({
6739
+ ok: true,
6740
+ mode: 'apply',
6741
+ restoredFrom: restored.restoredFrom,
6742
+ preRestoreBackup: restored.preRestoreBackup,
6743
+ schemaVersion: restored.schemaVersion,
6744
+ audit: restored.audit ? { count: restored.audit.count, lastSeq: restored.audit.lastSeq, headHash: restored.audit.headHash } : null,
6745
+ auditRow: auditRow ? { seq: auditRow.seq, action: auditRow.action } : null,
6746
+ anchor: anchorWrite ? { ok: anchorWrite.ok === true, code: anchorWrite.code ?? null, count: anchorWrite.anchor?.count ?? null } : null,
6747
+ steps: restored.steps,
6748
+ warnings: restored.warnings,
6749
+ }, null, 2))
6750
+ return
6751
+ }
6752
+ console.log(`restore: done — ${basename(restored.restoredFrom)} -> ${DB}`)
6753
+ console.log(`restore: pre-restore backup ${restored.preRestoreBackup ? basename(restored.preRestoreBackup) : '(none: fresh install)'}`)
6754
+ console.log(`restore: schema=v${restored.schemaVersion ?? '?'} audit=${restored.audit?.count ?? '?'} entries`)
6755
+ if (auditRow) console.log(`audit: db.restore seq ${auditRow.seq}`)
6756
+ if (anchorWrite?.ok) console.log(`audit: anchor refreshed (count=${anchorWrite.anchor?.count ?? '?'})`)
6757
+ else if (anchorWrite) console.error(`warning: the restore succeeded but the audit anchor failed (${anchorWrite.code ?? 'unknown'})`)
6758
+ for (const warning of restored.warnings ?? []) console.log(`warning: ${warning}`)
6759
+ console.log('next: advisers doctor --check-db')
3985
6760
  }
3986
6761
 
3987
6762
  async function brief(text, deep = false) {
@@ -4790,6 +7565,14 @@ async function templateQuoteOrProposal(name, dataFile, outFile, flags) {
4790
7565
  validation: ext + ((content && content.ok === false) ? ':content-warn' : ':ok'),
4791
7566
  audit: { actor: 'local', action: 'template.record', allowed: true, reason: name },
4792
7567
  matterId: typeof flags.matter === 'string' ? flags.matter : undefined,
7568
+ // 0.3.0 delivery lineage: the template version/quote number/data hash are
7569
+ // known at generation time; the store snapshots client/project from the
7570
+ // delivery's matter. A receipt generated later reads this row instead of
7571
+ // recomputing (or worse, guessing) the lineage.
7572
+ templateName: name,
7573
+ templateVersion: QUOTE_TEMPLATE_VERSION,
7574
+ quoteNo: normalized.data.quoteNo,
7575
+ dataSha256: dataSha256,
4793
7576
  })
4794
7577
  try { deliveryId = dbStore()?.listDeliveries(1)?.[0]?.id } catch {}
4795
7578
  }
@@ -5149,13 +7932,13 @@ async function captureFromImap(flags) {
5149
7932
  sinceDays: Math.max(1, Number(flags['since-days']) || 30),
5150
7933
  limit: Math.max(1, Math.min(100, Number(flags.limit) || 20)),
5151
7934
  })
5152
- } catch (error) { console.error(`imap failed: ${error.message}`); process.exitCode = 1; return }
7935
+ } catch (error) { console.error(sanitizeConsoleText('imap failed: ' + (error?.message ?? error), { max: 2000 })); process.exitCode = 1; return }
5153
7936
  let seen = 0, skipped = 0, failed = 0
5154
7937
  const created = []
5155
7938
  for (const msg of messages) {
5156
7939
  seen++
5157
7940
  let parsed
5158
- try { parsed = parseEml(msg.raw.toString('utf8')) } catch (error) { failed++; console.error(`imap message ${msg.uid}: ${error.message}`); continue }
7941
+ try { parsed = parseEml(msg.raw.toString('utf8')) } catch (error) { failed++; console.error(sanitizeConsoleText('imap message ' + msg.uid + ': ' + (error?.message ?? error), { max: 2000 })); continue }
5159
7942
  const key = dedupeKey('email', parsed)
5160
7943
  if (store.hasSeen('import', 'imap', key, 30)) { skipped++; continue }
5161
7944
  const input = toCaptureInput(parsed, { source: 'email' })
@@ -5164,7 +7947,7 @@ async function captureFromImap(flags) {
5164
7947
  const result = await proposeCaptureText({ text: input.text, source: 'email', date: parseEmailDate(parsed.date), matterId, store, json: flags.json === true, meta: { type: 'mail', channel: 'imap', uid: msg.uid, messageId: parsed.messageId, subject: parsed.subject, from: parsed.from } })
5165
7948
  created.push(...result.candidates)
5166
7949
  store.markSeen('import', 'imap', key)
5167
- } catch (error) { failed++; console.error(`imap message ${msg.uid}: ${error.message}`) }
7950
+ } catch (error) { failed++; console.error(sanitizeConsoleText('imap message ' + msg.uid + ': ' + (error?.message ?? error), { max: 2000 })) }
5168
7951
  }
5169
7952
  store.appendAudit({ actor: 'local', action: 'import.imap', allowed: true, reason: `${seen} seen, ${created.length} candidates, ${failed} failed` })
5170
7953
  if (flags.json) {
@@ -5208,12 +7991,23 @@ async function calendarImport(args) {
5208
7991
  async function calendarOccurrencesToday() {
5209
7992
  const store = dbStore()
5210
7993
  const localDay = localDayOf(Date.now())
5211
- if (!store) return { localDay, occurrences: [] }
7994
+ if (!store) return { localDay, occurrences: [], degraded: [] }
5212
7995
  const { expandRrule } = await loadIcal()
5213
7996
  const occurrences = []
7997
+ const degraded = []
5214
7998
  for (const row of store.listCalendarEvents()) {
7999
+ // Same TZID rule as agenda: lib/ical.js has no time-zone database, so a
8000
+ // non-Shanghai row is skipped and reported, never shown at a guessed +08:00
8001
+ // time (13-mail-calendar C5).
8002
+ if (!calendarTzidSupported(row)) {
8003
+ degraded.push({ source: 'calendar', code: 'E_CALENDAR_SKIP', id: row.uid ?? null, reason: 'unsupported tzid: ' + calendarTzidOf(row) })
8004
+ continue
8005
+ }
5215
8006
  let instances
5216
- try { instances = expandRrule(row, { from: localDay, to: localDay }) } catch { instances = [] }
8007
+ try { instances = expandRrule(row, { from: localDay, to: localDay }) } catch (error) {
8008
+ degraded.push({ source: 'calendar', code: 'E_CALENDAR_SKIP', id: row.uid ?? null, reason: String(error?.message ?? error) })
8009
+ continue
8010
+ }
5217
8011
  for (const instance of instances) {
5218
8012
  occurrences.push({
5219
8013
  uid: instance.uid,
@@ -5228,17 +8022,20 @@ async function calendarOccurrencesToday() {
5228
8022
  }
5229
8023
  }
5230
8024
  occurrences.sort((a, b) => (a.startsAt < b.startsAt ? -1 : a.startsAt > b.startsAt ? 1 : String(a.summary).localeCompare(String(b.summary))))
5231
- return { localDay, occurrences }
8025
+ return { localDay, occurrences, degraded }
5232
8026
  }
5233
8027
 
5234
8028
  async function printCalendarToday() {
5235
- const { localDay, occurrences } = await calendarOccurrencesToday()
5236
- if (!occurrences.length) { console.log('日历:今天没有本地导入的会议。'); return }
5237
- console.log(`日历(本地只读,${localDay}):`)
5238
- for (const e of occurrences) {
5239
- const time = e.allDay ? '全天' : e.startsAt.slice(11, 16)
5240
- console.log(` ${time} ${e.summary}${e.recurring ? '(循环)' : ''}${e.location ? ` · ${e.location}` : ''}`)
8029
+ const { localDay, occurrences, degraded } = await calendarOccurrencesToday()
8030
+ if (!occurrences.length) console.log('日历:今天没有本地导入的会议。')
8031
+ else {
8032
+ console.log('日历(本地只读,' + localDay + '):')
8033
+ for (const e of occurrences) {
8034
+ const time = e.allDay ? '全天' : e.startsAt.slice(11, 16)
8035
+ console.log(' ' + time + ' ' + sanitizeConsoleText(e.summary, { max: 200 }) + (e.recurring ? '(循环)' : '') + (e.location ? ' · ' + sanitizeConsoleText(e.location, { max: 120 }) : ''))
8036
+ }
5241
8037
  }
8038
+ if (degraded.length) console.log('日历降级:' + degraded.length + ' 条(非 Asia/Shanghai 时区或无法展开,已跳过)')
5242
8039
  }
5243
8040
 
5244
8041
  /** Host header allowlist for the local read-only UI (DNS-rebinding hardening, SEC2-07). */
@@ -5302,7 +8099,17 @@ async function remind(args) {
5302
8099
  const mutating = sub === 'install' || sub === 'uninstall' || flags.install === true ||
5303
8100
  flags.uninstall === true || flags.ics !== undefined || flags.deliver === true || flags.notify === true
5304
8101
  const store = mutating ? dbStore() : readStoreOrExit()
5305
- const ledger = mutating ? loadLedger({ commitments: {} }) : loadReadLedger({ commitments: {} })
8102
+ // 0.3.0 P0-T2: reminder planning only reads id/status/action/dueAt/offsets,
8103
+ // so a narrow projection replaces the whole-entity commitment load (which
8104
+ // cost ~480ms and mapped every row at a 200k-row ledger). Legacy JSON-store
8105
+ // mode keeps loadJson().
8106
+ let planLedger = null
8107
+ const plannerLedger = () => {
8108
+ if (planLedger) return planLedger
8109
+ if (mode === 'json' || !store) { planLedger = loadJson(); return planLedger }
8110
+ planLedger = reminderLedgerFromRows(store.read(() => store.projectCommitmentsForReminders()))
8111
+ return planLedger
8112
+ }
5306
8113
  const scheduler = await loadScheduler()
5307
8114
  if (sub === 'install' || flags.install) {
5308
8115
  const dir = join(HOME, 'scheduler')
@@ -5375,7 +8182,7 @@ async function remind(args) {
5375
8182
  // One prefix query instead of getMeta() per commitment (read-only store safe).
5376
8183
  const snoozed = {}
5377
8184
  for (const [key, value] of store?.listMetaByPrefix('snooze:') ?? []) snoozed[key.slice('snooze:'.length)] = value
5378
- const reminders = buildReminders(ledger, { now: new Date(), snoozedUntil: snoozed })
8185
+ const reminders = buildReminders(plannerLedger(), { now: new Date(), snoozedUntil: snoozed })
5379
8186
  if (flags.ics) {
5380
8187
  const path = typeof flags.ics === 'string' ? flags.ics : (positional[0] || join(HOME, 'reminders.ics'))
5381
8188
  writeFileSync(path, toIcs(reminders, { now: new Date() }), { mode: 0o600 })
@@ -5389,9 +8196,14 @@ async function remind(args) {
5389
8196
  if (flags.deliver) recordReminderRun(scheduler, { count: 0, channel: 'log' })
5390
8197
  return
5391
8198
  }
5392
- for (const r of reminders) console.log('[' + r.level + '/' + r.bucket + '] ' + r.action + (r.dueAt ? ' · ' + r.dueAt.slice(0, 16) : ''))
8199
+ for (const r of reminders) console.log('[' + r.level + '/' + r.bucket + '] ' + sanitizeConsoleText(r.action, { max: 2000 }) + (r.dueAt ? ' · ' + String(r.dueAt).slice(0, 16) : ''))
5393
8200
  if (flags.deliver) {
5394
- const line = new Date().toISOString() + '\t' + reminders.length + '\t' + reminders.map((r) => r.action).join(';') + '\n'
8201
+ // 0.3.0 Wave 3: reminders.log is one line per run. The action text is ledger
8202
+ // data (it can arrive through import or a model turn), so strip CR/LF and
8203
+ // control characters before appending; otherwise one entry could forge log
8204
+ // lines in the user's reminder history.
8205
+ const actions = reminders.map((r) => sanitizeConsoleText(r.action, { max: 2000 }))
8206
+ const line = new Date().toISOString() + '\t' + reminders.length + '\t' + actions.join(';') + '\n'
5395
8207
  writeFileSync(join(HOME, 'reminders.log'), line, { flag: 'a', mode: 0o600 })
5396
8208
  let channel = 'log'
5397
8209
  if (flags.notify) {
@@ -5400,7 +8212,7 @@ async function remind(args) {
5400
8212
  channel = local.sent ? local.channel : 'log-only'
5401
8213
  const webhook = await notify.sendWebhookNotification(reminders)
5402
8214
  if (webhook.sent) channel = channel === 'log-only' ? 'webhook' : channel + '+webhook'
5403
- else if (webhook.configured) console.error('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''))
8215
+ else if (webhook.configured) console.error(sanitizeConsoleText('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''), { max: 2000 }))
5404
8216
  }
5405
8217
  store?.appendAudit({ actor: 'local', action: 'notify.delivered', allowed: true, reason: reminders.length + ' reminders channel=' + channel })
5406
8218
  recordReminderRun(scheduler, { count: reminders.length, channel })
@@ -5585,7 +8397,11 @@ async function mcpServer() {
5585
8397
  if (mode === 'json') return loadJson()
5586
8398
  if (!store) return new Ledger(LOCAL_PORTS)
5587
8399
  if (kind === 'matters') return Ledger.fromParts({ version: 1, matters: store.loadMatters() }, LOCAL_PORTS)
5588
- if (kind === 'commitments') return Ledger.fromParts({ version: 1, commitments: store.loadCommitments() }, LOCAL_PORTS)
8400
+ // 0.2.5 A-2: the read models' clearance gate needs each commitment's matter
8401
+ // secrecy, so the commitments view also loads the small matters table.
8402
+ if (kind === 'commitments') {
8403
+ return Ledger.fromParts({ version: 1, matters: store.loadMatters(), commitments: store.loadCommitments() }, LOCAL_PORTS)
8404
+ }
5589
8405
  return Ledger.fromJSON(store.load(), LOCAL_PORTS)
5590
8406
  }
5591
8407
  const { createMcpServer } = await loadMcpServer()
@@ -5892,46 +8708,157 @@ async function timestampCommand(args) {
5892
8708
  } catch (error) { console.error(`timestamp failed: ${error.message}`); process.exitCode = 1 }
5893
8709
  }
5894
8710
 
5895
- async function tui(args) {
5896
- const once = args.includes('--once')
8711
+ const TUI_USAGE = [
8712
+ 'usage: advisers tui [--once] [--json] [--width <40..200>] [--plain|--accessible] [--color auto|always|never]',
8713
+ ' --once print the read-only snapshot once (default when stdin/stdout is a pipe)',
8714
+ ' --json print the same snapshot as one JSON document (pure stdout, no ANSI)',
8715
+ ' --width n wrap/truncate at n columns (default: terminal width or 80; 40..200)',
8716
+ ' --plain / --accessible / --color: global output policy (docs/TUI.md §6)',
8717
+ ].join(String.fromCharCode(10))
8718
+
8719
+ /**
8720
+ * Read-only TUI snapshot data.
8721
+ *
8722
+ * 0.2.3 §4.8: no writer lock; each refresh reads the current committed snapshot.
8723
+ * 0.3.0 P0-T2: one narrow projection feeds both the open list and the reminder
8724
+ * planner (all non-done rows incl. undated open commitments). The same data
8725
+ * object feeds the human snapshot, the --json projection and the dashboard so
8726
+ * the three can never disagree (plan 26 §6.4).
8727
+ */
8728
+ async function tuiSnapshotData() {
5897
8729
  const { buildReminders } = await loadRemind()
5898
- const render = () => {
5899
- // 0.2.3 §4.8: no writer lock; each refresh reads the current committed snapshot.
5900
- const ledger = loadReadLedger({ commitments: {} })
5901
- const store = readStoreOrExit()
5902
- const open = ledger.openCommitments()
5903
- const localDay = localDayOf(Date.now())
5904
- const due = open.filter((c) => c.dueAt && c.dueAt.slice(0, 10) <= localDay)
5905
- const reminders = buildReminders(ledger, { now: new Date() })
5906
- const deliveries = store?.listDeliveries(3) ?? []
5907
- const lines = [
5908
- 'Advisers TUI (read-only)',
5909
- `today ${localDay} · open ${open.length} · due ${due.length} · reminders ${reminders.length}`,
5910
- '',
5911
- 'reminders:',
5912
- ...(reminders.length ? reminders.slice(0, 8).map((r) => ` [${r.level}/${r.bucket}] ${r.action}${r.dueAt ? ` · ${r.dueAt.slice(0, 16)}` : ''}`) : [' (none)']),
5913
- '',
5914
- 'open commitments:',
5915
- ...(open.length ? open.slice(0, 8).map((c) => ` ${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`) : [' (none)']),
5916
- '',
5917
- 'recent deliveries:',
5918
- ...(deliveries.length ? deliveries.map((d) => ` ${d.createdAt.slice(0, 16)} ${d.title ?? d.tool ?? d.id}`) : [' (none)']),
5919
- ]
5920
- return lines.join(String.fromCharCode(10))
8730
+ const store = readStoreOrExit()
8731
+ const rows = mode === 'json' || !store
8732
+ ? loadJson().listCommitments()
8733
+ : store.read(() => store.projectCommitmentsForReminders({ includeUndated: true }))
8734
+ const open = rows.filter((c) => c.status === 'open')
8735
+ const localDay = localDayOf(Date.now())
8736
+ const due = open.filter((c) => c.dueAt && c.dueAt.slice(0, 10) <= localDay)
8737
+ const reminders = buildReminders(reminderLedgerFromRows(rows), { now: new Date() })
8738
+ const deliveries = store?.listDeliveries(3) ?? []
8739
+ return { localDay, open, due, reminders, deliveries }
8740
+ }
8741
+
8742
+ /** Column budget for the snapshot: --width, then ADVISERS_SHELL_WIDTH, then stdout. */
8743
+ function tuiOutputWidth(tuiKernel, explicitWidth) {
8744
+ const override = explicitWidth !== undefined ? Number(explicitWidth) : Number(process.env.ADVISERS_SHELL_WIDTH)
8745
+ return Number.isFinite(override) && override > 0
8746
+ ? tuiKernel.clampColumns(override)
8747
+ : tuiKernel.clampColumns(process.stdout.columns)
8748
+ }
8749
+
8750
+ /**
8751
+ * Human snapshot lines through the render kernel. Every line is sanitised
8752
+ * (ledger/model text is untrusted display data), CJK-width wrapped and kept
8753
+ * within the column budget; the section headings stay compatible with the
8754
+ * 0.2.x dashboard (`Advisers TUI`, `open commitments`).
8755
+ */
8756
+ function tuiSnapshotLines(tuiKernel, data, width) {
8757
+ const reminders = data.reminders.length
8758
+ ? data.reminders.slice(0, 8).map((r) => '[' + r.level + '/' + r.bucket + '] ' + r.action + (r.dueAt ? ' · ' + r.dueAt.slice(0, 16) : ''))
8759
+ : ['(none)']
8760
+ const commitments = data.open.length
8761
+ ? data.open.slice(0, 8).map((c) => c.id + ' ' + c.creditor + ' · ' + c.action + (c.dueAt ? ' · ' + c.dueAt.slice(0, 10) : ''))
8762
+ : ['(none)']
8763
+ const deliveries = data.deliveries.length
8764
+ ? data.deliveries.map((d) => String(d.createdAt ?? '').slice(0, 16) + ' ' + (d.title ?? d.tool ?? d.id))
8765
+ : ['(none)']
8766
+ return tuiKernel.renderSnapshot({
8767
+ title: 'Advisers TUI (read-only)',
8768
+ sections: [
8769
+ { lines: [data.localDay + ' · open ' + data.open.length + ' · due ' + data.due.length + ' · reminders ' + data.reminders.length] },
8770
+ { heading: 'reminders:', lines: reminders },
8771
+ { heading: 'open commitments:', lines: commitments },
8772
+ { heading: 'recent deliveries:', lines: deliveries },
8773
+ ],
8774
+ }, { width, color: false })
8775
+ }
8776
+
8777
+ /**
8778
+ * Pure --json projection of the snapshot (plan 26 §5.2/§6.5). Display strings go
8779
+ * through jsonSafe() so the stream can never carry ANSI/C1/bidi into a terminal;
8780
+ * ids, timestamps and counts stay structured values.
8781
+ */
8782
+ function tuiSnapshotPayload(tuiKernel, data) {
8783
+ return tuiKernel.jsonSafe({
8784
+ ok: true,
8785
+ command: 'tui',
8786
+ mode: 'snapshot',
8787
+ generatedAt: new Date().toISOString(),
8788
+ localDay: data.localDay,
8789
+ counts: {
8790
+ open: data.open.length,
8791
+ due: data.due.length,
8792
+ reminders: data.reminders.length,
8793
+ deliveries: data.deliveries.length,
8794
+ },
8795
+ reminders: data.reminders.slice(0, 50).map((r) => ({
8796
+ commitmentId: r.commitmentId ?? null,
8797
+ level: r.level ?? null,
8798
+ bucket: r.bucket ?? null,
8799
+ action: r.action ?? '',
8800
+ dueAt: r.dueAt ?? null,
8801
+ })),
8802
+ commitments: data.open.slice(0, 50).map((c) => ({
8803
+ id: c.id ?? null,
8804
+ creditor: c.creditor ?? null,
8805
+ action: c.action ?? '',
8806
+ dueAt: c.dueAt ?? null,
8807
+ status: c.status ?? null,
8808
+ })),
8809
+ deliveries: data.deliveries.map((d) => ({
8810
+ id: d.id ?? null,
8811
+ createdAt: d.createdAt ?? null,
8812
+ title: d.title ?? null,
8813
+ tool: d.tool ?? null,
8814
+ })),
8815
+ })
8816
+ }
8817
+
8818
+ async function tui(args) {
8819
+ const parsed = parseStrictFlags(args, { booleans: ['once', 'json', 'help'], values: ['width'] })
8820
+ if (!parsed.ok) { usageFail(parsed.error, TUI_USAGE); return }
8821
+ if (parsed.positional.length) { usageFail('unexpected argument ' + parsed.positional[0], TUI_USAGE); return }
8822
+ if (parsed.flags.help === true) { console.log(TUI_USAGE); return }
8823
+ if (parsed.flags.width !== undefined && !/^[0-9]+$/.test(String(parsed.flags.width))) { usageFail('--width must be an integer 40..200', TUI_USAGE); return }
8824
+ const tuiKernel = await loadTui()
8825
+ const policy = await getOutputPolicy()
8826
+ const width = tuiOutputWidth(tuiKernel, parsed.flags.width)
8827
+ const data = await tuiSnapshotData()
8828
+ if (parsed.flags.json === true) {
8829
+ // --json is a pure single document on stdout; nothing human is printed first.
8830
+ console.log(tuiKernel.stringifyJson(tuiSnapshotPayload(tuiKernel, data)))
8831
+ return
8832
+ }
8833
+ const lines = tuiSnapshotLines(tuiKernel, data, width)
8834
+ // 0.3.0 M10 gate (plan 26 §6.1/§10.3): the interactive dashboard only runs
8835
+ // when stdin is a terminal AND the output policy allows cursor control. Pipes,
8836
+ // CI, --plain and --accessible get one plain snapshot and exit instead of
8837
+ // issuing a clear-screen or entering a readline loop that could wait forever.
8838
+ if (parsed.flags.once === true || !policy.interactive || !policy.cursorControl) {
8839
+ console.log(lines.join(String.fromCharCode(10)))
8840
+ return
5921
8841
  }
5922
- if (once) { console.log(render()); return }
5923
8842
  const readline = await import('node:readline')
5924
8843
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
5925
- const draw = () => { process.stdout.write('\x1b[2J\x1b[H' + render() + '\n\n[r] refresh [q] quit\n') }
8844
+ const clear = String.fromCharCode(27) + '[2J' + String.fromCharCode(27) + '[H'
8845
+ let current = data
8846
+ const draw = () => { process.stdout.write(clear + tuiSnapshotLines(tuiKernel, current, width).join(String.fromCharCode(10)) + String.fromCharCode(10, 10) + '[r] refresh [q] quit' + String.fromCharCode(10)) }
5926
8847
  draw()
8848
+ let finish = () => {}
5927
8849
  await new Promise((resolve) => {
5928
- const onKey = (str, key) => {
5929
- if (key?.name === 'q' || str === 'q') { rl.close(); resolve() }
5930
- else if (key?.name === 'r' || str === 'r') draw()
8850
+ const onKey = async (str, key) => {
8851
+ if (key?.name === 'q' || str === 'q') { finish(); return }
8852
+ if (key?.name === 'r' || str === 'r') {
8853
+ try { current = await tuiSnapshotData() } catch {}
8854
+ draw()
8855
+ }
5931
8856
  }
8857
+ finish = () => { process.stdin.off('keypress', onKey); rl.close(); resolve() }
5932
8858
  process.stdin.on('keypress', onKey)
5933
- rl.on('close', resolve)
8859
+ rl.on('close', () => { process.stdin.off('keypress', onKey); resolve() })
5934
8860
  })
8861
+ finish()
5935
8862
  }
5936
8863
 
5937
8864
  function syncPass() {
@@ -6110,9 +9037,18 @@ async function printEvidence(args) {
6110
9037
  if (positional[0] === 'verify') {
6111
9038
  const dir = positional[1] ?? (typeof flags.dir === 'string' ? flags.dir : undefined)
6112
9039
  if (!dir) { console.error('usage: advisers evidence verify <dir>'); process.exitCode = 1; return }
6113
- const { verifyReceiptPackDir } = await loadReceiptVerify()
9040
+ const { verifyReceiptPackDir, RECEIPT_LIMIT_CODE } = await loadReceiptVerify()
9041
+ // The verifier caps entries/depth/file size/total size/SHA256SUMS/manifest
9042
+ // for an untrusted pack (lib/receipt-verify.js). A pack that trips a cap is
9043
+ // reported with the stable code and exits 1; stdout stays one pure JSON
9044
+ // document (the code is also in the JSON), the human hint goes to stderr.
6114
9045
  const result = verifyReceiptPackDir(dir)
6115
9046
  console.log(JSON.stringify(result, null, 2))
9047
+ if (result.code === RECEIPT_LIMIT_CODE) {
9048
+ const violation = result.limitViolation ?? {}
9049
+ console.error(sanitizeConsoleText(RECEIPT_LIMIT_CODE + ': receipt pack ' + (violation.limit ?? 'limit') + ' exceeded ' + (violation.max ?? '?') + ' (actual ' + (violation.actual ?? '?') + '); refusing to verify a pack that could exhaust memory or time.', { max: 2000 }))
9050
+ console.error('hint: inspect the directory before retrying; a legitimate pack is far below these limits.')
9051
+ }
6116
9052
  process.exitCode = result.ok ? 0 : 1
6117
9053
  return
6118
9054
  }
@@ -6151,6 +9087,35 @@ async function printEvidence(args) {
6151
9087
  if (unverifiable.length) console.log(' 说明:manual/operator-entered 证据由用户手工录入;本地无法外部核验,不计入 missing。')
6152
9088
  }
6153
9089
 
9090
+ /**
9091
+ * A-1 (0.2.5): secrecy level of the matter an item/delivery row belongs to.
9092
+ * No matter id -> 0 (a global row). A named matter the loaded ledger cannot
9093
+ * resolve -> Infinity, i.e. treated as protected: a clearance gate never
9094
+ * guesses a level for a row it cannot see.
9095
+ */
9096
+ function itemMatterSecrecy(ledger, matterId) {
9097
+ if (typeof matterId !== 'string' || !matterId) return 0
9098
+ let matter
9099
+ try { matter = typeof ledger?.getMatter === 'function' ? ledger.getMatter(matterId) : undefined } catch { matter = undefined }
9100
+ if (!matter && typeof ledger?.listMatters === 'function') {
9101
+ try { matter = ledger.listMatters().find((row) => row?.id === matterId) } catch { matter = undefined }
9102
+ }
9103
+ return matter ? secrecyLevel(matter) : Number.POSITIVE_INFINITY
9104
+ }
9105
+
9106
+ /**
9107
+ * Map a ProtectedEvidenceError from buildEvidencePack to a fail-closed CLI
9108
+ * exit. Only the count/clearance and a fixed hint are printed: no id, title,
9109
+ * creditor, action or quote.
9110
+ */
9111
+ function reportProtectedPackError(error) {
9112
+ if (error?.code !== 'E_SECRECY_BLOCKED') return false
9113
+ console.error('error: ' + error.message)
9114
+ if (error.hint) console.error('hint: ' + error.hint)
9115
+ process.exitCode = 1
9116
+ return true
9117
+ }
9118
+
6154
9119
  async function evidencePack(args) {
6155
9120
  const { flags, positional } = parseFlags(args)
6156
9121
  ensureHome()
@@ -6170,7 +9135,17 @@ async function evidencePack(args) {
6170
9135
  try {
6171
9136
  // Performance audit P1-1: --all was parsed but never forwarded, so the
6172
9137
  // documented escape hatch was a no-op and large ledgers always failed.
6173
- pack = buildEvidencePack({ store, ledger, ids: targetIds, all: flags.all === true })
9138
+ // A-1 (0.2.5): every included row is judged by its own matter's secrecy.
9139
+ // Explicit --ids must fail closed (never a silently partial answer); the
9140
+ // bulk path excludes protected rows and reports the count.
9141
+ pack = buildEvidencePack({
9142
+ store,
9143
+ ledger,
9144
+ ids: targetIds,
9145
+ all: flags.all === true,
9146
+ clearance: 0,
9147
+ protectedPolicy: ids ? 'error' : 'exclude',
9148
+ })
6174
9149
  } catch (error) {
6175
9150
  if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
6176
9151
  console.error('error: ' + error.message)
@@ -6178,6 +9153,7 @@ async function evidencePack(args) {
6178
9153
  process.exitCode = 1
6179
9154
  return
6180
9155
  }
9156
+ if (reportProtectedPackError(error)) return
6181
9157
  throw error
6182
9158
  }
6183
9159
  const out = flags.out ? String(flags.out) : join(HOME, 'evidence', `evidence-${new Date().toISOString().replace(/[:.]/g, '-')}`)
@@ -6196,15 +9172,22 @@ async function evidencePack(args) {
6196
9172
  receipt = join(out, 'receipt.docx')
6197
9173
  } catch (error) { console.error(`docx receipt skipped: ${error.message}`) }
6198
9174
  const verification = verifyPack(pack.files)
6199
- // Delivery row + audit row commit together (robustness audit P0-3).
9175
+ const protectedExcluded = Number.isInteger(pack.summary?.protectedExcluded) ? pack.summary.protectedExcluded : 0
9176
+ // Delivery row + audit row commit together (robustness audit P0-3). The audit
9177
+ // reason records the withheld count (a number, never protected content).
6200
9178
  recordDeliveryWithAudit({
6201
9179
  files: [join(out, 'manifest.json'), join(out, 'README.txt'), join(out, 'SHA256SUMS'), ...(receipt ? [receipt] : [])],
6202
9180
  tool: 'evidence-pack',
6203
9181
  title: 'evidence pack',
6204
9182
  validation: verification,
6205
- audit: { actor: 'local', action: 'evidence.pack', allowed: true, reason: `${pack.summary?.entryCount ?? 0} entries` },
9183
+ audit: {
9184
+ actor: 'local',
9185
+ action: 'evidence.pack',
9186
+ allowed: true,
9187
+ reason: `${pack.summary?.entryCount ?? 0} entries${protectedExcluded ? ', ' + protectedExcluded + ' protected excluded' : ''}`,
9188
+ },
6206
9189
  })
6207
- console.log(JSON.stringify({ out, files: Object.keys(pack.files), receipt, verification }, null, 2))
9190
+ console.log(JSON.stringify({ out, files: Object.keys(pack.files), receipt, verification, clearance: 0, protectedExcluded }, null, 2))
6208
9191
  if (!verification.ok) process.exitCode = 1
6209
9192
  }
6210
9193
 
@@ -6299,9 +9282,22 @@ async function receiptPack(args) {
6299
9282
  process.exitCode = 1
6300
9283
  return
6301
9284
  }
9285
+ // A-1 (0.2.5): a receipt copies the delivered artifacts and may span every
9286
+ // matter in the ledger. A row from a protected matter is never copied/read;
9287
+ // only a count is reported. Receipts have no per-delivery explicit selection
9288
+ // (--ids names evidence ids), so this path is exclude-only.
9289
+ const visibleRows = []
9290
+ let protectedDeliveries = 0
9291
+ for (const row of rows) {
9292
+ if (itemMatterSecrecy(ledger, row.matterId) > 0) {
9293
+ protectedDeliveries += 1
9294
+ continue
9295
+ }
9296
+ visibleRows.push(row)
9297
+ }
6302
9298
  const skippedFiles = []
6303
9299
  const deliveries = []
6304
- for (const row of rows) {
9300
+ for (const row of visibleRows) {
6305
9301
  const files = []
6306
9302
  for (const file of Array.isArray(row.files) ? row.files : []) {
6307
9303
  try {
@@ -6320,7 +9316,9 @@ async function receiptPack(args) {
6320
9316
  })
6321
9317
  }
6322
9318
  if (!deliveries.length) {
6323
- console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
9319
+ if (skippedFiles.length) console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
9320
+ if (protectedDeliveries) console.error(`另有 ${protectedDeliveries} 条交付记录属于受保护事项(secrecy>0),已排除。`)
9321
+ else if (!skippedFiles.length) console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
6324
9322
  if (skippedFiles.length) console.error('缺失:' + skippedFiles.slice(0, 5).join('; '))
6325
9323
  process.exitCode = 1
6326
9324
  return
@@ -6336,7 +9334,16 @@ async function receiptPack(args) {
6336
9334
  facts: ledger.listFacts().map((row) => row.id),
6337
9335
  preferences: ledger.listPreferences({ includeCandidates: false }).map((row) => row.id),
6338
9336
  }
6339
- evidence = buildEvidencePack({ store, ledger, ids: targetIds, all: flags.all === true })
9337
+ // A-1 (0.2.5): per-item clearance for the embedded evidence entries too.
9338
+ // Explicit --ids fail closed; the bulk path excludes protected rows.
9339
+ evidence = buildEvidencePack({
9340
+ store,
9341
+ ledger,
9342
+ ids: targetIds,
9343
+ all: flags.all === true,
9344
+ clearance: 0,
9345
+ protectedPolicy: ids ? 'error' : 'exclude',
9346
+ })
6340
9347
  } catch (error) {
6341
9348
  if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
6342
9349
  console.error('error: ' + error.message)
@@ -6344,6 +9351,7 @@ async function receiptPack(args) {
6344
9351
  process.exitCode = 1
6345
9352
  return
6346
9353
  }
9354
+ if (reportProtectedPackError(error)) return
6347
9355
  throw error
6348
9356
  }
6349
9357
  const out = typeof flags.out === 'string'
@@ -6379,17 +9387,31 @@ async function receiptPack(args) {
6379
9387
  return
6380
9388
  }
6381
9389
  const summary = pack.summary
9390
+ const evidenceProtectedExcluded = Number.isInteger(evidence?.summary?.protectedExcluded) ? evidence.summary.protectedExcluded : 0
9391
+ const protectedExcluded = protectedDeliveries + evidenceProtectedExcluded
6382
9392
  try {
6383
9393
  recordDeliveryWithAudit({
6384
9394
  files: [join(summary.outDir, 'manifest.json'), join(summary.outDir, 'README.txt'), join(summary.outDir, 'SHA256SUMS'), join(summary.outDir, 'receipt.docx')],
6385
9395
  tool: 'receipt-pack',
6386
9396
  title: 'delivery receipt pack',
6387
9397
  validation: 'receipt-pack-v1.1: ' + summary.verifyStatus,
6388
- audit: { actor: 'local', action: 'receipt.pack', allowed: true, reason: deliveries.length + ' deliveries/' + summary.fileCount + ' files' },
9398
+ audit: {
9399
+ actor: 'local',
9400
+ action: 'receipt.pack',
9401
+ allowed: true,
9402
+ reason:
9403
+ deliveries.length +
9404
+ ' deliveries/' +
9405
+ summary.fileCount +
9406
+ ' files' +
9407
+ (protectedDeliveries ? ', ' + protectedDeliveries + ' protected deliveries excluded' : '') +
9408
+ (evidenceProtectedExcluded ? ', ' + evidenceProtectedExcluded + ' protected evidence excluded' : ''),
9409
+ },
6389
9410
  })
6390
9411
  } catch {}
6391
- const { verifyReceiptPackDir } = await loadReceiptVerify()
9412
+ const { verifyReceiptPackDir, RECEIPT_LIMIT_CODE } = await loadReceiptVerify()
6392
9413
  const verification = verifyReceiptPackDir(summary.outDir)
9414
+ if (verification.code === RECEIPT_LIMIT_CODE) console.error(sanitizeConsoleText(RECEIPT_LIMIT_CODE + ': the receipt pack just written exceeds a resource limit; do not trust it until inspected.', { max: 2000 }))
6393
9415
  console.log(JSON.stringify({
6394
9416
  ok: verification.ok,
6395
9417
  format: summary.format,
@@ -6404,6 +9426,10 @@ async function receiptPack(args) {
6404
9426
  manifestDigest: summary.manifestDigest,
6405
9427
  receiptSha256: summary.receiptSha256,
6406
9428
  evidence: summary.evidence,
9429
+ clearance: 0,
9430
+ protectedExcluded,
9431
+ deliveriesProtectedExcluded: protectedDeliveries,
9432
+ evidenceProtectedExcluded,
6407
9433
  files: summary.files,
6408
9434
  skippedFiles,
6409
9435
  verification: {
@@ -6911,7 +9937,7 @@ async function soul(sub, file) {
6911
9937
  */
6912
9938
  const TOS_EXEMPT_COMMANDS = new Set([
6913
9939
  'help', '--help', '-h', 'version', '--version', '-v', 'status', 'doctor', 'init', 'tos',
6914
- 'privacy', 'export', 'audit', 'purge',
9940
+ 'privacy', 'export', 'audit', 'purge', 'backups',
6915
9941
  ])
6916
9942
  /** Known commands. Unknown commands keep the plain "unknown command" error, not the gate. */
6917
9943
  const KNOWN_COMMANDS = new Set([
@@ -6919,9 +9945,12 @@ const KNOWN_COMMANDS = new Set([
6919
9945
  'deliver', 'timestamp', 'tui', 'ocr', 'evidence', 'receipt', 'deliveries', 'learn', 'commit', 'diff',
6920
9946
  'undo', 'compact', 'search', 'nudge', 'risks', 'pet-brief', 'today', 'tick', 'ui', 'remind', 'calendar',
6921
9947
  'who', 'memory', 'digest', 'week', 'prefs', 'privacy', 'audit', 'purge', 'decay', 'correct', 'ls', 'why',
6922
- 'forget', 'sync', 'vault', 'export', 'import', 'backup', 'brief', 'review', 'research', 'capture', 'policy',
9948
+ 'forget', 'sync', 'vault', 'export', 'import', 'backup', 'backups', 'restore', 'brief', 'review', 'research', 'capture', 'policy',
6923
9949
  'office-edit', 'office-read', 'verify', 'office', 'routine', 'template', 'link', 'bridge', 'soul', 'tos',
6924
9950
  'matter', 'agenda', 'morning',
9951
+ // 0.3.0 customer entities: reads and writes both go through the L1/TOS gate
9952
+ // (they touch the local ledger); there is no exempt customer command.
9953
+ 'client', 'project',
6925
9954
  ])
6926
9955
 
6927
9956
  /** Append a TOS audit row; audit is best-effort (JSON store has no audit chain). */
@@ -6968,6 +9997,38 @@ async function maybeSourceModifiedNotice(tos) {
6968
9997
  } catch {}
6969
9998
  }
6970
9999
 
10000
+ let tosEnvOverrideAudited = false
10001
+
10002
+ /**
10003
+ * Resolve TOS facts from the packaged manifest (0.3.0 P0-S3).
10004
+ *
10005
+ * lib/tos keeps an ADVISERS_TOS_VERSION override for debugging, but the consent
10006
+ * gate and the acceptance record must never follow it: an env variable could
10007
+ * otherwise write a fake version into tos.json and the audit chain. bin/
10008
+ * therefore always passes the manifest version explicitly (the DSH read facade
10009
+ * does the same in lib/ledger-read.js), records one
10010
+ * `tos.env_override_ignored` audit row per process when the env is set, and
10011
+ * surfaces it as a warning in `tos status`. `tos show --as-version <v>` stays
10012
+ * available as an explicit, display-only debug switch.
10013
+ */
10014
+ function resolveTosFacts(tos) {
10015
+ const manifest = tos.readManifest()
10016
+ const info = tos.currentTos({ version: manifest.version })
10017
+ const raw = typeof process.env.ADVISERS_TOS_VERSION === 'string' ? process.env.ADVISERS_TOS_VERSION.trim() : ''
10018
+ const envOverride = raw
10019
+ ? { set: true, ignored: true, requestedVersion: raw, manifestVersion: manifest.version }
10020
+ : { set: false, ignored: false, requestedVersion: null, manifestVersion: manifest.version }
10021
+ if (raw && !tosEnvOverrideAudited) {
10022
+ tosEnvOverrideAudited = true
10023
+ // Audit once per process, and only when an audit chain already exists so a
10024
+ // read-only `tos status` never creates a database just to record this.
10025
+ if (mode === 'sqlite' && existsSync(DB)) {
10026
+ tosAudit('tos.env_override_ignored', false, `event=TOS_ENV_OVERRIDE_IGNORED;envVersion=${safeAuditToken(raw, 'redacted')};manifestVersion=${manifest.version};scope=app`)
10027
+ }
10028
+ }
10029
+ return { info, envOverride }
10030
+ }
10031
+
6971
10032
  /** L1 gate: run before dispatch; exits the process on block/reject (exit 3 / exit 1). */
6972
10033
  async function tosGate() {
6973
10034
  const isTTY = Boolean(process.stdin.isTTY)
@@ -6977,7 +10038,7 @@ async function tosGate() {
6977
10038
  else if (command === 'evidence' && args[0] === 'verify') return
6978
10039
  else if (TOS_EXEMPT_COMMANDS.has(command) || !KNOWN_COMMANDS.has(command)) return
6979
10040
  const tos = await loadTos()
6980
- const info = tos.currentTos()
10041
+ const { info } = resolveTosFacts(tos)
6981
10042
  const status = tos.acceptanceStatus({ home: HOME, version: info.version, sha256: info.sha256 })
6982
10043
  if (status.accepted) { await maybeSourceModifiedNotice(tos); return }
6983
10044
  const explicit = tos.resolveConsent({ flag: acceptTosFlag, env: process.env.ADVISERS_ACCEPT_TOS, version: info.version, isTTY })
@@ -7007,7 +10068,7 @@ async function tosGate() {
7007
10068
  /** L2 gate: per-modification re-confirmation (TOS §2.3). Returns true when allowed. */
7008
10069
  async function requireTosReaccept({ scope, subject = '', action }) {
7009
10070
  const tos = await loadTos()
7010
- const info = tos.currentTos()
10071
+ const { info } = resolveTosFacts(tos)
7011
10072
  const isTTY = Boolean(process.stdin.isTTY)
7012
10073
  const extra = `;scope=${scope}${subject ? `;subject=${subject}` : ''};action=${action ?? '-'}`
7013
10074
  const explicit = tos.resolveConsent({ flag: acceptTosFlag, env: process.env.ADVISERS_ACCEPT_TOS, version: info.version, isTTY })
@@ -7055,11 +10116,12 @@ function tosAuditState() {
7055
10116
  }
7056
10117
  }
7057
10118
 
7058
- function tosStatusFacts(tos, info, status) {
10119
+ function tosStatusFacts(tos, info, status, envOverride = null) {
7059
10120
  const record = status.record
7060
10121
  return {
7061
10122
  version: info.version,
7062
10123
  manifestVersion: info.manifestVersion,
10124
+ envOverride: envOverride ?? { set: false, ignored: false, requestedVersion: null, manifestVersion: info.manifestVersion },
7063
10125
  effectiveFrom: info.effectiveFrom,
7064
10126
  textSha256: info.sha256,
7065
10127
  canonical: info.canonical,
@@ -7081,8 +10143,8 @@ function tosStatusFacts(tos, info, status) {
7081
10143
  }
7082
10144
  }
7083
10145
 
7084
- function printTosStatus(tos, info, status, asJson) {
7085
- const facts = tosStatusFacts(tos, info, status)
10146
+ function printTosStatus(tos, info, status, asJson, envOverride = null) {
10147
+ const facts = tosStatusFacts(tos, info, status, envOverride)
7086
10148
  if (asJson) { console.log(JSON.stringify(facts, null, 2)); return }
7087
10149
  const record = facts.acceptance
7088
10150
  console.log(`version ${facts.version}(生效 ${facts.effectiveFrom};manifest ${facts.manifestVersion})`)
@@ -7096,6 +10158,9 @@ function printTosStatus(tos, info, status, asJson) {
7096
10158
  console.log(`terms ${facts.termsPath}`)
7097
10159
  console.log(`url ${facts.url}`)
7098
10160
  console.log(`store ${facts.store.type}${facts.store.path ? ` (${facts.store.path})` : ''}`)
10161
+ if (facts.envOverride?.set) {
10162
+ console.log(`warning ADVISERS_TOS_VERSION=${facts.envOverride.requestedVersion} 已被忽略:同意记录与门禁只认 manifest v${facts.envOverride.manifestVersion}(调试用 'advisers tos show --as-version <v>')`)
10163
+ }
7099
10164
  if (facts.audit.available) {
7100
10165
  const c = facts.audit.counts
7101
10166
  console.log(`audit ${facts.audit.verified ? 'verified' : `BROKEN at seq ${facts.audit.brokenAt}`} · ${facts.audit.count} entries · tos.accept=${c.accept} tos.block=${c.block} tos.reaccept=${c.reaccept} tos.revoke=${c.revoke}`)
@@ -7116,18 +10181,26 @@ function tosUsage(version = '') {
7116
10181
  async function tosCommand(argv) {
7117
10182
  const tos = await loadTos()
7118
10183
  const sub = argv[0]
7119
- const info = tos.currentTos()
10184
+ const { info, envOverride } = resolveTosFacts(tos)
7120
10185
  if (!sub || sub === 'help' || sub === '--help') { tosUsage(info.version); return }
7121
10186
  const status = tos.acceptanceStatus({ home: HOME, version: info.version, sha256: info.sha256 })
7122
10187
  if (sub === 'show') {
7123
- console.log(`Advisers 使用条款 v${info.version}(生效 ${info.effectiveFrom})`)
7124
- console.log(`文本 SHA-256:${info.sha256}`)
7125
- console.log(`规范文本:${info.canonical};随包副本:${info.termsPath};在线:${info.url}`)
10188
+ let showInfo = info
10189
+ const asVersionIndex = argv.indexOf('--as-version')
10190
+ if (asVersionIndex !== -1) {
10191
+ const requested = argv[asVersionIndex + 1]
10192
+ if (!requested) { console.error('usage: advisers tos show [--as-version <version>]'); process.exitCode = 1; return }
10193
+ showInfo = tos.currentTos({ version: requested })
10194
+ console.error(`advisers: debug view only — showing v${requested} (manifest v${info.version}); the consent gate and record are not affected.`)
10195
+ }
10196
+ console.log(`Advisers 使用条款 v${showInfo.version}(生效 ${showInfo.effectiveFrom})`)
10197
+ console.log(`文本 SHA-256:${showInfo.sha256}`)
10198
+ console.log(`规范文本:${showInfo.canonical};随包副本:${showInfo.termsPath};在线:${showInfo.url}`)
7126
10199
  console.log('---')
7127
- process.stdout.write(readFileSync(info.termsPath, 'utf8'))
10200
+ process.stdout.write(readFileSync(showInfo.termsPath, 'utf8'))
7128
10201
  return
7129
10202
  }
7130
- if (sub === 'status') { printTosStatus(tos, info, status, argv.includes('--json')); return }
10203
+ if (sub === 'status') { printTosStatus(tos, info, status, argv.includes('--json'), envOverride); return }
7131
10204
  if (sub === 'accept') {
7132
10205
  if (status.accepted) {
7133
10206
  console.log(`已接受使用条款 v${info.version}(channel=${status.record.channel},${status.record.acceptedAt});撤回:advisers tos revoke。`)
@@ -7138,7 +10211,7 @@ async function tosCommand(argv) {
7138
10211
  if (explicit?.error) { console.error(`advisers: ${explicit.error}`); process.exitCode = 1; return }
7139
10212
  if (explicit?.ok) {
7140
10213
  await recordTosAcceptance(tos, info, { channel: explicit.channel, nonInteractive: true })
7141
- console.log(`已接受使用条款 v${info.version}(channel=${explicit.channel},nonInteractive=1);已写入本地审计链。`)
10214
+ console.log(`已接受使用条款 v${info.version}(channel=${explicit.channel},nonInteractive=1);已写入本地审计链。${envOverride?.set ? ` ADVISERS_TOS_VERSION=${envOverride.requestedVersion} 已忽略。` : ''}`)
7142
10215
  return
7143
10216
  }
7144
10217
  if (!isTTY) {
@@ -7199,7 +10272,9 @@ if (!command) {
7199
10272
  } else if (command === 'chat') {
7200
10273
  await chat(args)
7201
10274
  } else if (command === 'status') {
7202
- printStatus(args.includes('--json'))
10275
+ const parsed = parseStrictFlags(args, { booleans: ['json'], positional: false })
10276
+ if (!parsed.ok) usageFail(parsed.error, 'usage: advisers status [--json]')
10277
+ else printStatus(parsed.flags.json === true)
7203
10278
  } else if (command === 'doctor') {
7204
10279
  await doctor(args)
7205
10280
  } else if (command === 'init') {
@@ -7417,6 +10492,12 @@ if (!command) {
7417
10492
  console.log(`done: ${id}`)
7418
10493
  } catch (error) { reportCommandFailure(error) }
7419
10494
  }
10495
+ } else if (flags.json === true) {
10496
+ // 0.3.0 JSON contract (plan 26 §5.4): a failed --json invocation must not
10497
+ // print human prose on stdout. Unknown subcommands (e.g. `commit show`) get
10498
+ // the error envelope on stderr, an empty stdout and exit 1.
10499
+ console.error(JSON.stringify({ error: { code: 'E_USAGE', message: 'unknown commit subcommand: ' + String(sub ?? ''), hint: 'usage: advisers commit add|edit|ls|done|snooze [--json]' } }))
10500
+ process.exitCode = 1
7420
10501
  } else { console.error('usage: advisers commit add|edit|ls|done|snooze'); process.exitCode = 1 }
7421
10502
  } else if (command === 'diff') {
7422
10503
  const { diffLatest } = await loadUndo()
@@ -7477,7 +10558,10 @@ if (!command) {
7477
10558
  const asJson = args.includes('--json')
7478
10559
  if (asJson || sources) {
7479
10560
  // The JSON contract and --sources need full commitment entities (evidence).
7480
- const ledger = readLedgerForCommand({ commitments: sources ? {} : { status: 'open' } })
10561
+ // 0.3.0 P0-T1: 'table' reads the table without the status index, so the
10562
+ // historical rowid order is kept with no ORDER BY rowid TEMP B-TREE spill
10563
+ // (today --json used to write 10 MB per run at a 200k-row ledger).
10564
+ const ledger = readLedgerForCommand({ commitments: sources ? {} : { status: 'open', order: 'table' } })
7481
10565
  await today(ledger.openCommitments(), { calendar: args.includes('--calendar'), sources, json: asJson, ledger })
7482
10566
  } else {
7483
10567
  // Human view: six columns + the cached classification (0.2.3 hot path).
@@ -7589,6 +10673,10 @@ if (!command) {
7589
10673
  else printMemory(loadReadLedger({ preferences: {}, commitments: {}, routines: {} }))
7590
10674
  } else if (command === 'matter') {
7591
10675
  await matterCommand(args)
10676
+ } else if (command === 'client') {
10677
+ clientCommand(args)
10678
+ } else if (command === 'project') {
10679
+ projectCommand(args)
7592
10680
  } else if (command === 'agenda') {
7593
10681
  await agendaCommand(args)
7594
10682
  } else if (command === 'morning') {
@@ -7599,22 +10687,30 @@ if (!command) {
7599
10687
  const period = args[0] === 'week' ? 'week' : 'day'
7600
10688
  const store = readStoreOrExit()
7601
10689
  const { buildDigest } = await loadDigest()
7602
- const ledger = mode === 'json' ? loadJson() : loadReadLedger({ commitments: {} })
10690
+ // 0.3.0 P0-T2: digest reads status/action/dueAt/doneAt only; the narrow
10691
+ // projection keeps rowid order without mapping 100k full entities.
10692
+ const commitments = mode === 'json' || !store
10693
+ ? loadJson().listCommitments()
10694
+ : store.read(() => store.projectCommitmentsForDigest())
7603
10695
  const conversationId = store?.listSessions(1)?.[0]?.conversationId ?? 'local'
7604
10696
  const { turns, deliveries } = store
7605
10697
  ? store.read(() => ({ turns: store.listTurns(conversationId, 200), deliveries: store.listDeliveries(100) }))
7606
10698
  : { turns: [], deliveries: [] }
7607
- console.log(buildDigest({ period, turns, commitments: ledger.listCommitments(), deliveries }))
10699
+ console.log(buildDigest({ period, turns, commitments, deliveries }))
7608
10700
  }
7609
10701
  } else if (command === 'week') {
7610
- if (mode === 'json') printWeek(loadJson())
7611
- else printWeek(loadReadLedger({ commitments: {} }))
10702
+ // --json is the output flag; `mode` is the store (sqlite|json) and must not
10703
+ // decide the output format (0.2.4 bug: `advisers week --json` printed Chinese
10704
+ // human text even in SQLite mode).
10705
+ const weekJson = args.includes('--json')
10706
+ const weekLedger = mode === 'json' ? loadJson() : loadReadLedger({ commitments: {} })
10707
+ printWeek(weekLedger, weekJson)
7612
10708
  } else if (command === 'prefs') {
7613
10709
  printPreferences()
7614
10710
  } else if (command === 'privacy') {
7615
- printPrivacy(args)
10711
+ await printPrivacy(args)
7616
10712
  } else if (command === 'audit') {
7617
- printAudit(args)
10713
+ await auditCommand(args)
7618
10714
  } else if (command === 'purge') {
7619
10715
  purgeMatter(args[0], args.includes('--yes'))
7620
10716
  } else if (command === 'decay') {
@@ -7695,12 +10791,17 @@ if (!command) {
7695
10791
  else if (sub === 'status' || !sub) vaultStatus()
7696
10792
  else { console.error('usage: advisers vault seal [--out file] [--remove] | unseal [file] | status'); process.exitCode = 1 }
7697
10793
  } else if (command === 'export') {
7698
- const { flags } = parseFlags(args)
7699
- await exportLedger(flags.all === true || args.includes('--all'), { encrypted: args.includes('--encrypted'), out: typeof flags.out === 'string' ? flags.out : undefined })
10794
+ const parsed = parseStrictFlags(args, { booleans: ['all', 'encrypted'], values: ['out'], positional: false })
10795
+ if (!parsed.ok) usageFail(parsed.error, 'usage: advisers export [--all] [--out <file>] [--encrypted]')
10796
+ else await exportLedger(parsed.flags.all === true, { encrypted: parsed.flags.encrypted === true, out: typeof parsed.flags.out === 'string' ? parsed.flags.out : undefined })
7700
10797
  } else if (command === 'import') {
7701
10798
  await importLedger(args.find((a) => !a.startsWith('--')), { replace: args.includes('--replace') })
7702
10799
  } else if (command === 'backup') {
7703
- backup(args[0])
10800
+ await backupCommand(args)
10801
+ } else if (command === 'backups') {
10802
+ await backupsCommand(args)
10803
+ } else if (command === 'restore') {
10804
+ await restoreCommand(args)
7704
10805
  } else if (command === 'brief') {
7705
10806
  await brief(args.filter((a) => a !== '--deep').join(' ').trim(), args.includes('--deep'))
7706
10807
  } else if (command === 'review') {