advisers 0.3.1 → 0.4.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 (48) hide show
  1. package/README-zh.md +13 -15
  2. package/README.md +32 -22
  3. package/THIRD-PARTY-NOTICES.md +1 -1
  4. package/bin/advisers.js +2769 -183
  5. package/index.js +1 -1
  6. package/lib/brief-archive.js +267 -0
  7. package/lib/client-pack.js +1016 -0
  8. package/lib/consent.js +390 -0
  9. package/lib/credentials.js +195 -0
  10. package/lib/customer-read.js +524 -0
  11. package/lib/error-codes.js +516 -7
  12. package/lib/evidence.js +928 -120
  13. package/lib/kb-extract.js +626 -0
  14. package/lib/kb-facts.js +429 -0
  15. package/lib/kb-pages.js +1084 -0
  16. package/lib/kb.js +1036 -0
  17. package/lib/ledger-read.js +109 -1
  18. package/lib/mail-errors.js +46 -0
  19. package/lib/mail-extract.js +351 -0
  20. package/lib/mail-imap.js +446 -0
  21. package/lib/mail-import.js +176 -0
  22. package/lib/mail-parse.js +223 -0
  23. package/lib/mail-store.js +731 -0
  24. package/lib/mail.js +506 -0
  25. package/lib/mcp-server.js +397 -11
  26. package/lib/notify.js +265 -7
  27. package/lib/policy/decision.js +315 -0
  28. package/lib/policy/egress.js +268 -0
  29. package/lib/policy/errors.js +71 -0
  30. package/lib/policy/index.js +99 -0
  31. package/lib/policy/rules.js +468 -0
  32. package/lib/policy/surfaces.js +141 -0
  33. package/lib/receipt-verify.js +283 -26
  34. package/lib/receivables.js +1653 -0
  35. package/lib/scheduler.js +453 -9
  36. package/lib/shell.js +1406 -0
  37. package/lib/source.js +98 -3
  38. package/lib/sqlite.js +501 -49
  39. package/lib/tos/index.js +2 -2
  40. package/lib/tos/manifest.json +6 -6
  41. package/lib/tos/privacy.zh-CN.md +33 -20
  42. package/lib/tos/safety.zh-CN.md +7 -6
  43. package/lib/tos/summary.zh-CN.md +3 -2
  44. package/lib/tos/terms.zh-CN.md +31 -16
  45. package/lib/tui/labels.js +1 -1
  46. package/lib/tui/render.js +1 -1
  47. package/lib/urgency.js +467 -0
  48. package/package.json +4 -4
package/bin/advisers.js CHANGED
@@ -120,6 +120,24 @@ const loadContextWindow = lazyModule(() => import('../lib/context-window.js'))
120
120
  const loadPetBrief = lazyModule(() => import('../lib/pet-brief.js'))
121
121
  const loadImap = lazyModule(() => import('../lib/imap.js'))
122
122
  const loadUi = lazyModule(() => import('../lib/ui.js'))
123
+ // 0.4.0 (task-29): interactive shell + KB/mail/money/consent command families.
124
+ // Each one is only imported by the commands that need it, so ordinary commands
125
+ // keep the 0.3.2 startup graph (and --version/help pay for nothing extra).
126
+ const loadShell = lazyModule(() => import('../lib/shell.js'))
127
+ const loadUrgency = lazyModule(() => import('../lib/urgency.js'))
128
+ const loadBriefArchive = lazyModule(() => import('../lib/brief-archive.js'))
129
+ const loadKb = lazyModule(() => import('../lib/kb.js'))
130
+ const loadKbPages = lazyModule(() => import('../lib/kb-pages.js'))
131
+ const loadKbFacts = lazyModule(() => import('../lib/kb-facts.js'))
132
+ const loadMail = lazyModule(() => import('../lib/mail.js'))
133
+ const loadCredentials = lazyModule(() => import('../lib/credentials.js'))
134
+ const loadConsent = lazyModule(() => import('../lib/consent.js'))
135
+ const loadPolicy = lazyModule(() => import('../lib/policy/index.js'))
136
+ const loadMailStore = lazyModule(() => import('../lib/mail-store.js'))
137
+ const loadClientPack = lazyModule(() => import('../lib/client-pack.js'))
138
+ // Money sidecar: the library lands with the 0.4.0 receivables wave; the loader
139
+ // fails only when a money command is actually run, never at startup.
140
+ const loadReceivablesLib = lazyModule(() => import('../lib/receivables.js'))
123
141
 
124
142
  let core
125
143
  if (process.env.ADVISERS_CORE_LOCAL === '1') {
@@ -736,6 +754,35 @@ function loadOpenCommitmentRowsForToday() {
736
754
  return readProjection((store) => store.projectOpenCommitmentsForToday()) ?? []
737
755
  }
738
756
 
757
+ /**
758
+ * 0.3.2: parse `today --json --limit N` (additive cap; N full Commitment rows
759
+ * per bucket, counts stay the true totals). Requires --json and is not
760
+ * combinable with --sources, which needs the full evidence rows.
761
+ */
762
+ function parseTodayLimit(args) {
763
+ const index = args.indexOf('--limit')
764
+ if (index === -1) return { limit: null }
765
+ const raw = args[index + 1]
766
+ if (typeof raw !== 'string' || !/^[1-9][0-9]*$/.test(raw)) return { error: '--limit must be an integer 1..10000' }
767
+ const value = Number(raw)
768
+ if (value < 1 || value > 10000) return { error: '--limit must be an integer 1..10000' }
769
+ if (!args.includes('--json')) return { error: '--limit requires --json (the human view has its own cap)' }
770
+ if (args.includes('--sources')) return { error: '--limit cannot be combined with --sources (the source rows need full evidence)' }
771
+ return { limit: value }
772
+ }
773
+
774
+ /** Full Commitment entities for the capped today --json rows, id order preserved. */
775
+ function hydrateCommitmentsForToday(ids) {
776
+ if (!Array.isArray(ids) || !ids.length) return []
777
+ const store = readStoreOrExit()
778
+ if (!store) return []
779
+ try {
780
+ return store.read(() => ids.map((id) => store.getCommitment(id)).filter(Boolean))
781
+ } catch {
782
+ return []
783
+ }
784
+ }
785
+
739
786
  /** Narrow commitment rows for reminder planning (remind / tui). */
740
787
  function loadReminderRows({ includeUndated = false } = {}) {
741
788
  return readProjection((store) => store.projectCommitmentsForReminders({ includeUndated }))
@@ -1061,7 +1108,7 @@ const CONTRACTS_DISCOVERY = Object.freeze({
1061
1108
  mcpTools: 1,
1062
1109
  mcpResources: 1,
1063
1110
  mcpProtocol: '2024-11-05',
1064
- dshTools: 1,
1111
+ dshTools: 2,
1065
1112
  petBrief: 2,
1066
1113
  })
1067
1114
  function friendlyError(error) {
@@ -1165,7 +1212,8 @@ function help() {
1165
1212
  console.log(`advisers — a staff of AI advisers
1166
1213
 
1167
1214
  Usage:
1168
- advisers start the local conversation (TTY)
1215
+ advisers start the local conversation (TTY shell)
1216
+ (status line + result blocks; non-TTY prints help; ADVISERS_NO_SHELL=1 keeps the legacy REPL)
1169
1217
  advisers chat [--file <path>] [--allow-path <dir>]... [text]
1170
1218
  one-shot task, or start the local conversation
1171
1219
  advisers init initialize home + soul
@@ -1180,12 +1228,14 @@ Usage:
1180
1228
  advisers history recent conversations
1181
1229
  advisers search <text> full-text search old turns
1182
1230
  advisers compact ls|rollback summary versions
1183
- advisers today [--calendar] [--sources] [--json]
1231
+ advisers today [--calendar] [--sources] [--json [--limit n]]
1184
1232
  one-screen today/week/waiting view (+ local events)
1185
1233
  advisers remind [--json] [--ics [path]] [--deliver [--notify]] due reminders + ICS/VALARM export
1186
1234
  advisers remind install|uninstall|status [--apply] [--schedule "0 9 * * *"]
1187
1235
  scheduler scripts + OS plan (dry-run by default; --apply executes)
1188
- status also shows the last recorded run (scheduler/status.json)
1236
+ --morning adds the second morning block (--morning-time 08:30, --morning-days 1-5)
1237
+ status v2 shows the remind + morning sections and both OS plans
1238
+ advisers remind --json [--now ISO] reminders + per-row urgency (pure read)
1189
1239
  advisers calendar import --ics <file> local .ics read-only import
1190
1240
  advisers risks up to 3 deterministic obligation risks
1191
1241
  advisers pet-brief [--json] [--out [path]] [--check [--strict]] [--display-policy public|private|none]
@@ -1194,8 +1244,9 @@ Usage:
1194
1244
  advisers week [--json] last 7 local days (Asia/Shanghai); --json is one JSON document
1195
1245
  advisers agenda [--days 7] [--json]
1196
1246
  7-day agenda: commitments + calendar_events, Asia/Shanghai days
1197
- advisers morning [--json] [--out f]
1198
- deterministic local morning brief (no model, no network)
1247
+ advisers morning [--json] [--out f] [--top 1..5] [--archive [--keep 1..365]]
1248
+ deterministic local morning brief (no model, no network);
1249
+ --archive writes ~/.advisers/briefs/<day>.md + latest.md
1199
1250
  advisers digest day|week|morning short digest (morning = the deterministic brief)
1200
1251
  advisers diff show the last changed file
1201
1252
  advisers undo [--list] restore the last file write
@@ -1233,6 +1284,8 @@ Usage:
1233
1284
  [--limit n] [--clearance 0-3] [--json]
1234
1285
  advisers client archive <id> [--dry-run] [--json]
1235
1286
  advisers client merge <from> <into> [--dry-run] [--json]
1287
+ advisers client export <id> [--format md|docx] [--out <file>] [--redact-names] [--json]
1288
+ advisers client export <id> --pack [--out <dir>] [--force] [--json] client status pack v1 (no money fields)
1236
1289
  advisers client note add <id> "<summary>" [--kind k] [--at ISO] [--project id] [--matter id] [--json]
1237
1290
  advisers client note list <id> [--project id] [--limit n] [--json]
1238
1291
  advisers project add <client-id> "<name>" [--start YYYY-MM-DD] [--end YYYY-MM-DD]
@@ -1242,6 +1295,33 @@ Usage:
1242
1295
  advisers project archive <id> [--dry-run] [--json]
1243
1296
  customer/project entities + derived timeline (SQLite store;
1244
1297
  see docs/CLIENTS.md)
1298
+ advisers kb add <file>... [--title s] [--kind k] [--client|--project|--matter id] [--secrecy 0-3]
1299
+ [--replace] [--from list.txt] [--json] index a local document (text extracted locally)
1300
+ advisers kb ls|show <id>|rm <id>|purge <id>|reindex [--rebuild] [--json]
1301
+ list/inspect/tombstone/physically purge documents; reindex verifies/rebuilds KB FTS
1302
+ advisers kb page ls|show <id>|rebuild|diff ... deterministic compiled pages (client/project/timeline/facts)
1303
+ advisers kb search <q> [--scope kb|pages|all] [--limit n] [--clearance 0-3] [--json]
1304
+ local KB search (no model, no network; clearance filtered before counting)
1305
+ advisers search <q> --scope turns|kb|pages|facts|all [--json]
1306
+ scoped local search; without --scope the 0.3.2 turn search output is unchanged
1307
+ advisers fact show <id>|history <id>|as-of <YYYY-MM-DD|ISO> [--json]
1308
+ fact source/supersede chain/value as-of a moment (no model, no network)
1309
+ advisers mail account add --name n --host h [--port 993] [--tls tls|starttls] --user u [--pass-stdin]
1310
+ store an IMAP account; password only from the TTY prompt or stdin, never argv
1311
+ advisers mail account ls|show <acct>|rm <acct> [--json]
1312
+ advisers mail sync [<acct>] [--full] [--dry-run] [--json] the only IMAP network entry (read-only EXAMINE/FETCH)
1313
+ advisers mail ls|show <id> [--body]|purge [--older-than 30d] [--dry-run|--yes]|import <file|dir> [--json]
1314
+ local reads; purge clears bodies (metadata/hash stay); import reads .eml/.mbox offline
1315
+ advisers mail extract [<id>...] [--all-new] [--local|--model --yes] [--matter id] [--dry-run] [--json]
1316
+ default local rules (offline); --model needs --yes + ADVISERS_API_KEY + consent + secrecy 0
1317
+ advisers receivable add <client-id> "<label>" --amount 8000.00 [--due DATE] [--currency CNY] [--json]
1318
+ advisers receivable ls|show <id>|edit <id>|void <id> [--aging] [--json]
1319
+ money sidecars in integer minor units; amounts never enter MCP/receipt packs
1320
+ advisers payment add <client-id> --amount 4000.00 [--receivable rcv] [--method bank] [--json]
1321
+ advisers payment ls|void <id> [--json] payments reopen/complete the follow-up commitment atomically
1322
+ advisers consent status|grant <surface>|revoke <surface> [--data-class mail|kb] [--yes] [--json]
1323
+ separate model-egress consent (provider/base-URL bound; TTY typed confirmation)
1324
+ advisers privacy --matrix [--json] policy surface/action/gate matrix from the registry
1245
1325
  advisers privacy [--json] [--prove] show/verify local data & egress facts
1246
1326
  advisers why <pref-id> explain a preference
1247
1327
  advisers forget <pref-id> forget a preference (tombstone)
@@ -1269,7 +1349,7 @@ Usage:
1269
1349
  advisers capture --from-transcript <file> 转写稿导入→候选(不录音/不入会)
1270
1350
  advisers capture --from-imap 只读 IMAP 导入(EXAMINE/FETCH;env 凭据)
1271
1351
  advisers ui [--port n] 本地只读视图(127.0.0.1,GET only)
1272
- advisers mcp --stdio MCP server(7 工具 + 4 resources;写入口仅 pending 候选/回执校验)
1352
+ advisers mcp --stdio MCP server(8 工具 + 5 resources;写入口仅 pending 候选/回执校验)
1273
1353
  advisers evidence show <id> [--json] 承诺/事实/偏好→原文来源
1274
1354
  advisers deliver [--commit id] [--type confirmation|weekly|statement|ledger] [--format docx|xlsx|pdf] [--out f] 交付物
1275
1355
  advisers deliveries --pack [--out dir] [--ids ...] [--all] 证据包(manifest/README/SHA256SUMS + DOCX 回执;默认上限 2000)
@@ -1520,7 +1600,7 @@ function purgeMatter(id, confirmed) {
1520
1600
  function parseFlags(args) {
1521
1601
  const flags = {}
1522
1602
  const positional = []
1523
- const booleanFlags = new Set(['web', 'deep', 'all', 'yes', 'json', 'list', 'force', 'apply', 'quiet', 'help', 'content', 'ics', 'deliver', 'install', 'uninstall', 'status', 'calendar', 'sources', 'pack', 'receipt', 'from-imap', 'remove', 'force', 'notify', 'no-remind', 'dry-run', 'unclassified', 'no-calendar', 'include-done', 'record-delivery'])
1603
+ const booleanFlags = new Set(['web', 'deep', 'all', 'yes', 'json', 'list', 'force', 'apply', 'quiet', 'help', 'content', 'ics', 'deliver', 'install', 'uninstall', 'status', 'calendar', 'sources', 'pack', 'receipt', 'from-imap', 'remove', 'force', 'notify', 'no-remind', 'dry-run', 'unclassified', 'no-calendar', 'include-done', 'record-delivery', 'include-global', 'archive', 'morning', 'include-deleted', 'all-new', 'local', 'model', 'full', 'pass-stdin'])
1524
1604
  for (let i = 0; i < args.length; i++) {
1525
1605
  if (args[i].startsWith('--')) {
1526
1606
  const key = args[i].slice(2)
@@ -2216,6 +2296,7 @@ const CUSTOMER_USAGE = {
2216
2296
  projectList: 'usage: advisers project list [--client <id>] [--all] [--limit n] [--json]',
2217
2297
  projectShow: 'usage: advisers project show <id> [--timeline-limit n] [--clearance 0-3] [--json]',
2218
2298
  projectArchive: 'usage: advisers project archive <id> [--dry-run] [--json]',
2299
+ export: 'usage: advisers client export <id> [--format md|docx] [--out <file>] [--redact-names] [--json]\n advisers client export <id> --pack [--out <dir>] [--force] [--json]'
2219
2300
  }
2220
2301
 
2221
2302
  /** An application error with a stable E_* code and optional actionable hint. */
@@ -2687,6 +2768,7 @@ function clientUsage() {
2687
2768
  console.log(' ' + CUSTOMER_USAGE.merge)
2688
2769
  console.log(' ' + CUSTOMER_USAGE.note)
2689
2770
  console.log(' ' + CUSTOMER_USAGE.noteList)
2771
+ console.log(' ' + CUSTOMER_USAGE.export)
2690
2772
  console.log('客户是归属维度:matter 通过 --client/--project 挂到客户;commitments/facts 仍只挂 matter。')
2691
2773
  }
2692
2774
 
@@ -2777,7 +2859,7 @@ function clientList(rest) {
2777
2859
  } catch (error) { reportCustomerFailure(error) }
2778
2860
  }
2779
2861
 
2780
- function clientShow(rest) {
2862
+ async function clientShow(rest) {
2781
2863
  const usage = CUSTOMER_USAGE.show
2782
2864
  try {
2783
2865
  const parsed = customerFlags(rest, { booleans: ['json'], values: ['timeline-limit', 'clearance'] }, usage)
@@ -2786,6 +2868,9 @@ function clientShow(rest) {
2786
2868
  const timelineLimit = customerIntegerFlag(parsed.flags['timeline-limit'], 'timeline-limit', 0, CUSTOMER_TIMELINE_MAX, CUSTOMER_TIMELINE_DEFAULT, usage)
2787
2869
  if (!customerStoreOrFail()) return
2788
2870
  const store = readStoreOrExit()
2871
+ // 0.4.0 additive: money summary (no amounts beyond per-currency totals; the
2872
+ // lib also fails closed above clearance and only counts hidden rows).
2873
+ const money = await loadReceivablesLib().catch(() => null)
2789
2874
  const payload = store.read(() => {
2790
2875
  const view = readClientView(store, id)
2791
2876
  const filtered = clearCustomerView(view, clearance)
@@ -2824,6 +2909,7 @@ function clientShow(rest) {
2824
2909
  clearance: clearance,
2825
2910
  protectedExcluded: filtered.protectedExcluded,
2826
2911
  degraded: timeline.degraded,
2912
+ ...(money ? { receivables: money.clientReceivablesBlock(store, id, { clearance }) } : {}),
2827
2913
  }
2828
2914
  })
2829
2915
  const lines = []
@@ -3042,7 +3128,233 @@ function clientNoteList(rest) {
3042
3128
  } catch (error) { reportCustomerFailure(error) }
3043
3129
  }
3044
3130
 
3045
- function clientCommand(rawArgs) {
3131
+ /**
3132
+ * `advisers client export <id>`: deterministic, external-facing client status
3133
+ * sheet (markdown or DOCX). It is written at clearance 0, never contains
3134
+ * evidence quotes or note bodies, and states its own scope/limits: it is a
3135
+ * status summary, not a statement of account, contract or legal advice.
3136
+ *
3137
+ * The file is created 0600 (directory 0700) and its SHA-256 is reported in the
3138
+ * JSON summary so a recipient can verify the bytes out of band.
3139
+ */
3140
+ async function clientExport(rest) {
3141
+ const usage = CUSTOMER_USAGE.export
3142
+ try {
3143
+ const parsed = customerFlags(rest, { booleans: ['json', 'redact-names', 'pack', 'force', 'include-receivables'], values: ['format', 'out'] }, usage)
3144
+ if (parsed.flags['include-receivables'] === true) throw customerError('E_CLIENT_PACK_RECEIVABLES_UNSUPPORTED', 'client status packs do not carry receivable/payment amounts in 0.4.0', 'amounts stay local; --include-receivables is reserved until legal review (0.4.1)')
3145
+ const id = customerIdArg(parsed.positional, 0, 'a client id', usage)
3146
+ const format = parsed.flags.format === undefined ? 'md' : String(parsed.flags.format).toLowerCase()
3147
+ if (format !== 'md' && format !== 'docx') throw customerError('E_USAGE', '--format must be md or docx', usage)
3148
+ if (parsed.flags.out !== undefined && (typeof parsed.flags.out !== 'string' || !parsed.flags.out.trim())) {
3149
+ throw customerError('E_USAGE', '--out requires a file path', usage)
3150
+ }
3151
+ if (!customerStoreOrFail()) return
3152
+ const store = readStoreOrExit()
3153
+ const clearance = 0
3154
+ const generatedAt = new Date().toISOString()
3155
+ const data = store.read(() => {
3156
+ const view = readClientView(store, id)
3157
+ const filtered = clearCustomerView(view, clearance)
3158
+ const counts = customerClientCounts(store, view, filtered, clearance)
3159
+ const timeline = customerTimeline(view, filtered, { kinds: ['delivery', 'commitment'], limit: 20 })
3160
+ const open = customerOpenBuckets(view, filtered)
3161
+ const redact = parsed.flags['redact-names'] === true
3162
+ const projectRows = view.projects
3163
+ .filter((project) => project.status !== 'archived')
3164
+ .map((project) => {
3165
+ const summary = customerProjectOfClientCounts(store, view, filtered, project, clearance)
3166
+ return {
3167
+ id: project.id,
3168
+ name: redact ? '(已隐去)' : project.name,
3169
+ status: project.status,
3170
+ counts: summary.counts,
3171
+ nextDueAt: summary.nextDueAt,
3172
+ }
3173
+ })
3174
+ return {
3175
+ client: view.client,
3176
+ displayName: redact ? '(已隐去)' : view.client.name,
3177
+ aliases: redact ? [] : view.client.aliases,
3178
+ projects: projectRows,
3179
+ counts: counts,
3180
+ open: {
3181
+ mine: open.mine.map((row) => ({ id: row.id, action: row.action, dueAt: row.dueAt ?? null, projectId: row.projectId ?? null })),
3182
+ waiting: open.waiting.map((row) => ({ id: row.id, action: row.action, dueAt: row.dueAt ?? null, projectId: row.projectId ?? null })),
3183
+ },
3184
+ nextDueAt: customerNextDueAt(filtered.open),
3185
+ timeline: timeline.items.map((item) => ({ at: item.at, kind: item.kind, title: item.title, status: item.status ?? null })),
3186
+ timelineTotal: timeline.total,
3187
+ timelineTruncated: timeline.truncated,
3188
+ protectedExcluded: filtered.protectedExcluded,
3189
+ }
3190
+ })
3191
+ const disclaimer = '本文件是状态说明,不是对账单、合同、法律意见或送达证明;本地生成、无签名、未锚定(仅本地自证)。SHA-256 仅用于检测生成后的改动。'
3192
+ const scopeLine = '范围:本文件只含客户 ' + data.client.id + '(' + data.displayName + ')的数据;其他客户数据、全局 facts/preferences、对话原文与备注正文不在本文件内。'
3193
+ const sections = []
3194
+ sections.push({ heading: '概况', paragraphs: [
3195
+ '客户:' + data.displayName + ' (' + data.client.id + ') · 状态 ' + data.client.status + (data.aliases.length ? ' · 别名 ' + data.aliases.join('/') : ''),
3196
+ '事项 ' + data.counts.matters + '(归档 ' + data.counts.mattersArchived + ') · 未完成 我方 ' + data.counts.openMine + ' / 等待对方 ' + data.counts.openWaiting + ' · 逾期 ' + data.counts.overdue + ' · 交付 ' + data.counts.deliveries + ' · 备注 ' + data.counts.notes + '(仅计数)',
3197
+ '下一截止:' + (data.nextDueAt || '无'),
3198
+ '受保护事项(clearance=0 不可见,仅计数):' + data.protectedExcluded,
3199
+ ] })
3200
+ sections.push({ heading: '进行中的项目', paragraphs: data.projects.length
3201
+ ? data.projects.map((project) => project.id + ' ' + project.name + ' ' + project.status + ' · 事项 ' + project.counts.matters + ' · 未完成 ' + (project.counts.openMine + project.counts.openWaiting) + ' · 下一截止 ' + (project.nextDueAt || '无'))
3202
+ : ['(没有进行中的项目)'] })
3203
+ const openLines = (title, rows) => {
3204
+ const out = [title + '(' + rows.length + '):']
3205
+ if (!rows.length) out.push('(无)')
3206
+ for (const row of rows.slice(0, 20)) out.push('- ' + (row.dueAt ? row.dueAt + ' ' : '') + row.action + (row.projectId ? ' [' + row.projectId + ']' : ''))
3207
+ return out
3208
+ }
3209
+ sections.push({ heading: '待办', paragraphs: [...openLines('我方欠客户', data.open.mine), ...openLines('等待对方', data.open.waiting)] })
3210
+ sections.push({ heading: '最近时间线', paragraphs: data.timeline.length
3211
+ ? data.timeline.map((item) => String(item.at).replace('T', ' ').slice(0, 16) + ' ' + item.kind + ' ' + item.title + (item.status ? ' [' + item.status + ']' : ''))
3212
+ : ['(没有可展示的时间线条目)'] })
3213
+ sections.push({ heading: '边界与校验', paragraphs: [scopeLine, disclaimer, '生成时间:' + generatedAt + ' · advisers ' + VERSION + ' · clearance=0'] })
3214
+ const markdown = ['# 客户状态包 · ' + data.displayName, '', '> ' + scopeLine, '> ' + disclaimer, '',
3215
+ ...sections.flatMap((section) => ['## ' + section.heading, '', ...section.paragraphs, ''])].join('\n')
3216
+ let buffer
3217
+ if (format === 'docx') {
3218
+ let buildDocx
3219
+ try {
3220
+ buildDocx = await loadOfficeOperation('docx', 'buildDocx')
3221
+ } catch {}
3222
+ if (typeof buildDocx !== 'function') {
3223
+ throw customerError('E_USAGE', '--format docx 需要可选的 advisers-office 包(当前不可用)', 'advisers client export ' + data.client.id + ' --format md')
3224
+ }
3225
+ buffer = await buildDocx({ title: '客户状态包 · ' + data.displayName, sections: sections })
3226
+ } else {
3227
+ buffer = Buffer.from(markdown, 'utf8')
3228
+ }
3229
+ // 0.4.0: client status pack v2 (directory pack). The pack contains no money
3230
+ // fields (amounts stay local in 0.4.0; --include-receivables would fail
3231
+ // closed in the library), is written 0700/0600 atomically and self-verified.
3232
+ if (parsed.flags.pack === true) {
3233
+ const packLib = await loadClientPack()
3234
+ const statusPayload = {
3235
+ ok: true,
3236
+ command: 'client export',
3237
+ format: 'json',
3238
+ scope: 'client',
3239
+ subject: { kind: 'client', id: data.client.id, name: data.displayName },
3240
+ generatedAt: generatedAt,
3241
+ clearance: clearance,
3242
+ protectedExcluded: data.protectedExcluded,
3243
+ counts: data.counts,
3244
+ projects: data.projects,
3245
+ open: data.open,
3246
+ nextDueAt: data.nextDueAt,
3247
+ timeline: data.timeline,
3248
+ timelineTotal: data.timelineTotal,
3249
+ timelineTruncated: data.timelineTruncated,
3250
+ disclaimer: true,
3251
+ }
3252
+ const outDir = typeof parsed.flags.out === 'string' && parsed.flags.out.trim()
3253
+ ? parsed.flags.out.trim()
3254
+ : join(HOME, 'exports', 'client-' + data.client.id + '-' + generatedAt.replace(/[:.]/g, '-'))
3255
+ const packResult = packLib.exportClientStatusPack({
3256
+ outDir,
3257
+ status: statusPayload,
3258
+ markdown: markdown,
3259
+ ...(format === 'docx' ? { docx: buffer } : {}),
3260
+ subject: { kind: 'client', id: data.client.id, name: data.displayName },
3261
+ generatedAt: generatedAt,
3262
+ overwrite: parsed.flags.force === true,
3263
+ env: { advisersVersion: VERSION, command: 'client export --pack' },
3264
+ })
3265
+ try {
3266
+ const writeStore = dbStore()
3267
+ if (writeStore) {
3268
+ writeStore.appendAudit({
3269
+ actor: 'local',
3270
+ action: 'client.export',
3271
+ allowed: true,
3272
+ reason: 'client ' + data.client.id + ' format=pack bytes=' + packResult.bytes + ' files=' + packResult.fileCount + ' protected=' + data.protectedExcluded,
3273
+ })
3274
+ }
3275
+ } catch {}
3276
+ const payload = {
3277
+ ok: true,
3278
+ command: 'client export --pack',
3279
+ format: packResult.format,
3280
+ version: packResult.version,
3281
+ scope: packResult.scope,
3282
+ subject: packResult.subject,
3283
+ out: packResult.out,
3284
+ replaced: packResult.replaced,
3285
+ generatedAt: packResult.generatedAt,
3286
+ counts: packResult.counts,
3287
+ bytes: packResult.bytes,
3288
+ fileCount: packResult.fileCount,
3289
+ checksumCount: packResult.checksumCount,
3290
+ manifestDigest: packResult.manifestDigest,
3291
+ verificationBasis: packResult.verificationBasis,
3292
+ verification: packResult.verification,
3293
+ clearance: clearance,
3294
+ protectedExcluded: data.protectedExcluded,
3295
+ disclaimer: true,
3296
+ }
3297
+ const human = [
3298
+ '已生成客户状态包目录(pack v1):' + payload.out,
3299
+ '客户:' + data.displayName + ' (' + data.client.id + ') · files=' + payload.fileCount + ' · bytes=' + payload.bytes + ' · manifestDigest=' + String(payload.manifestDigest).slice(0, 16),
3300
+ '离线校验:' + (payload.verification.ok ? '通过(仅证明包内 SHA-256 自洽,不是签名/第三方存证)' : '失败:' + (payload.verification.errors ?? []).slice(0, 3).join(' | ')),
3301
+ '边界:状态说明,不是对账单/合同/法律意见;不含金额、对话原文与备注正文。',
3302
+ ]
3303
+ customerPrint(parsed.flags.json === true, payload, human)
3304
+ if (!payload.verification.ok) process.exitCode = 1
3305
+ return
3306
+ }
3307
+ const out = typeof parsed.flags.out === 'string'
3308
+ ? parsed.flags.out.trim()
3309
+ : join(HOME, 'exports', 'client-' + data.client.id + '-' + generatedAt.replace(/[:.]/g, '-') + '.' + format)
3310
+ const dir = dirname(out)
3311
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
3312
+ try { chmodSync(dir, 0o700) } catch {}
3313
+ writeFileSync(out, buffer, { mode: 0o600 })
3314
+ try { chmodSync(out, 0o600) } catch {}
3315
+ const sha256 = createHash('sha256').update(buffer).digest('hex')
3316
+ // A client status sheet is an external-facing artifact: record the export
3317
+ // (ids/counts only, no names) even though it does not mutate the ledger.
3318
+ try {
3319
+ const writeStore = dbStore()
3320
+ if (writeStore) {
3321
+ writeStore.appendAudit({
3322
+ actor: 'local',
3323
+ action: 'client.export',
3324
+ allowed: true,
3325
+ reason: 'client ' + data.client.id + ' format=' + format + ' bytes=' + buffer.length + ' protected=' + data.protectedExcluded,
3326
+ })
3327
+ }
3328
+ } catch {}
3329
+ const payload = {
3330
+ ok: true,
3331
+ command: 'client export',
3332
+ format: format,
3333
+ scope: 'client',
3334
+ subject: { kind: 'client', id: data.client.id, name: data.displayName },
3335
+ out: out,
3336
+ bytes: buffer.length,
3337
+ sha256: sha256,
3338
+ generatedAt: generatedAt,
3339
+ clearance: clearance,
3340
+ protectedExcluded: data.protectedExcluded,
3341
+ counts: data.counts,
3342
+ nextDueAt: data.nextDueAt,
3343
+ timelineCount: data.timeline.length,
3344
+ timelineTotal: data.timelineTotal,
3345
+ timelineTruncated: data.timelineTruncated,
3346
+ disclaimer: true,
3347
+ }
3348
+ const human = [
3349
+ '已生成客户状态包(' + format + '):' + out,
3350
+ '客户:' + data.displayName + ' (' + data.client.id + ') · 事项 ' + data.counts.matters + ' · 未完成 我方 ' + data.counts.openMine + ' / 等待对方 ' + data.counts.openWaiting,
3351
+ 'clearance=0 · 受保护事项仅计数:' + data.protectedExcluded + ' · sha256=' + sha256,
3352
+ '边界:状态说明,不是对账单/合同/法律意见;不含对话原文与备注正文。',
3353
+ ]
3354
+ customerPrint(parsed.flags.json === true, payload, human)
3355
+ } catch (error) { reportCustomerFailure(error) }
3356
+ }
3357
+ async function clientCommand(rawArgs) {
3046
3358
  const sub = rawArgs[0]
3047
3359
  const rest = rawArgs.slice(1)
3048
3360
  if (!sub || sub === 'help' || sub === '--help') { clientUsage(); return }
@@ -3050,6 +3362,7 @@ function clientCommand(rawArgs) {
3050
3362
  if (sub === 'list' || sub === 'ls') return clientList(rest)
3051
3363
  if (sub === 'show') return clientShow(rest)
3052
3364
  if (sub === 'timeline') return clientTimeline(rest)
3365
+ if (sub === 'export') return clientExport(rest)
3053
3366
  if (sub === 'archive') return clientArchive(rest)
3054
3367
  if (sub === 'merge') return clientMerge(rest)
3055
3368
  if (sub === 'note') return clientNote(rest)
@@ -3491,15 +3804,24 @@ async function buildAgendaData(input) {
3491
3804
  conflicts.sort((a, b) => (a.date === b.date ? (a.items.join(',') < b.items.join(',') ? -1 : 1) : (a.date < b.date ? -1 : 1)))
3492
3805
  const perDayLoad = {}
3493
3806
  for (const day of daysOut) if (day.load) perDayLoad[day.date] = day.load
3807
+ // 0.4.0 proactive (task-29): urgency is a derived, additive field attached
3808
+ // after the deterministic projection. It is never part of the morning hash
3809
+ // (buildMorningReport strips it before hashing) and calendar items are left
3810
+ // untouched. Secrecy is not an input (see lib/urgency.js).
3811
+ const { scoreUrgency } = await loadUrgency()
3812
+ const urgencyRecords = new Map()
3813
+ for (const commitment of input.ledger.listCommitments()) urgencyRecords.set(commitment.id, commitment)
3814
+ const urgencyOptions = { now: nowMs, timezone: AGENDA_TIMEZONE, records: urgencyRecords }
3815
+ const withUrgency = (items) => items.map((item) => (item.kind === 'commitment' ? { ...item, urgency: scoreUrgency(item, urgencyOptions) } : item))
3494
3816
  return {
3495
3817
  ok: true,
3496
3818
  command: 'agenda',
3497
3819
  now: new Date(nowMs).toISOString(),
3498
3820
  window: { from: startDay, to: lastDay, days: days, timezone: AGENDA_TIMEZONE },
3499
- overdue: overdue.slice(0, 50),
3500
- days: daysOut,
3501
- waiting: waiting.slice(0, 20),
3502
- unscheduled: unscheduled.slice(0, 20),
3821
+ overdue: withUrgency(overdue.slice(0, 50)),
3822
+ days: daysOut.map((day) => ({ ...day, items: withUrgency(day.items) })),
3823
+ waiting: withUrgency(waiting.slice(0, 20)),
3824
+ unscheduled: withUrgency(unscheduled.slice(0, 20)),
3503
3825
  conflicts: conflicts,
3504
3826
  counts: { overdue: overdue.length, today: daysOut[0] ? daysOut[0].load : 0, days: days, waiting: waiting.length, unscheduled: unscheduled.length, conflicts: conflicts.length, perDayLoad: perDayLoad },
3505
3827
  degraded: degraded,
@@ -3634,9 +3956,44 @@ async function buildMorningReport(input) {
3634
3956
  if (agenda.conflicts.length) risks.push('时间冲突 ' + agenda.conflicts.length + ' 处')
3635
3957
  if (today.load >= 3) risks.push('今日负载较高(' + today.load + ' 项)')
3636
3958
  if (agenda.unscheduled.length) risks.push('未排期 ' + agenda.unscheduled.length + ' 条')
3959
+ // 0.4.0 proactive: urgency now rides on the agenda commitment items, but the
3960
+ // frozen dataSha256 must cover exactly the 0.3.2 shape. Strip the derived field
3961
+ // before hashing (the same data still ships in payloadInput below).
3962
+ const stripUrgency = (value) => {
3963
+ if (Array.isArray(value)) return value.map(stripUrgency)
3964
+ if (value && typeof value === 'object') {
3965
+ const out = {}
3966
+ for (const [key, entry] of Object.entries(value)) if (key !== 'urgency') out[key] = stripUrgency(entry)
3967
+ return out
3968
+ }
3969
+ return value
3970
+ }
3971
+ const counts = {
3972
+ mustDo: mustDo.length,
3973
+ overdue: agenda.overdue.length,
3974
+ meetings: meetings.length,
3975
+ waiting: agenda.waiting.length,
3976
+ upcoming: upcoming.length,
3977
+ unscheduled: agenda.unscheduled.length,
3978
+ conflicts: agenda.conflicts.length,
3979
+ }
3637
3980
  const hashInput = {
3638
3981
  localDay: agenda.window.from,
3639
3982
  window: agenda.window,
3983
+ mustDo: stripUrgency(mustDo),
3984
+ overdue: stripUrgency(agenda.overdue),
3985
+ meetings: meetings,
3986
+ waiting: stripUrgency(agenda.waiting),
3987
+ upcoming: upcoming,
3988
+ unscheduled: stripUrgency(agenda.unscheduled),
3989
+ conflicts: agenda.conflicts,
3990
+ counts: counts,
3991
+ }
3992
+ const evidence = await loadEvidence()
3993
+ const dataSha256 = evidence.sha256Hex(evidence.stableStringify(hashInput, { space: 0 }))
3994
+ const payloadInput = {
3995
+ localDay: hashInput.localDay,
3996
+ window: agenda.window,
3640
3997
  mustDo: mustDo,
3641
3998
  overdue: agenda.overdue,
3642
3999
  meetings: meetings,
@@ -3644,19 +4001,26 @@ async function buildMorningReport(input) {
3644
4001
  upcoming: upcoming,
3645
4002
  unscheduled: agenda.unscheduled,
3646
4003
  conflicts: agenda.conflicts,
3647
- counts: {
3648
- mustDo: mustDo.length,
3649
- overdue: agenda.overdue.length,
3650
- meetings: meetings.length,
3651
- waiting: agenda.waiting.length,
3652
- upcoming: upcoming.length,
3653
- unscheduled: agenda.unscheduled.length,
3654
- conflicts: agenda.conflicts.length,
3655
- },
3656
- }
3657
- const evidence = await loadEvidence()
3658
- const dataSha256 = evidence.sha256Hex(evidence.stableStringify(hashInput, { space: 0 }))
3659
- return { agenda: agenda, today: today, risks: risks, hashInput: hashInput, dataSha256: dataSha256 }
4004
+ counts: counts,
4005
+ }
4006
+ // Deterministic human priority list (score desc -> dueAt asc -> id asc); it is
4007
+ // presentation only and never enters dataSha256.
4008
+ const { selectTopUrgent } = await loadUrgency()
4009
+ const topLimit = Number.isInteger(input.top) && input.top >= 1 && input.top <= 5 ? input.top : 3
4010
+ const topCandidates = [
4011
+ ...mustDo.map((item) => ({ ...item, source: 'today' })),
4012
+ ...agenda.overdue.map((item) => ({ ...item, source: 'overdue' })),
4013
+ ]
4014
+ const top = selectTopUrgent(topCandidates, { limit: topLimit }).map((item) => ({
4015
+ id: item.id,
4016
+ kind: item.kind,
4017
+ title: item.title,
4018
+ ...(item.localTime ? { localTime: item.localTime } : {}),
4019
+ urgency: item.urgency,
4020
+ whyNow: item.urgency?.whyNow ?? '',
4021
+ source: item.source,
4022
+ }))
4023
+ return { agenda: agenda, today: today, risks: risks, hashInput: hashInput, payloadInput: payloadInput, dataSha256: dataSha256, top: top, topLimit: topLimit }
3660
4024
  }
3661
4025
 
3662
4026
  function morningMarkdown(report) {
@@ -3666,6 +4030,17 @@ function morningMarkdown(report) {
3666
4030
  lines.push('# 晨报 ' + day + '(' + agendaWeekday(day) + ')')
3667
4031
  lines.push('> 本地确定性生成 · 不含模型推理 · 数据哈希 sha256:' + report.dataSha256.slice(0, 16))
3668
4032
  lines.push('')
4033
+ // 0.4.0 additive section: top-urgency view (<=3/--top). The full "今天必须做"
4034
+ // list below keeps its 0.3.2 meaning, so existing readers do not break.
4035
+ const urgencyLevelLabels = { low: '低', medium: '中', high: '高', critical: '急' }
4036
+ lines.push('## 今天优先(最多 ' + report.topLimit + ')')
4037
+ if (!report.top.length) lines.push('(无)')
4038
+ for (let index = 0; index < report.top.length; index++) {
4039
+ const item = report.top[index]
4040
+ const level = urgencyLevelLabels[item.urgency?.level] ?? String(item.urgency?.level ?? '低')
4041
+ lines.push((index + 1) + '. ' + item.title + (item.localTime ? '(今天 ' + item.localTime + ' 到期)' : '') + ',urgency ' + (item.urgency?.score ?? 0) + '/' + level + (item.whyNow ? ':' + item.whyNow : ''))
4042
+ }
4043
+ lines.push('')
3669
4044
  lines.push('## 今天必须做')
3670
4045
  if (!report.hashInput.mustDo.length) lines.push('(无)')
3671
4046
  for (let index = 0; index < report.hashInput.mustDo.length; index++) {
@@ -3711,19 +4086,34 @@ async function morningReportCommand(args) {
3711
4086
  const parsed = parseFlags(args)
3712
4087
  const flags = parsed.flags
3713
4088
  if (flags.help === true) {
3714
- console.log('usage: advisers morning [digest morning] [--days 1..31] [--matter id] [--out file] [--json] [--now ISO]')
4089
+ console.log('usage: advisers morning [digest morning] [--days 1..31] [--matter id] [--top 1..5] [--out file] [--archive [--keep 1..365]] [--json] [--now ISO]')
3715
4090
  return
3716
4091
  }
3717
4092
  const window = parseAgendaWindowFlags(flags, 'morning')
3718
4093
  if (!window) return
4094
+ // 0.4.0 flags: --top (human priority count) and --keep (archive retention).
4095
+ let top
4096
+ if (flags.top !== undefined) {
4097
+ if (flags.top === true || !/^\d+$/.test(String(flags.top)) || Number(flags.top) < 1 || Number(flags.top) > 5) { agendaUsageFail('--top must be an integer 1..5'); return }
4098
+ top = Number(flags.top)
4099
+ }
4100
+ let keep
4101
+ if (flags.keep !== undefined) {
4102
+ if (flags.keep === true || !/^\d+$/.test(String(flags.keep)) || Number(flags.keep) < 1 || Number(flags.keep) > 365) { agendaUsageFail('--keep must be an integer 1..365'); return }
4103
+ keep = Number(flags.keep)
4104
+ }
3719
4105
  try {
3720
4106
  const inputs = loadAgendaInputs()
3721
4107
  if (window.matterId) {
3722
4108
  try { resolveMatterForCommand(inputs.ledger, window.matterId, 'morning') } catch (error) { agendaMatterErrorLine(error); return }
3723
4109
  }
3724
- const report = await buildMorningReport({ ledger: inputs.ledger, events: inputs.events, nowMs: window.nowMs, days: window.days, fromDay: window.fromDay, matterId: window.matterId })
4110
+ const report = await buildMorningReport({ ledger: inputs.ledger, events: inputs.events, nowMs: window.nowMs, days: window.days, fromDay: window.fromDay, matterId: window.matterId, top: top })
3725
4111
  const markdown = morningMarkdown(report)
3726
- const payload = Object.assign({ ok: true, command: 'morning', generatedAt: new Date(window.nowMs).toISOString() }, report.hashInput, { dataSha256: report.dataSha256, degraded: report.agenda.degraded })
4112
+ const payload = Object.assign(
4113
+ { ok: true, command: 'morning', generatedAt: new Date(window.nowMs).toISOString() },
4114
+ report.payloadInput,
4115
+ { dataSha256: report.dataSha256, degraded: report.agenda.degraded, top: report.top, urgencyModelVersion: 1 },
4116
+ )
3727
4117
  let outPath
3728
4118
  if (flags.out !== undefined) {
3729
4119
  if (typeof flags.out !== 'string') { agendaUsageFail('--out requires a file path'); return }
@@ -3732,9 +4122,45 @@ async function morningReportCommand(args) {
3732
4122
  atomicWriteFileSync(outPath, markdown, { mode: 0o600 })
3733
4123
  payload.out = outPath
3734
4124
  }
4125
+ // 0.4.0 proactive: --archive is the only write path here. It takes the
4126
+ // writer lock (audit row brief.archive inside the same transaction), writes
4127
+ // briefs/<localDay>.md + latest.md atomically, and prunes old day files.
4128
+ let archiveInfo
4129
+ if (flags.archive === true) {
4130
+ const archive = await loadBriefArchive()
4131
+ const localDay = report.hashInput.localDay
4132
+ const writeBrief = () => archive.archiveBrief({ home: HOME, env: process.env, localDay, markdown, keep })
4133
+ try {
4134
+ if (dbStore()) {
4135
+ mutateWithAudit(() => { archiveInfo = writeBrief(); return null }, archive.briefAuditRow({ localDay }))
4136
+ } else {
4137
+ archiveInfo = writeBrief()
4138
+ }
4139
+ } catch (error) { reportCommandFailure(error); return }
4140
+ try {
4141
+ const scheduler = await loadScheduler()
4142
+ scheduler.recordSchedulerRunV2({ homeDir: HOME, at: new Date(window.nowMs), section: 'morning', result: 'ok', count: report.top.length, path: archiveInfo.path, dryRun: false })
4143
+ } catch (error) {
4144
+ console.error(sanitizeConsoleText('scheduler status not recorded: ' + (error?.message ?? error), { max: 2000 }))
4145
+ }
4146
+ payload.archive = {
4147
+ path: archiveInfo.path,
4148
+ latestPath: archiveInfo.latestPath,
4149
+ keep: archiveInfo.keep,
4150
+ bytes: archiveInfo.bytes,
4151
+ removed: archiveInfo.removed,
4152
+ failed: archiveInfo.failed,
4153
+ }
4154
+ }
3735
4155
  if (flags.json === true) { console.log(JSON.stringify(payload, null, 2)); return }
3736
4156
  process.stdout.write(markdown)
3737
4157
  if (outPath) console.log('wrote ' + outPath + ' (mode 600)')
4158
+ if (archiveInfo) {
4159
+ console.log('已归档:' + sanitizeConsoleText(archiveInfo.path, { max: 240 }) + '(' + formatBytes(archiveInfo.bytes) + ',keep=' + archiveInfo.keep + ')')
4160
+ console.log('最新:' + sanitizeConsoleText(archiveInfo.latestPath, { max: 240 }))
4161
+ for (const removed of archiveInfo.removed) console.log('已删除:' + sanitizeConsoleText(removed, { max: 240 }))
4162
+ for (const failed of archiveInfo.failed) console.error(sanitizeConsoleText('归档清理失败:' + failed.path + ' (' + failed.code + ')', { max: 2000 }))
4163
+ }
3738
4164
  } catch (error) { reportCommandFailure(error) }
3739
4165
  }
3740
4166
 
@@ -3802,7 +4228,7 @@ async function printSources(ledger) {
3802
4228
  for (const r of rows.slice(0, 20)) console.log(` ${r.commitmentId} ${r.action} ← ${r.label} (${r.ref ?? '-'}) 「${r.quote.slice(0, 80)}」`)
3803
4229
  }
3804
4230
 
3805
- async function today(openRows, { calendar = false, sources = false, json = false, ledger = null } = {}) {
4231
+ async function today(openRows, { calendar = false, sources = false, json = false, ledger = null, limit = null, hydrate = null } = {}) {
3806
4232
  const nowMs = Date.now()
3807
4233
  const localDay = localDayOf(nowMs)
3808
4234
  const weekAhead = nowMs + 7 * 86400_000
@@ -3850,17 +4276,32 @@ async function today(openRows, { calendar = false, sources = false, json = false
3850
4276
  }
3851
4277
  if (json) {
3852
4278
  // JSON contract v1 (docs/CLI-JSON.md): same classification as the human view.
4279
+ // 0.3.2 additive `--limit N`: each bucket keeps at most N full Commitment
4280
+ // entities (hydrated on demand); `counts`/`next` stay the true totals. The
4281
+ // flagless output is byte-identical to v1.
4282
+ const capped = (list) => (limit === null ? list : list.slice(0, limit))
4283
+ const materialize = (list) => {
4284
+ const kept = capped(list)
4285
+ if (limit === null || typeof hydrate !== 'function' || !kept.length) return kept
4286
+ const hydrated = hydrate(kept.map((row) => row.id))
4287
+ const byId = new Map((Array.isArray(hydrated) ? hydrated : []).map((row) => [row.id, row]))
4288
+ return kept.map((row) => byId.get(row.id) ?? row)
4289
+ }
3853
4290
  const payload = {
3854
4291
  now: new Date(nowMs).toISOString(),
3855
4292
  localDay,
3856
4293
  counts: { today: todayDue.length, overdue: overdue.length, week: week.length, waiting: waiting.length, noDue: noDue.length },
3857
- overdue,
3858
- today: todayDue,
3859
- week,
3860
- waiting,
3861
- noDue,
4294
+ overdue: materialize(overdue),
4295
+ today: materialize(todayDue),
4296
+ week: materialize(week),
4297
+ waiting: materialize(waiting),
4298
+ noDue: materialize(noDue),
3862
4299
  next: next ? { id: next.id, action: next.action, dueAt: next.dueAt } : null,
3863
4300
  }
4301
+ if (limit !== null) {
4302
+ payload.limit = limit
4303
+ payload.truncated = [overdue, todayDue, week, waiting, noDue].some((list) => list.length > limit)
4304
+ }
3864
4305
  if (calendar) {
3865
4306
  const calendarToday = await calendarOccurrencesToday()
3866
4307
  payload.calendar = calendarToday.occurrences
@@ -3979,8 +4420,9 @@ function tick(ledger, asJson = false) {
3979
4420
  * pointed at by `verifyFtsIntegrity()` / reader warnings ("advisers audit
3980
4421
  * --rebuild-fts"). Runs in the single-writer lock inside one immediate
3981
4422
  * 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).
4423
+ * rebuilt index and records an audit row. `rebuildAllFtsIndexes()` (0.4.0)
4424
+ * rebuilds the v19 turn pair AND the v22 KB pair with the same probed tokenizer,
4425
+ * so a KB FTS drift is repairable here instead of only detectable.
3984
4426
  */
3985
4427
  async function rebuildFtsIndexes({ asJson = false } = {}) {
3986
4428
  let store
@@ -3995,7 +4437,7 @@ async function rebuildFtsIndexes({ asJson = false } = {}) {
3995
4437
  try {
3996
4438
  store.db.exec('BEGIN IMMEDIATE')
3997
4439
  try {
3998
- store._setupFts()
4440
+ store.rebuildAllFtsIndexes()
3999
4441
  store.db.exec('COMMIT')
4000
4442
  } catch (error) {
4001
4443
  try { store.db.exec('ROLLBACK') } catch {}
@@ -4203,6 +4645,17 @@ async function printPrivacy(args = []) {
4203
4645
  ensureHome()
4204
4646
  const asJson = args.includes('--json')
4205
4647
  const prove = args.includes('--prove')
4648
+ // 0.4.0: surface x action x gate matrix generated from the policy registry
4649
+ // (read-only; no ledger rows). Replaces the hand-maintained coverage narrative.
4650
+ if (args.includes('--matrix')) {
4651
+ const policy = await loadPolicy()
4652
+ const matrix = policy.surfaceMatrix()
4653
+ const payload = { ok: true, command: 'privacy --matrix', policyVersion: matrix.policyVersion, rulesetVersion: matrix.rulesetVersion, generatedAt: new Date().toISOString(), rows: matrix.rows }
4654
+ if (asJson) { console.log(JSON.stringify(payload, null, 2)); return }
4655
+ console.log('policy matrix · policy v' + payload.policyVersion + ' · ruleset ' + payload.rulesetVersion + ' · generatedAt ' + payload.generatedAt)
4656
+ for (const row of payload.rows) console.log(row.surface + '\t' + row.actions.join(',') + '\t' + row.dataClass + '\t' + row.gate + '\tdefault=' + row.default)
4657
+ return
4658
+ }
4206
4659
  const store = readStoreOrExit()
4207
4660
  let audit = null
4208
4661
  try { const v = store?.verifyAudit(); if (v) audit = { ok: v.ok, count: v.count ?? 0 } } catch {}
@@ -4243,6 +4696,8 @@ async function printPrivacy(args = []) {
4243
4696
  'model provider — chat / brief --deep / review / learn review (only when ADVISERS_API_KEY is set; ADVISERS_BASE_URL)',
4244
4697
  'research --web|--url — provider web search/read tool (explicit opt-in; no silent research egress)',
4245
4698
  'capture --from-imap — read-only IMAP fetch from the server you configure (TLS by default)',
4699
+ 'mail sync — IMAP server you configure (TLS/STARTTLS, read-only EXAMINE/FETCH)',
4700
+ 'mail extract --model — mail body excerpts sent to the model provider only after explicit opt-in + separate consent (ADVISERS_API_KEY)',
4246
4701
  'remind --deliver --notify — optional outbound webhook or local notifier you configure',
4247
4702
  'sync push|pull — the directory you provide; snapshots are AES-256-GCM encrypted before writing',
4248
4703
  'bridge — Hermes file gateway: inbox/outbox JSON files are handed to the Hermes process',
@@ -4299,7 +4754,7 @@ async function printPrivacy(args = []) {
4299
4754
  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
4755
  }
4301
4756
  }
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.')
4757
+ console.log('egress gate coverage: chat/model, review, research, brief --deep, learn review, bridge, capture, mail sync and mail extract --model are wired to the local secrecy gate (mail extract --model also requires a separate consent record); the other surfaces listed above are self-attested.')
4303
4758
  if (failed) process.exitCode = 1
4304
4759
  }
4305
4760
  }
@@ -5025,7 +5480,7 @@ async function doctorRepair(flags) {
5025
5480
  if (!before.ok) {
5026
5481
  store.db.exec('BEGIN IMMEDIATE')
5027
5482
  try {
5028
- store._setupFts()
5483
+ store.rebuildAllFtsIndexes()
5029
5484
  store.db.exec('COMMIT')
5030
5485
  } catch (error) {
5031
5486
  try { store.db.exec('ROLLBACK') } catch {}
@@ -5143,6 +5598,9 @@ function printStatus(asJson = false) {
5143
5598
  // queries on the same read snapshot (no row materialisation).
5144
5599
  clients: Number(store.db.prepare("SELECT COUNT(*) AS n FROM clients WHERE status = 'active' AND deleted_at IS NULL").get()?.n ?? 0),
5145
5600
  projects: Number(store.db.prepare("SELECT COUNT(*) AS n FROM projects WHERE status = 'active' AND deleted_at IS NULL").get()?.n ?? 0),
5601
+ // 0.4.0 additive status counts: money rows (never amounts).
5602
+ receivables: Number(store.db.prepare('SELECT COUNT(*) AS n FROM receivables WHERE deleted_at IS NULL').get()?.n ?? 0),
5603
+ payments: Number(store.db.prepare('SELECT COUNT(*) AS n FROM payments WHERE deleted_at IS NULL').get()?.n ?? 0),
5146
5604
  usage: store.sumModelUsage(),
5147
5605
  }))
5148
5606
  data.matters = counts.matters
@@ -5153,6 +5611,8 @@ function printStatus(asJson = false) {
5153
5611
  data.deliveries = counts.deliveries
5154
5612
  data.clients = counts.clients
5155
5613
  data.projects = counts.projects
5614
+ data.receivables = counts.receivables
5615
+ data.payments = counts.payments
5156
5616
  const usage = counts.usage
5157
5617
  if (usage.calls) data.modelUsage = usage
5158
5618
  }
@@ -5367,7 +5827,7 @@ async function runTurn(options) {
5367
5827
  }
5368
5828
  }
5369
5829
 
5370
- async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [], allowPaths = [], renderWidth = null }) {
5830
+ async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [], allowPaths = [], renderWidth = null, signal = null }) {
5371
5831
  // 0.3.0 Wave 3 (plan 26 §4.1): internal process lines ([tool]/[attach]/[compact])
5372
5832
  // are hidden by default; ADVISERS_PROGRESS=1 (or /debug) is the explicit
5373
5833
  // opt-in. Results, confirmations and failures are never gated.
@@ -5491,6 +5951,10 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
5491
5951
  effort: process.env.ADVISERS_THINKING_EFFORT,
5492
5952
  onTool: (name) => { if (showProgress) console.log('[tool] ' + sanitizeConsoleText(name, { max: 120 })) },
5493
5953
  onToolAction: auditToolAction,
5954
+ // 0.4.0: the interactive shell passes an AbortSignal so Ctrl+C/Esc can
5955
+ // interrupt one turn; one-shot chat passes null and keeps the exact old
5956
+ // options object shape (no behavioural change).
5957
+ ...(signal ? { signal } : {}),
5494
5958
  })
5495
5959
  // 0.2.3 Wave 1: consume the structured warnings (they used to be discarded)
5496
5960
  // and treat a blocked turn as a failure, never as a successful reply.
@@ -5926,49 +6390,1463 @@ async function repl({ allowPaths = [] } = {}) {
5926
6390
  saveLedger(ledger)
5927
6391
  }
5928
6392
 
5929
- function ls() {
5930
- const matters = loadReadLedger({ matters: {} }).listMatters()
5931
- if (!matters.length) {
5932
- console.log('no matters yet')
5933
- return
6393
+ /* ---------------------------------------------------------------------------
6394
+ * 0.4.0 Wave 1 (task-29): interactive shell entry.
6395
+ *
6396
+ * The state machine / rendering / paste guard live in lib/shell.js. This file
6397
+ * keeps the process-level concerns (the TOS gate already ran, the ledger and
6398
+ * model runtime, the writer lock) and injects read-only JSON views plus one
6399
+ * turn executor. The legacy REPL (repl) stays as the explicit fallback
6400
+ * (ADVISERS_NO_SHELL=1); a non-TTY stdin keeps the 0.3.x "print help, exit 0"
6401
+ * path byte for byte, and `advisers tui --once/--json` is untouched.
6402
+ * ------------------------------------------------------------------------- */
6403
+
6404
+ /** Today counts for the shell status line (same definition as repl()). */
6405
+ function shellTodayCounts(ledger, nowMs = Date.now()) {
6406
+ const today = localDayOf(nowMs)
6407
+ let due = 0
6408
+ let overdue = 0
6409
+ try {
6410
+ for (const commitment of ledger.openCommitments()) {
6411
+ if (!commitment.dueAt) continue
6412
+ const ms = Date.parse(commitment.dueAt)
6413
+ if (Number.isNaN(ms)) continue
6414
+ if (ms < nowMs && localDayOf(ms) !== today) overdue += 1
6415
+ else if (localDayOf(ms) === today) due += 1
6416
+ }
6417
+ } catch {}
6418
+ return { due, overdue }
6419
+ }
6420
+
6421
+ function shellModelState() {
6422
+ const local = !process.env.ADVISERS_API_KEY || process.env.ADVISERS_NO_MODEL === '1'
6423
+ return { local, model: local ? null : (process.env.ADVISERS_MODEL || 'deepseek-flash') }
6424
+ }
6425
+
6426
+ /**
6427
+ * Run legacy printing code and collect its stdout as result-block lines.
6428
+ * Keeps the old /commands alive inside the shell without a second command
6429
+ * surface: the functions print like before, the shell renders the captured
6430
+ * lines through the sanitising kernel.
6431
+ */
6432
+ async function captureConsole(fn) {
6433
+ const lines = []
6434
+ const original = console.log
6435
+ console.log = (...values) => { lines.push(values.map((value) => (typeof value === 'string' ? value : String(value))).join(' ')) }
6436
+ try { await fn() } finally { console.log = original }
6437
+ return lines
6438
+ }
6439
+
6440
+ /** Read-only evidence view shared by /evidence (no exit-code side effects). */
6441
+ async function shellEvidenceBlock(id) {
6442
+ const store = mode === 'sqlite' ? readStore() : null
6443
+ const ledger = readLedgerForCommand(id.startsWith('fact_') ? { facts: {} } : id.startsWith('pref_') ? { preferences: {} } : { commitments: {} })
6444
+ const { evidenceForCommitment, evidenceForFact, evidenceForPreference } = await loadEvidence()
6445
+ const lookups = await buildEvidenceLookups(store)
6446
+ let result
6447
+ if (id.startsWith('cm_')) result = await evidenceForCommitment(store, ledger, id, undefined, { lookup: lookups })
6448
+ else if (id.startsWith('fact_')) result = await evidenceForFact(store, ledger, id, undefined, { lookup: lookups })
6449
+ else if (id.startsWith('pref_')) result = await evidenceForPreference(store, ledger, id, undefined, { lookup: lookups })
6450
+ else throw Object.assign(new Error('unknown evidence id prefix (want cm_/fact_/pref_)'), { code: 'E_USAGE' })
6451
+ if (!result || (!result.commitment && !result.fact && !result.preference)) throw new Error('not found: ' + id)
6452
+ await normalizeEvidenceSources(result)
6453
+ const unverifiable = Array.isArray(result.unverifiable) ? result.unverifiable : []
6454
+ const label = result.commitment ? result.commitment.action : result.fact ? result.fact.subject + ' ' + result.fact.predicate : result.preference?.statement
6455
+ const lines = []
6456
+ if (!result.sources.length && !unverifiable.length) lines.push({ role: 'fact', text: '(没有可回溯来源)' })
6457
+ for (const source of result.sources) lines.push({ role: 'fact', text: source.sessionId + '#' + source.turnId + ' 「' + String(source.quote ?? '').slice(0, 120) + '」' })
6458
+ for (const missing of result.missing) lines.push({ role: 'fact', text: 'MISSING ' + missing.reason + (missing.ref ? ' ' + missing.ref : '') })
6459
+ for (const item of unverifiable) lines.push({ role: 'fact', text: 'MANUAL 操作者录入(未外部核验) 「' + String(item.quote ?? '').slice(0, 120) + '」' })
6460
+ return { headline: String(id) + ' ' + String(label ?? ''), lines, next: 'advisers evidence show ' + id + ' --json' }
6461
+ }
6462
+
6463
+ /** Read-only client view for /client [id|list]. */
6464
+ function shellClientBlock(args, arg) {
6465
+ const store = readStore()
6466
+ if (!store) throw new Error('customer views need the SQLite store (ADVISERS_STORE=sqlite)')
6467
+ const words = Array.isArray(args) ? args : []
6468
+ const sub = words[0]
6469
+ if (!sub || sub === 'list' || sub === 'ls') {
6470
+ const rows = store.listClients({ status: 'active', limit: 50 })
6471
+ return {
6472
+ headline: '客户(' + rows.length + ')',
6473
+ lines: rows.length ? rows.map((client) => ({ role: 'item', text: client.id + ' ' + client.name })) : [{ role: 'fact', text: '(还没有客户)' }],
6474
+ next: 'advisers client show <id>',
6475
+ }
6476
+ }
6477
+ const id = sub === 'show' ? words[1] : sub
6478
+ if (!id) throw new Error('usage: /client [list|<id>]')
6479
+ const view = readClientView(store, id)
6480
+ const openRows = Array.isArray(view.open) ? view.open : []
6481
+ const lines = [
6482
+ { role: 'fact', text: '状态 ' + String(view.client.status ?? 'active') + ' · secrecy ' + String(view.client.secrecyDefault ?? 0) },
6483
+ { role: 'item', text: '项目 ' + view.projects.length + ' · 事项 ' + view.matters.length + ' · 未完成 ' + openRows.length + ' · 备注 ' + view.notes.length },
6484
+ ]
6485
+ for (const item of openRows.slice(0, 5)) lines.push({ role: 'item', text: item.id + ' ' + String(item.action ?? item.title ?? '') })
6486
+ return { headline: view.client.name + ' [' + view.client.id + ']', lines, next: 'advisers client show ' + view.client.id + ' --json' }
6487
+ }
6488
+
6489
+ /** Open commitments grouped for /today and /who (no store reads). */
6490
+ function shellOpenRows(ledger) {
6491
+ const rows = []
6492
+ try {
6493
+ for (const commitment of ledger.openCommitments()) rows.push(commitment)
6494
+ } catch {}
6495
+ return rows
6496
+ }
6497
+
6498
+ /** Build the runShell() handler table for one interactive session. */
6499
+ async function runShellEntry({ allowPaths = [] } = {}) {
6500
+ const shell = await loadShell()
6501
+ ensureHome()
6502
+ const ledger = loadLedger()
6503
+ const runtime = runtimeFor(ledger)
6504
+ const state = {
6505
+ ledger,
6506
+ runtime,
6507
+ conversationId: latestConversationId(),
6508
+ debug: process.env.ADVISERS_DEBUG === '1',
6509
+ allowPaths: [...allowPaths],
6510
+ }
6511
+ const handlers = {
6512
+ status: () => {
6513
+ const model = shellModelState()
6514
+ return { kind: 'idle', today: shellTodayCounts(state.ledger), local: model.local, model: model.model, hint: '/help' }
6515
+ },
6516
+ turn: async (payload) => {
6517
+ let question
6518
+ try {
6519
+ question = await runTurn({
6520
+ runtime: state.runtime,
6521
+ ledger: state.ledger,
6522
+ text: payload.text,
6523
+ conversationId: state.conversationId,
6524
+ debug: state.debug,
6525
+ confirm: payload.confirm,
6526
+ attachments: Array.isArray(payload.attachments) ? payload.attachments : [],
6527
+ allowPaths: [...state.allowPaths, ...(Array.isArray(payload.allowPaths) ? payload.allowPaths : [])],
6528
+ renderWidth: null,
6529
+ signal: payload.signal ?? null,
6530
+ })
6531
+ } finally {
6532
+ try { saveLedger(state.ledger) } catch {}
6533
+ }
6534
+ if (lastTurnSafetyBlock) {
6535
+ return { kind: 'error', error: { title: '本轮被内容安全拦截', reason: '没有执行;未创建承诺或文件。', next: '/retry 或 /help', code: lastTurnSafetyBlock.code ?? undefined } }
6536
+ }
6537
+ if (question) return { question: String(question) }
6538
+ return undefined
6539
+ },
6540
+ history: async () => {
6541
+ const rows = dbStore()?.listSessions(50) ?? []
6542
+ return { sessions: rows.map((row, index) => ({ n: index + 1, id: row.conversationId, title: row.title, updatedAt: row.updatedAt })) }
6543
+ },
6544
+ resume: async ({ arg }) => {
6545
+ const rows = dbStore()?.listSessions(50) ?? []
6546
+ const pick = /^\d+$/.test(String(arg)) ? rows[Number(arg) - 1] : rows.find((row) => row.conversationId === arg)
6547
+ if (!pick) throw new Error('unknown session: ' + arg)
6548
+ state.conversationId = pick.conversationId
6549
+ return { kind: 'notice', headline: '已恢复会话', summary: String(pick.title ?? '') + ' [' + pick.conversationId + ']', next: '直接输入下一步' }
6550
+ },
6551
+ newSession: async () => {
6552
+ state.conversationId = 'local_' + Date.now()
6553
+ return { kind: 'notice', headline: '新会话', summary: '下一条消息写在新会话里' }
6554
+ },
6555
+ today: async () => {
6556
+ const nowMs = Date.now()
6557
+ const today = localDayOf(nowMs)
6558
+ const due = []
6559
+ const overdue = []
6560
+ for (const commitment of shellOpenRows(state.ledger)) {
6561
+ if (!commitment.dueAt) continue
6562
+ const ms = Date.parse(commitment.dueAt)
6563
+ if (Number.isNaN(ms)) continue
6564
+ if (ms < nowMs && localDayOf(ms) !== today) overdue.push(commitment)
6565
+ else if (localDayOf(ms) === today) due.push(commitment)
6566
+ }
6567
+ const lines = []
6568
+ for (const commitment of due.slice(0, 8)) lines.push({ role: 'item', text: '今天 · ' + commitment.id + ' ' + String(commitment.action) })
6569
+ for (const commitment of overdue.slice(0, 8)) lines.push({ role: 'item', text: '逾期 · ' + commitment.id + ' ' + String(commitment.action) + '(' + String(commitment.dueAt).slice(0, 10) + ')' })
6570
+ if (!lines.length) lines.push({ role: 'fact', text: '今天没有到期的承诺。' })
6571
+ return { headline: '今天 · 今天到期 ' + due.length + ' · 逾期 ' + overdue.length, lines, next: 'advisers today --json' }
6572
+ },
6573
+ remind: async () => {
6574
+ const { buildReminders } = await loadRemind()
6575
+ const snoozed = {}
6576
+ for (const [key, value] of readStore()?.listMetaByPrefix('snooze:') ?? []) snoozed[key.slice('snooze:'.length)] = value
6577
+ const reminders = buildReminders(state.ledger, { now: new Date(), snoozedUntil: snoozed })
6578
+ const lines = reminders.slice(0, 8).map((reminder) => ({ role: 'item', text: '[' + reminder.level + '/' + reminder.bucket + '] ' + String(reminder.action) + (reminder.dueAt ? ' · ' + String(reminder.dueAt).slice(0, 16) : '') }))
6579
+ return { headline: '提醒(' + reminders.length + ')', lines: lines.length ? lines : [{ role: 'fact', text: '现在没有到期的提醒。' }], next: 'advisers remind --json' }
6580
+ },
6581
+ who: async () => {
6582
+ const open = shellOpenRows(state.ledger)
6583
+ const mine = open.filter((commitment) => commitment.debtor === 'user' || commitment.debtor === 'agent')
6584
+ const waiting = open.filter((commitment) => commitment.debtor === 'third' || String(commitment.debtor).startsWith('third:'))
6585
+ const lines = []
6586
+ for (const commitment of mine) lines.push({ role: 'item', text: '我欠 ' + commitment.id + ' ' + commitment.creditor + ' · ' + String(commitment.action) })
6587
+ for (const commitment of waiting) lines.push({ role: 'item', text: '等人 ' + commitment.id + ' ' + String(commitment.action) })
6588
+ return { headline: '我欠别人 ' + mine.length + ' · 等别人 ' + waiting.length, lines: lines.length ? lines.slice(0, 12) : [{ role: 'fact', text: '(没有未完成的承诺)' }], next: 'advisers who' }
6589
+ },
6590
+ client: async ({ args, arg }) => shellClientBlock(args, arg),
6591
+ evidence: async ({ arg }) => {
6592
+ if (!arg) throw Object.assign(new Error('usage: /evidence <cm_|fact_|pref_ id>'), { code: 'E_USAGE' })
6593
+ return shellEvidenceBlock(String(arg).split(/\s+/)[0])
6594
+ },
6595
+ opening: async () => {
6596
+ const lines = await captureConsole(() => printOpening(state.conversationId))
6597
+ return lines.filter((line) => line.trim() !== '').slice(0, 2)
6598
+ },
6599
+ legacyCommand: async ({ name, args, arg }) => {
6600
+ const sub = Array.isArray(args) ? args[0] : undefined
6601
+ switch (name) {
6602
+ case '/deliveries': { const lines = await captureConsole(() => printDeliveries()); return { lines } }
6603
+ case '/tick': { const lines = await captureConsole(() => tick(state.ledger)); return { lines } }
6604
+ case '/week': { const lines = await captureConsole(() => printWeek(state.ledger)); return { lines } }
6605
+ case '/memory': { const lines = await captureConsole(() => printMemory(state.ledger)); return { lines } }
6606
+ case '/prefs': { const lines = await captureConsole(() => printPreferences()); return { lines } }
6607
+ case '/links': { const lines = await captureConsole(() => printLinks()); return { lines } }
6608
+ case '/audit': { const lines = await captureConsole(() => auditCommand([])); return { lines } }
6609
+ case '/agenda': {
6610
+ const lines = await captureConsole(async () => {
6611
+ const inputs = loadAgendaInputs()
6612
+ const data = await buildAgendaData({ ledger: inputs.ledger, events: inputs.events, nowMs: Date.now(), days: 7, includeCalendar: true, includeDone: false })
6613
+ printAgenda(data)
6614
+ })
6615
+ return { lines }
6616
+ }
6617
+ case '/search': {
6618
+ const query = String(arg ?? '').trim()
6619
+ if (!query) throw Object.assign(new Error('usage: /search <text>'), { code: 'E_USAGE' })
6620
+ const rows = dbStore()?.searchTurns(query, { limit: 10 }) ?? []
6621
+ return { headline: '搜索 · ' + query, lines: rows.length ? rows.map((row) => ({ role: 'item', text: row.seq + '\t' + row.role + '\t' + String(row.content).replace(/\s+/g, ' ').slice(0, 160) })) : [{ role: 'fact', text: '没有匹配' }] }
6622
+ }
6623
+ case '/digest': {
6624
+ const lines = await captureConsole(async () => {
6625
+ const store = dbStore()
6626
+ const { buildDigest } = await loadDigest()
6627
+ console.log(buildDigest({
6628
+ period: String(arg ?? '').endsWith('week') ? 'week' : 'day',
6629
+ turns: store?.listTurns(state.conversationId, 200) ?? [],
6630
+ commitments: state.ledger.listCommitments(),
6631
+ deliveries: store?.listDeliveries(100) ?? [],
6632
+ }))
6633
+ })
6634
+ return { lines }
6635
+ }
6636
+ case '/diff': { const lines = await captureConsole(async () => { const { diffLatest } = await loadUndo(); const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') }); console.log(result.ok ? result.diff : 'diff failed: ' + result.error) }); return { lines } }
6637
+ case '/undo': { const lines = await captureConsole(async () => { const { undoLatest } = await loadUndo(); const result = await undoLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo'), force: args.includes('--force') }); console.log(result.ok ? '已回滚:' + result.path : '撤销失败:' + result.error) }); return { lines } }
6638
+ case '/why': { const id = String(arg ?? '').trim(); if (!id) throw Object.assign(new Error('usage: /why <pref-id>'), { code: 'E_USAGE' }); const lines = await captureConsole(() => why(id)); return { lines } }
6639
+ case '/debug': {
6640
+ state.debug = !state.debug
6641
+ return { kind: 'notice', headline: state.debug ? '明细已开启' : '明细已关闭', summary: state.debug ? '会打印上下文与内部行。' : undefined }
6642
+ }
6643
+ case '/forget': {
6644
+ const id = String(arg ?? '').trim()
6645
+ if (!id) throw Object.assign(new Error('usage: /forget <pref-id>'), { code: 'E_USAGE' })
6646
+ const ok = state.ledger.forget('preference', id)
6647
+ saveLedger(state.ledger)
6648
+ return { kind: 'notice', headline: ok ? '已忘记:' + id : '没有这条偏好:' + id }
6649
+ }
6650
+ case '/correct': {
6651
+ const statement = String(arg ?? '').trim()
6652
+ if (!statement) throw Object.assign(new Error('usage: /correct <text>'), { code: 'E_USAGE' })
6653
+ const lines = await captureConsole(() => { const result = learnPreference(state.ledger, statement, statement); saveLedger(state.ledger); printLearnReceipt(result) })
6654
+ return { lines }
6655
+ }
6656
+ case '/decay': {
6657
+ const lines = await captureConsole(async () => { const { applyPreferenceDecay } = await loadLearning(); const changed = applyPreferenceDecay(state.ledger.listPreferences({ includeCandidates: true })); saveLedger(state.ledger); console.log('[decay] ' + changed.length + ' preference(s) updated') })
6658
+ return { lines }
6659
+ }
6660
+ case '/matter': {
6661
+ const useId = sub === 'use' && Array.isArray(args) ? args[1] : undefined
6662
+ if (!useId) throw Object.assign(new Error('usage: /matter use <matter-id>'), { code: 'E_USAGE' })
6663
+ const matter = state.ledger.getMatter(useId)
6664
+ if (!matter) throw new Error('unknown matter: ' + useId)
6665
+ if (matter.status !== 'active') throw new Error('matter 已归档:' + useId)
6666
+ state.ledger.setRoute('active-matter', useId)
6667
+ saveLedger(state.ledger)
6668
+ return { kind: 'notice', headline: 'active matter: ' + useId, summary: String(matter.title ?? '') }
6669
+ }
6670
+ case '/commit': {
6671
+ const { flags, positional } = parseFlags(Array.isArray(args) ? args : [])
6672
+ if (positional[0] === 'ls') { const lines = await captureConsole(() => printCommitments(state.ledger)); return { lines } }
6673
+ if (positional[0] === 'add') {
6674
+ const action = positional.slice(1).join(' ')
6675
+ if (!action || !flags.quote) throw Object.assign(new Error('用法:/commit add <action> --quote <原话> [--due ISO]'), { code: 'E_USAGE' })
6676
+ const c = state.ledger.addCommitment({ matterId: resolveMatterForCommand(state.ledger, flags.matter, 'commit add'), debtor: flags.debtor ?? 'user', creditor: flags.creditor ?? 'me', action, dueAt: flags.due, capability: 'todo', evidence: [manualEvidence(String(flags.quote), 'repl commit add')] })
6677
+ saveLedger(state.ledger)
6678
+ return { kind: 'notice', headline: c.id + ' open ' + c.action }
6679
+ }
6680
+ throw Object.assign(new Error('用法:/commit add ... 或 /commit ls'), { code: 'E_USAGE' })
6681
+ }
6682
+ case '/done': {
6683
+ const { flags, positional } = parseFlags(Array.isArray(args) ? args : [])
6684
+ const id = positional[0]
6685
+ if (!id || !flags.evidence) throw Object.assign(new Error('用法:/done <id> --evidence <证据>'), { code: 'E_USAGE' })
6686
+ state.ledger.completeCommitment(id, [manualEvidence(String(flags.evidence), 'repl commit done')])
6687
+ saveLedger(state.ledger)
6688
+ return { kind: 'notice', headline: 'done: ' + id }
6689
+ }
6690
+ case '/routine': {
6691
+ if (sub !== 'save') throw Object.assign(new Error('usage: /routine save'), { code: 'E_USAGE' })
6692
+ const last = lastRun
6693
+ const routine = state.ledger.addRoutine({
6694
+ name: (last?.toolLog?.map((tool) => tool.name).join(' ') || '本地任务').slice(0, 60),
6695
+ description: '从本地任务沉淀的流程草稿',
6696
+ trigger: [],
6697
+ steps: last?.toolLog?.map((tool) => tool.name).length ? last.toolLog.map((tool) => tool.name) : ['执行任务'],
6698
+ preferences: [],
6699
+ pitfalls: [],
6700
+ verification: ['产物已生成并记录 delivery'],
6701
+ createdBy: 'agent',
6702
+ })
6703
+ saveLedger(state.ledger)
6704
+ return { kind: 'notice', headline: 'draft routine ' + routine.id, summary: String(routine.name), next: 'advisers routine approve ' + routine.id }
6705
+ }
6706
+ case '/brief': {
6707
+ const text = String(arg ?? '').trim()
6708
+ if (!text) throw Object.assign(new Error('usage: /brief <text>'), { code: 'E_USAGE' })
6709
+ const lines = await captureConsole(() => { const brief = state.runtime.brief(text); console.log(core.renderIntentBrief(brief)); console.log(core.renderReadback(brief)) })
6710
+ return { lines }
6711
+ }
6712
+ default:
6713
+ return undefined
6714
+ }
6715
+ },
5934
6716
  }
5935
- for (const m of matters) {
5936
- console.log(`${m.id}\t${m.status}\tsecrecy=${m.secrecy}\t${m.title}`)
6717
+ const result = await shell.runShell({
6718
+ argv: outputArgv,
6719
+ env: process.env,
6720
+ stdin: process.stdin,
6721
+ stdout: process.stdout,
6722
+ stderr: process.stderr,
6723
+ store: null,
6724
+ allowPaths: state.allowPaths,
6725
+ handlers,
6726
+ })
6727
+ try { saveLedger(state.ledger) } catch {}
6728
+ return result
6729
+ }
6730
+
6731
+
6732
+ /* ---------------------------------------------------------------------------
6733
+ * 0.4.0 Wave 2 (task-29): KB / fact / scoped-search commands.
6734
+ *
6735
+ * Design source: 04-0.4-research/45-kb-design.md sections 3.4-3.7. Human output
6736
+ * and machine output stay separate: --json prints one JSON document and nothing
6737
+ * else; failures go to stderr as {error:{code,message,hint?}} with exit code 1
6738
+ * (the TOS gate still uses 3).
6739
+ * ------------------------------------------------------------------------- */
6740
+
6741
+ /** One structured family error (new 0.4 command family style). */
6742
+ function familyError(code, message, hint) {
6743
+ const error = new Error(message)
6744
+ error.code = code
6745
+ if (typeof hint === 'string' && hint) error.hint = hint
6746
+ return error
6747
+ }
6748
+
6749
+ /** Print one family failure as stderr JSON and exit 1 (store failures keep the
6750
+ * documented E_DB_* hint path instead). */
6751
+ function reportFamilyFailure(error) {
6752
+ if (isStoreWriteFailure(error)) { exitStoreWriteFailure(error); return }
6753
+ const code = typeof error?.code === 'string' && error.code ? error.code : 'E_INTERNAL'
6754
+ let message = String(error?.message ?? error)
6755
+ if (message.startsWith(code + ': ')) message = message.slice(code.length + 2)
6756
+ const hintTail = message.lastIndexOf(' (hint: ')
6757
+ if (hintTail !== -1 && message.endsWith(')')) message = message.slice(0, hintTail)
6758
+ const payload = { error: { code, message } }
6759
+ if (typeof error?.hint === 'string' && error.hint) payload.error.hint = error.hint
6760
+ console.error(JSON.stringify(payload))
6761
+ process.exitCode = 1
6762
+ }
6763
+
6764
+ /** Resolve the SQLite store for a family command (null in JSON-store mode). */
6765
+ function familyStore({ write = false } = {}) {
6766
+ if (mode !== 'sqlite') {
6767
+ throw familyError('E_STORE_REQUIRED', 'this command needs the SQLite store (ADVISERS_STORE=sqlite)', 'unset ADVISERS_STORE=json or run advisers doctor')
5937
6768
  }
6769
+ if (write) {
6770
+ const store = dbStore()
6771
+ if (!store) throw familyError('E_STORE_REQUIRED', 'the SQLite store is unavailable for writing', 'run advisers doctor')
6772
+ return store
6773
+ }
6774
+ return readStoreOrExit()
5938
6775
  }
5939
6776
 
5940
- function why(id) {
5941
- if (!id) {
5942
- console.error('usage: advisers why <pref-id|fact-id>')
5943
- process.exitCode = 1
6777
+ /** Shared strict flag parse that reports E_USAGE for the family commands. */
6778
+ function familyFlags(args, spec, usage) {
6779
+ const parsed = parseStrictFlags(args, spec)
6780
+ if (!parsed.ok) { usageFail(parsed.error, usage); return null }
6781
+ return parsed
6782
+ }
6783
+
6784
+ function familyInteger(value, name, min, max) {
6785
+ if (value === undefined) return undefined
6786
+ if (!/^\d+$/.test(String(value))) throw familyError('E_USAGE', name + ' must be an integer')
6787
+ const number = Number(value)
6788
+ if (number < min || number > max) throw familyError('E_USAGE', name + ' must be an integer ' + min + '..' + max)
6789
+ return number
6790
+ }
6791
+
6792
+ const KB_USAGE = [
6793
+ 'usage: advisers kb add <file>... [--title s] [--kind quote|contract|receipt|delivery|note|other]',
6794
+ ' [--client id] [--project id] [--matter id] [--secrecy 0-3] [--replace] [--from list.txt] [--json]',
6795
+ ' advisers kb ls [--client|--matter|--kind] [--all] [--limit n] [--clearance 0-3] [--json]',
6796
+ ' advisers kb show <id> [--chunks 0..20] [--json]',
6797
+ ' advisers kb rm <id> [--json]',
6798
+ ' advisers kb purge <id> [--dry-run|--yes] [--json]',
6799
+ ' advisers kb reindex [--rebuild] [--json]',
6800
+ ' advisers kb search <query> [--scope kb|pages|all] [--limit n] [--clearance 0-3] [--json]',
6801
+ ' advisers kb page ls|show|rebuild|diff ... [--json]',
6802
+ ].join('\n')
6803
+
6804
+ function kbDocRowText(doc) {
6805
+ return doc.id + ' ' + doc.kind + ' ' + (doc.status === 'active' ? '' : '[' + doc.status + '] ') + doc.title + ' (' + doc.chunkCount + ' chunks, ' + doc.sizeBytes + ' B)'
6806
+ }
6807
+
6808
+ async function kbAddCommand(args) {
6809
+ const usage = 'usage: advisers kb add <file>... [--title s] [--kind k] [--client id] [--project id] [--matter id] [--secrecy 0-3] [--replace] [--from list.txt] [--json]'
6810
+ const parsed = familyFlags(args, { booleans: ['json', 'replace'], values: ['title', 'kind', 'client', 'project', 'matter', 'secrecy', 'from'] }, usage)
6811
+ if (!parsed) return
6812
+ const flags = parsed.flags
6813
+ let secrecy
6814
+ if (flags.secrecy !== undefined) secrecy = familyInteger(flags.secrecy, '--secrecy', 0, 3)
6815
+ const files = [...parsed.positional]
6816
+ if (typeof flags.from === 'string') {
6817
+ let list
6818
+ try { list = readFileSync(flags.from, 'utf8') } catch (error) { throw familyError('E_KB_READ', 'cannot read --from list: ' + (error?.message ?? error)) }
6819
+ for (const line of list.split(/\r?\n/)) {
6820
+ const value = line.trim()
6821
+ if (value && !value.startsWith('#')) files.push(value)
6822
+ }
6823
+ }
6824
+ if (!files.length) { usageFail('no input files', usage); return }
6825
+ const store = familyStore({ write: true })
6826
+ const kb = await loadKb()
6827
+ const added = []
6828
+ const skipped = []
6829
+ const failed = []
6830
+ let chunks = 0
6831
+ let textBytes = 0
6832
+ let truncated = 0
6833
+ let needsOcr = 0
6834
+ for (const file of files) {
6835
+ try {
6836
+ const result = await kb.kbAdd(store, { file, title: flags.title, kind: flags.kind, clientId: flags.client, projectId: flags.project, matterId: flags.matter, secrecy, replace: flags.replace === true, hmacKey: process.env.ADVISERS_AUDIT_KEY })
6837
+ const doc = result.document
6838
+ added.push({ id: doc.id, title: doc.title, kind: doc.kind, sizeBytes: doc.sizeBytes, textBytes: result.counts.textBytes, chunks: result.counts.chunks, truncated: result.truncated, needsOcr: doc.needsOcr, encoding: doc.encoding })
6839
+ chunks += result.counts.chunks
6840
+ textBytes += result.counts.textBytes
6841
+ if (result.truncated) truncated += 1
6842
+ if (doc.needsOcr) needsOcr += 1
6843
+ } catch (error) {
6844
+ if (error?.skip === true) skipped.push({ file, code: error.code ?? 'E_KB_DUPLICATE', existingId: error.existingId })
6845
+ else failed.push({ file, code: typeof error?.code === 'string' ? error.code : 'E_KB_INVALID', message: String(error?.message ?? error) })
6846
+ }
6847
+ }
6848
+ const payload = { ok: failed.length === 0, command: 'kb add', counts: { added: added.length, skipped: skipped.length, failed: failed.length, chunks, textBytes }, added, skipped, failed, truncated, needsOcr }
6849
+ if (failed.length) process.exitCode = 1
6850
+ if (flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
6851
+ for (const item of added) console.log('added ' + item.id + ' ' + item.title + ' (' + item.chunks + ' chunks, ' + item.textBytes + ' B text)')
6852
+ for (const item of skipped) console.log('skipped ' + item.file + ' ' + item.code + (item.existingId ? ' existing ' + item.existingId : ''))
6853
+ for (const item of failed) console.error('failed ' + item.file + ' ' + item.code + ': ' + item.message)
6854
+ console.log('counts: added=' + added.length + ' skipped=' + skipped.length + ' failed=' + failed.length + ' chunks=' + chunks + ' textBytes=' + textBytes)
6855
+ }
6856
+
6857
+ async function kbListCommand(args) {
6858
+ const usage = 'usage: advisers kb ls [--client id] [--matter id] [--kind k] [--all] [--limit n] [--clearance 0-3] [--json]'
6859
+ const parsed = familyFlags(args, { booleans: ['json', 'all'], values: ['client', 'matter', 'kind', 'limit', 'clearance'] }, usage)
6860
+ if (!parsed) return
6861
+ const flags = parsed.flags
6862
+ const store = familyStore()
6863
+ const kb = await loadKb()
6864
+ const result = kb.kbList(store, {
6865
+ clientId: flags.client,
6866
+ matterId: flags.matter,
6867
+ kind: flags.kind,
6868
+ all: flags.all === true,
6869
+ limit: familyInteger(flags.limit, '--limit', 1, 200),
6870
+ clearance: familyInteger(flags.clearance, '--clearance', 0, 3),
6871
+ })
6872
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6873
+ if (!result.documents.length) console.log('(没有 KB 文档)')
6874
+ for (const doc of result.documents) console.log(kbDocRowText(doc))
6875
+ console.log('total=' + result.total + ' limit=' + result.limit + ' clearance=' + result.clearance + (result.truncated ? ' truncated' : '') + (result.protectedExcluded ? ' protectedExcluded=' + result.protectedExcluded : ''))
6876
+ }
6877
+
6878
+ async function kbShowCommand(args) {
6879
+ const usage = 'usage: advisers kb show <id> [--chunks 0..20] [--clearance 0-3] [--json]'
6880
+ const parsed = familyFlags(args, { booleans: ['json'], values: ['chunks', 'clearance'] }, usage)
6881
+ if (!parsed) return
6882
+ const id = parsed.positional[0]
6883
+ if (!id) { usageFail('missing document id', usage); return }
6884
+ const kb = await loadKb()
6885
+ const result = kb.kbShow(familyStore(), id, { chunks: familyInteger(parsed.flags.chunks, '--chunks', 0, 20), clearance: familyInteger(parsed.flags.clearance, '--clearance', 0, 3) })
6886
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6887
+ const doc = result.document
6888
+ console.log(doc.id + ' ' + doc.kind + ' ' + doc.title)
6889
+ console.log('size=' + doc.sizeBytes + ' textBytes=' + doc.textBytes + ' chunks=' + doc.chunkCount + ' secrecy=' + doc.secrecy + ' status=' + doc.status)
6890
+ console.log('source=' + doc.sourceName + ' sha256=' + String(doc.sourceSha256 ?? '').slice(0, 16) + ' capturedAt=' + doc.capturedAt)
6891
+ if (result.chunks.length) {
6892
+ console.log('chunks (showing ' + result.chunks.length + '/' + result.chunksTotal + '):')
6893
+ for (const chunk of result.chunks) console.log(' #' + chunk.seq + ' ' + chunk.text + (chunk.truncated ? '…' : ''))
6894
+ }
6895
+ }
6896
+
6897
+ async function kbRmCommand(args) {
6898
+ const usage = 'usage: advisers kb rm <id> [--json]'
6899
+ const parsed = familyFlags(args, { booleans: ['json'], values: [] }, usage)
6900
+ if (!parsed) return
6901
+ const id = parsed.positional[0]
6902
+ if (!id) { usageFail('missing document id', usage); return }
6903
+ const kb = await loadKb()
6904
+ const result = kb.kbRm(familyStore({ write: true }), id)
6905
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6906
+ console.log('removed ' + result.document.id + ' ' + result.document.title + ' (' + result.counts.chunks + ' chunks)')
6907
+ }
6908
+
6909
+ async function kbPurgeCommand(args) {
6910
+ const usage = 'usage: advisers kb purge <id> [--dry-run|--yes] [--json]'
6911
+ const parsed = familyFlags(args, { booleans: ['json', 'dry-run', 'yes'], values: [] }, usage)
6912
+ if (!parsed) return
6913
+ const id = parsed.positional[0]
6914
+ if (!id) { usageFail('missing document id', usage); return }
6915
+ let yes = parsed.flags.yes === true
6916
+ if (!yes && parsed.flags['dry-run'] !== true && process.stdin.isTTY) yes = await askYesNo(null, '永久删除 KB 文档 ' + id + '?[y/N] ', false)
6917
+ const kb = await loadKb()
6918
+ const result = kb.kbPurge(familyStore({ write: yes }), id, { yes })
6919
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6920
+ if (result.dryRun) console.log('dry-run: 会物理删除 ' + id + '(chunks=' + result.counts.chunks + ', factLinks=' + result.counts.factLinks + ');加 --yes 执行')
6921
+ else console.log('purged ' + result.document.id + ' (' + result.counts.chunks + ' chunks, ' + result.counts.factLinks + ' fact links)')
6922
+ }
6923
+
6924
+ async function kbReindexCommand(args) {
6925
+ const usage = 'usage: advisers kb reindex [--rebuild] [--json]'
6926
+ const parsed = familyFlags(args, { booleans: ['json', 'rebuild'], values: [] }, usage)
6927
+ if (!parsed) return
6928
+ const kb = await loadKb()
6929
+ // kbReindex() may rebuild (a write) when the integrity probe fails, so it
6930
+ // always runs on the writable store (one audit row when anything changed).
6931
+ const store = familyStore({ write: true })
6932
+ const result = kb.kbReindex(store, { rebuild: parsed.flags.rebuild === true })
6933
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6934
+ console.log('integrity: ' + (result.integrity.ok ? 'ok' : 'BROKEN') + ' tokenizer=' + (result.integrity.tokenizer ?? 'LIKE-only'))
6935
+ if (result.rebuilt.length) console.log('rebuilt: ' + result.rebuilt.join(', '))
6936
+ else console.log('rebuilt: none (indexes already consistent; --rebuild forces)')
6937
+ console.log('counts: documents=' + result.counts.documents + ' chunks=' + result.counts.chunks + ' pages=' + result.counts.pages)
6938
+ if (result.degraded.length) console.log('degraded: ' + result.degraded.join(', '))
6939
+ if (!result.ok) process.exitCode = 1
6940
+ }
6941
+
6942
+ async function kbPageCommand(args) {
6943
+ const usage = [
6944
+ 'usage: advisers kb page ls [--kind client|project|timeline|facts] [--check] [--limit n] [--json]',
6945
+ ' advisers kb page show <id> [--stored] [--diff] [--json]',
6946
+ ' advisers kb page rebuild [--kind k] [--id page-id] [--only-stale] [--dry-run] [--json]',
6947
+ ' advisers kb page diff <id> [--json]',
6948
+ ].join('\n')
6949
+ const sub = args[0]
6950
+ const parsed = familyFlags(args.slice(1), { booleans: ['json', 'check', 'stored', 'diff', 'dry-run', 'only-stale'], values: ['kind', 'id', 'limit', 'clearance'] }, usage)
6951
+ if (!parsed) return
6952
+ const flags = parsed.flags
6953
+ const pages = await loadKbPages()
6954
+ const baseOptions = { kind: flags.kind, id: parsed.positional[0] ?? flags.id, limit: familyInteger(flags.limit, '--limit', 1, 500), clearance: familyInteger(flags.clearance, '--clearance', 0, 3) }
6955
+ if (sub === 'ls') {
6956
+ const result = pages.kbPageList(familyStore(), { ...baseOptions, check: flags.check === true })
6957
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6958
+ if (!result.pages.length) console.log('(没有页面;先运行 advisers kb page rebuild)')
6959
+ for (const page of result.pages) console.log(page.id + ' ' + page.kind + ' ' + page.title + (page.stale === true ? ' [STALE]' : page.stale === false ? ' [fresh]' : ''))
6960
+ console.log('total=' + result.total + ' limit=' + result.limit + (flags.check === true ? ' staleCount=' + result.staleCount : '') + (result.protectedExcluded ? ' protectedExcluded=' + result.protectedExcluded : ''))
5944
6961
  return
5945
6962
  }
5946
- if (id.startsWith('fact_')) {
5947
- const ledger = loadReadLedger({ facts: {} })
5948
- const fact = ledger.listFacts(undefined, true).find((f) => f.id === id)
5949
- if (!fact) { console.error(`unknown fact: ${id}`); process.exitCode = 1; return }
5950
- console.log(`${fact.id} [${fact.authority}] ${fact.subject} ${fact.predicate} ${fact.object}`)
5951
- console.log(`status: ${fact.status}; confidence: ${fact.confidence}`)
5952
- for (const e of fact.evidence ?? []) console.log(`evidence: ${e.ref ?? '-'} 「${e.quote ?? ''}」`)
6963
+ if (sub === 'show' || sub === 'diff') {
6964
+ const id = parsed.positional[0]
6965
+ if (!id) { usageFail('missing page id', usage); return }
6966
+ const result = sub === 'diff' ? pages.kbPageDiff(familyStore(), id, baseOptions) : pages.kbPageShow(familyStore(), id, { ...baseOptions, stored: flags.stored === true, diff: flags.diff === true })
6967
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6968
+ if (sub === 'diff') { console.log(result.diff || '(页面没有变化)'); return }
6969
+ const page = result.page
6970
+ console.log(page.id + ' ' + page.kind + ' ' + page.title + ' [' + (result.stale ? 'STALE' : 'fresh') + ']')
6971
+ if (page.markdown) process.stdout.write(page.markdown.endsWith('\n') ? page.markdown : page.markdown + '\n')
6972
+ if (result.diff) process.stdout.write(result.diff)
5953
6973
  return
5954
6974
  }
5955
- const pref = loadReadLedger({ preferences: {} }).findPreference(id)
5956
- if (!pref) {
5957
- console.error(`unknown preference: ${id}`)
5958
- process.exitCode = 1
6975
+ if (sub === 'rebuild') {
6976
+ const result = pages.kbPageRebuild(familyStore({ write: flags['dry-run'] !== true }), { ...baseOptions, dryRun: flags['dry-run'] === true })
6977
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6978
+ console.log((result.dryRun ? 'dry-run: ' : '') + 'built=' + result.counts.built + ' written=' + result.counts.written + ' unchanged=' + result.counts.unchanged + ' skipped=' + result.counts.skipped)
6979
+ if (result.degraded.length) console.log('degraded: ' + result.degraded.join(', '))
5959
6980
  return
5960
6981
  }
5961
- console.log(`${pref.id} [${pref.kind}/${pref.priority}] ${pref.statement}`)
5962
- console.log(`scope: ${pref.scope.level}${pref.scope.value ? ':' + pref.scope.value : ''}`)
5963
- console.log(`source: ${pref.source.type}${pref.source.quote ? ' — ' + pref.source.quote : ''}`)
5964
- console.log(`confidence: ${pref.confidence}; status: ${pref.status}`)
6982
+ usageFail('unknown kb page subcommand: ' + (sub ?? '(none)'), usage)
6983
+ }
6984
+
6985
+ async function kbSearchCommand(args, options = {}) {
6986
+ const usage = 'usage: advisers kb search <query> [--scope kb|pages|all] [--client id] [--matter id] [--kind k] [--limit n] [--clearance 0-3] [--json]'
6987
+ const parsed = familyFlags(args, { booleans: ['json'], values: ['scope', 'client', 'matter', 'kind', 'limit', 'clearance'] }, usage)
6988
+ if (!parsed) return
6989
+ const query = parsed.positional.join(' ').trim()
6990
+ if (!query) { usageFail('missing query', usage); return }
6991
+ const scope = options.scope ?? (parsed.flags.scope === undefined ? 'kb' : String(parsed.flags.scope))
6992
+ const kb = await loadKb()
6993
+ const store = familyStore()
6994
+ const result = kb.kbSearch(store, query, {
6995
+ scope,
6996
+ clientId: parsed.flags.client,
6997
+ matterId: parsed.flags.matter,
6998
+ kind: parsed.flags.kind,
6999
+ limit: familyInteger(parsed.flags.limit, '--limit', 1, 200),
7000
+ clearance: familyInteger(parsed.flags.clearance, '--clearance', 0, 3),
7001
+ })
7002
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7003
+ if (!result.hits.length) console.log('没有匹配')
7004
+ for (const hit of result.hits) console.log(hit.kind + '\t' + String(hit.title ?? hit.snippet ?? '') + (hit.snippet ? ' 「' + String(hit.snippet).replace(/\s+/g, ' ').slice(0, 120) + '」' : ''))
7005
+ console.log('counts: docs=' + result.counts.kbDocs + ' chunks=' + result.counts.kbChunks + ' pages=' + result.counts.kbPages + ' total=' + result.total + ' clearance=' + result.clearance + (result.degraded.length ? ' degraded=' + result.degraded.join(',') : ''))
5965
7006
  }
5966
7007
 
5967
- /**
5968
- * `advisers forget <id>` — soft delete (fact tombstone / preference deprecated).
5969
- *
5970
- * 0.2.3 §3.3.8: one targeted UPDATE, no full load/save and (as in 0.2.2) no audit
5971
- * row. An unknown id writes nothing and keeps the "unknown <kind>: <id>" text.
7008
+ async function kbCommand(rawArgs) {
7009
+ const sub = rawArgs[0]
7010
+ try {
7011
+ if (!sub || sub === 'help' || sub === '--help') { console.log(KB_USAGE); return }
7012
+ if (sub === 'add') return await kbAddCommand(rawArgs.slice(1))
7013
+ if (sub === 'ls' || sub === 'list') return await kbListCommand(rawArgs.slice(1))
7014
+ if (sub === 'show') return await kbShowCommand(rawArgs.slice(1))
7015
+ if (sub === 'rm' || sub === 'remove') return await kbRmCommand(rawArgs.slice(1))
7016
+ if (sub === 'purge') return await kbPurgeCommand(rawArgs.slice(1))
7017
+ if (sub === 'reindex') return await kbReindexCommand(rawArgs.slice(1))
7018
+ if (sub === 'page') return await kbPageCommand(rawArgs.slice(1))
7019
+ if (sub === 'search') return await kbSearchCommand(rawArgs.slice(1))
7020
+ usageFail('unknown kb subcommand: ' + sub, KB_USAGE)
7021
+ } catch (error) { reportFamilyFailure(error) }
7022
+ }
7023
+
7024
+ const FACT_USAGE = [
7025
+ 'usage: advisers fact show <id> [--include-deleted] [--json]',
7026
+ ' advisers fact history <id> [--json]',
7027
+ ' advisers fact as-of <YYYY-MM-DD|ISO> [--matter id] [--client id] [--subject s] [--predicate s] [--limit n] [--include-deleted] [--json]',
7028
+ ].join('\n')
7029
+
7030
+ function factLine(fact) {
7031
+ return fact.id + ' ' + fact.subject + ' ' + fact.predicate + ' ' + String(fact.object ?? '') + (fact.matterId ? ' [' + fact.matterId + ']' : '') + ' status=' + fact.status + ' recordedAt=' + fact.recordedAt + (fact.validFrom ? ' validFrom=' + fact.validFrom : '') + (fact.validTo ? ' validTo=' + fact.validTo : '')
7032
+ }
7033
+
7034
+ async function factCommand(rawArgs) {
7035
+ const sub = rawArgs[0]
7036
+ try {
7037
+ if (!sub || sub === 'help' || sub === '--help') { console.log(FACT_USAGE); return }
7038
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'include-deleted'], values: ['matter', 'client', 'subject', 'predicate', 'limit', 'at'] }, FACT_USAGE)
7039
+ if (!parsed) return
7040
+ const flags = parsed.flags
7041
+ const facts = await loadKbFacts()
7042
+ if (sub === 'show') {
7043
+ const id = parsed.positional[0]
7044
+ if (!id) { usageFail('missing fact id', FACT_USAGE); return }
7045
+ const result = facts.factShow(familyStore(), id, { includeDeleted: flags['include-deleted'] === true })
7046
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7047
+ console.log(factLine(result.fact))
7048
+ for (const evidence of result.fact.evidence ?? []) console.log(' evidence 「' + String(evidence.quote ?? '').slice(0, 200) + '」')
7049
+ for (const source of result.kbSources ?? []) console.log(' kb ' + source.docId + ' ' + String(source.title ?? ''))
7050
+ for (const warning of result.warnings ?? []) console.log(' warning: ' + warning)
7051
+ return
7052
+ }
7053
+ if (sub === 'history') {
7054
+ const id = parsed.positional[0]
7055
+ if (!id) { usageFail('missing fact id', FACT_USAGE); return }
7056
+ const result = facts.factHistory(familyStore(), id, { includeDeleted: flags['include-deleted'] !== false })
7057
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7058
+ console.log('history of ' + result.rootId + ' (' + result.items.length + ')')
7059
+ result.items.forEach((fact, index) => console.log(' ' + (index + 1) + '. ' + factLine(fact)))
7060
+ for (const warning of result.warnings) console.log(' warning: ' + warning)
7061
+ return
7062
+ }
7063
+ if (sub === 'as-of' || sub === 'asof') {
7064
+ const at = parsed.positional[0] ?? flags.at
7065
+ if (!at) { usageFail('missing as-of instant (YYYY-MM-DD or ISO)', FACT_USAGE); return }
7066
+ const result = facts.factAsOf(familyStore(), {
7067
+ at,
7068
+ matterId: flags.matter,
7069
+ clientId: flags.client,
7070
+ subject: flags.subject,
7071
+ predicate: flags.predicate,
7072
+ limit: familyInteger(flags.limit, '--limit', 1, 500),
7073
+ includeDeleted: flags['include-deleted'] === true,
7074
+ })
7075
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7076
+ console.log('as-of ' + result.at + '(本地日 ' + result.asOfLocalDay + ')· ' + result.items.length + ' 条')
7077
+ for (const fact of result.items) console.log(' ' + factLine(fact))
7078
+ for (const warning of result.warnings) console.log(' warning: ' + warning)
7079
+ if (result.degraded.length) console.log(' degraded: ' + result.degraded.join(', '))
7080
+ return
7081
+ }
7082
+ usageFail('unknown fact subcommand: ' + sub, FACT_USAGE)
7083
+ } catch (error) { reportFamilyFailure(error) }
7084
+ }
7085
+
7086
+ /**
7087
+ * 'search <q> --scope turns|kb|pages|facts|all' (0.4.0 additive).
7088
+ *
7089
+ * The default (no --scope, or --scope turns) path is the frozen 0.3.2 output;
7090
+ * this helper only runs for the KB-inclusive scopes. KB hits come from
7091
+ * lib/kb.kbSearch; scope=all also merges local turn hits (never model calls).
7092
+ */
7093
+ async function scopedSearch(args) {
7094
+ const usage = 'usage: advisers search <query> [--scope turns|kb|pages|facts|all] [--client id] [--matter id] [--kind k] [--limit n] [--clearance 0-3] [--json]'
7095
+ const parsed = familyFlags(args, { booleans: ['json', 'explain'], values: ['scope', 'client', 'matter', 'kind', 'limit', 'clearance'] }, usage)
7096
+ if (!parsed) return
7097
+ const query = parsed.positional.join(' ').trim()
7098
+ if (!query) { usageFail('missing query', usage); return }
7099
+ const scope = String(parsed.flags.scope ?? 'all')
7100
+ if (!['kb', 'pages', 'all', 'facts', 'turns'].includes(scope)) { usageFail('--scope must be turns, kb, pages, facts or all', usage); return }
7101
+ if (scope === 'turns') {
7102
+ const rows = readStoreOrExit()?.searchTurns(query, { limit: 10 }) ?? []
7103
+ if (parsed.flags.json) {
7104
+ console.log(JSON.stringify({ ok: true, command: 'search', query, scope: 'turns', counts: { turns: rows.length, kbDocs: 0, kbChunks: 0, kbPages: 0, facts: 0, preferences: 0 }, hits: rows.map((row) => ({ kind: 'turn', ref: { kind: 'turn', id: row.conversationId + '#' + row.seq }, snippet: String(row.content).slice(0, 240), at: row.createdAt })), total: rows.length, truncated: false, protectedExcluded: 0 }, null, 2))
7105
+ return
7106
+ }
7107
+ if (!rows.length) console.log('没有匹配')
7108
+ for (const row of rows) console.log(row.seq + '\t' + row.role + '\t' + row.content.replace(/\s+/g, ' ').slice(0, 160))
7109
+ return
7110
+ }
7111
+ const store = familyStore()
7112
+ const kb = await loadKb()
7113
+ const result = kb.kbSearch(store, query, {
7114
+ scope: scope === 'facts' ? 'kb' : scope,
7115
+ clientId: parsed.flags.client,
7116
+ matterId: parsed.flags.matter,
7117
+ kind: parsed.flags.kind,
7118
+ limit: familyInteger(parsed.flags.limit, '--limit', 1, 200),
7119
+ clearance: familyInteger(parsed.flags.clearance, '--clearance', 0, 3),
7120
+ })
7121
+ if (scope === 'all') {
7122
+ const turns = readStoreOrExit()?.searchTurns(query, { limit: 10 }) ?? []
7123
+ result.counts.turns = turns.length
7124
+ for (const row of turns) {
7125
+ if (result.hits.length >= result.limit) break
7126
+ result.hits.push({ kind: 'turn', ref: { kind: 'turn', id: row.conversationId + '#' + row.seq }, snippet: String(row.content).slice(0, 240), at: row.createdAt })
7127
+ }
7128
+ result.total = result.counts.kbDocs + result.counts.kbChunks + result.counts.kbPages + result.counts.turns
7129
+ result.truncated = result.total > result.hits.length
7130
+ }
7131
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7132
+ if (!result.hits.length) console.log('没有匹配')
7133
+ for (const hit of result.hits) console.log(String(hit.kind) + '\t' + String(hit.title ?? hit.snippet ?? '').slice(0, 200))
7134
+ console.log('counts: turns=' + result.counts.turns + ' docs=' + result.counts.kbDocs + ' chunks=' + result.counts.kbChunks + ' pages=' + result.counts.kbPages + ' facts=' + result.counts.facts + ' total=' + result.total + ' clearance=' + result.clearance)
7135
+ }
7136
+
7137
+
7138
+ /* ---------------------------------------------------------------------------
7139
+ * 0.4.0 Wave 3 (task-29): mail / receivable / payment / consent commands.
7140
+ *
7141
+ * Design sources: 41-mail-entry.md section 3.7, 48-customer-v2.md section 3.3,
7142
+ * 46-policy-evidence.md section 3.5. All of them are additive CLI commands:
7143
+ * human output and --json output are separate, failures go to stderr as
7144
+ * {error:{code,message,hint?}} with exit 1, and credentials never appear on
7145
+ * argv, in the ledger or in logs.
7146
+ * ------------------------------------------------------------------------- */
7147
+
7148
+ function flagString(flags, name, label, usage) {
7149
+ const value = flags[name]
7150
+ if (value === undefined) return undefined
7151
+ if (typeof value !== 'string' || !value.trim()) { usageFail('--' + label + ' requires a value', usage); return undefined }
7152
+ return value.trim()
7153
+ }
7154
+
7155
+ /** Prompt for a secret on the terminal without echo (TTY only). */
7156
+ async function promptHidden(question) {
7157
+ if (!process.stdin.isTTY) throw familyError('E_TERM_REQUIRED', 'a terminal is required for the hidden password prompt', 'pipe one line with --pass-stdin instead')
7158
+ return await new Promise((resolve) => {
7159
+ const stdin = process.stdin
7160
+ const output = process.stderr
7161
+ let value = ''
7162
+ let done = false
7163
+ const wasRaw = Boolean(stdin.isRaw)
7164
+ const finish = (result) => {
7165
+ if (done) return
7166
+ done = true
7167
+ try { stdin.setRawMode(wasRaw) } catch {}
7168
+ try { stdin.off('data', onData) } catch {}
7169
+ try { stdin.pause() } catch {}
7170
+ output.write('\n')
7171
+ resolve(result)
7172
+ }
7173
+ const onData = (chunk) => {
7174
+ for (const char of String(chunk)) {
7175
+ if (char === '\r' || char === '\n') { finish(value); return }
7176
+ if (char === '\u0003') { finish(undefined); return }
7177
+ if (char === '\u0004') { finish(value); return }
7178
+ if (char === '\u007f' || char === '\b') {
7179
+ if (value) { const chars = Array.from(value); chars.pop(); value = chars.join(''); output.write('\b \b') }
7180
+ continue
7181
+ }
7182
+ value += char
7183
+ output.write('*')
7184
+ }
7185
+ }
7186
+ output.write(question)
7187
+ try { stdin.setRawMode(true) } catch {}
7188
+ try { stdin.resume() } catch {}
7189
+ stdin.on('data', onData)
7190
+ })
7191
+ }
7192
+
7193
+ /** Read one secret line from stdin (non-TTY --pass-stdin path). */
7194
+ async function readSecretFromStdin() {
7195
+ let text = ''
7196
+ process.stdin.setEncoding('utf8')
7197
+ for await (const chunk of process.stdin) text += chunk
7198
+ const first = text.split(/\r?\n/)[0]
7199
+ return first === undefined ? '' : first
7200
+ }
7201
+
7202
+ /* -------------------------------- mail ---------------------------------- */
7203
+
7204
+ const MAIL_USAGE = [
7205
+ 'usage: advisers mail account add --name n --host h [--port 993] [--tls tls|starttls] --user u [--pass-stdin]',
7206
+ ' [--mailbox INBOX] [--retention-days 30] [--client id] [--matter id] [--json]',
7207
+ ' advisers mail account ls|show <account>|rm <account> [--json]',
7208
+ ' advisers mail sync [<account>] [--full] [--dry-run] [--since-days 30] [--limit 50] [--mailbox INBOX] [--json]',
7209
+ ' advisers mail ls [--account a] [--client id] [--status s] [--since 30d] [--limit n] [--json]',
7210
+ ' advisers mail show <id> [--body] [--json]',
7211
+ ' advisers mail extract [<id>...] [--all-new] [--local|--model] [--yes] [--matter id] [--limit n] [--dry-run] [--json]',
7212
+ ' advisers mail import <file|dir> [--limit n] [--dry-run] [--client id] [--project id] [--json]',
7213
+ ' advisers mail purge [--older-than 30d] [--dry-run|--yes] [--account a] [--json]',
7214
+ ].join('\n')
7215
+
7216
+ function mailHumanRow(message) {
7217
+ const from = sanitizeConsoleText(String(message.from ?? ''), { max: 120 })
7218
+ const subject = sanitizeConsoleText(String(message.subject ?? ''), { max: 200 })
7219
+ return message.id + ' ' + String(message.receivedAt ?? '').slice(0, 16) + ' ' + from + ' ' + subject + ' [' + message.status + ']'
7220
+ }
7221
+
7222
+ async function mailAccountCommand(args) {
7223
+ const sub = args[0]
7224
+ const rest = args.slice(1)
7225
+ const usage = 'usage: advisers mail account add|ls|show|rm ...'
7226
+ if (!sub || sub === 'help' || sub === '--help') { console.log(MAIL_USAGE); return }
7227
+ const mail = await loadMail()
7228
+ if (sub === 'add') {
7229
+ const parsed = familyFlags(rest, { booleans: ['json', 'pass-stdin'], values: ['name', 'host', 'port', 'tls', 'user', 'mailbox', 'client', 'matter', 'retention-days', 'pass'] }, usage)
7230
+ if (!parsed) return
7231
+ const flags = parsed.flags
7232
+ if (flags.pass !== undefined) throw familyError('E_MAIL_CONFIG', 'refusing a password on the command line (--pass)', 'use the interactive TTY prompt or --pass-stdin')
7233
+ const name = flagString(flags, 'name', 'name', usage)
7234
+ const host = flagString(flags, 'host', 'host', usage)
7235
+ const user = flagString(flags, 'user', 'user', usage)
7236
+ if (!name || !host || !user) { usageFail('--name, --host and --user are required', usage); return }
7237
+ let pass
7238
+ if (flags['pass-stdin'] === true) pass = await readSecretFromStdin()
7239
+ else pass = await promptHidden('IMAP 密码(输入不回显):')
7240
+ if (typeof pass !== 'string' || pass === '') throw familyError('E_MAIL_CONFIG', 'no IMAP password was provided', 'run in a terminal for the hidden prompt, or pipe one line with --pass-stdin')
7241
+ const store = familyStore({ write: true })
7242
+ const result = mail.mailAccountAdd(store, {
7243
+ name,
7244
+ host,
7245
+ port: flags.port === undefined ? undefined : familyInteger(flags.port, '--port', 1, 65535),
7246
+ tls: flags.tls,
7247
+ username: user,
7248
+ mailbox: flags.mailbox,
7249
+ clientId: flags.client,
7250
+ defaultMatterId: flags.matter,
7251
+ retentionDays: flags['retention-days'] === undefined ? undefined : familyInteger(flags['retention-days'], '--retention-days', 0, 3650),
7252
+ }, { credential: { user, pass }, home: HOME })
7253
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7254
+ const account = result.account
7255
+ console.log('added ' + account.id + ' ' + account.name + ' ' + account.username + '@' + account.host + ':' + account.port + ' (' + account.tls + ')')
7256
+ console.log('credential: ' + (account.hasCredential ? 'stored (0600, outside the ledger)' : 'not stored'))
7257
+ return
7258
+ }
7259
+ if (sub === 'ls' || sub === 'list') {
7260
+ const parsed = familyFlags(rest, { booleans: ['json', 'all'], values: [] }, usage)
7261
+ if (!parsed) return
7262
+ const result = mail.mailAccountList(familyStore(), { includeRemoved: parsed.flags.all === true, home: HOME })
7263
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7264
+ if (!result.accounts.length) console.log('(没有邮件账号)')
7265
+ for (const account of result.accounts) console.log(account.id + ' ' + account.name + ' ' + account.username + '@' + account.host + ':' + account.port + ' ' + account.status + (account.hasCredential ? ' credential' : ' no-credential'))
7266
+ return
7267
+ }
7268
+ if (sub === 'show') {
7269
+ const parsed = familyFlags(rest, { booleans: ['json'], values: [] }, usage)
7270
+ if (!parsed) return
7271
+ const ref = parsed.positional[0]
7272
+ if (!ref) { usageFail('missing account id or name', usage); return }
7273
+ const result = mail.mailAccountShow(familyStore(), ref, { home: HOME })
7274
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7275
+ const account = result.account
7276
+ console.log(account.id + ' ' + account.name + ' ' + account.username + '@' + account.host + ':' + account.port + ' (' + account.tls + ') ' + account.status)
7277
+ console.log('mailbox=' + account.mailbox + ' retentionDays=' + account.retentionDays + ' credential=' + (account.hasCredential ? 'stored' : 'missing') + (account.lastSyncAt ? ' lastSyncAt=' + account.lastSyncAt : ''))
7278
+ return
7279
+ }
7280
+ if (sub === 'rm' || sub === 'remove') {
7281
+ const parsed = familyFlags(rest, { booleans: ['json', 'purge-messages'], values: [] }, usage)
7282
+ if (!parsed) return
7283
+ const ref = parsed.positional[0]
7284
+ if (!ref) { usageFail('missing account id or name', usage); return }
7285
+ const result = mail.mailAccountRemove(familyStore({ write: true }), ref, { home: HOME, purgeMessages: parsed.flags['purge-messages'] === true })
7286
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7287
+ console.log('removed ' + result.accountId + ' credentialRemoved=' + (result.credentialRemoved ? 'yes' : 'no') + ' messagesDeleted=' + result.messagesDeleted)
7288
+ return
7289
+ }
7290
+ usageFail('unknown mail account subcommand: ' + sub, MAIL_USAGE)
7291
+ }
7292
+
7293
+ async function mailSyncCommand(args) {
7294
+ const usage = 'usage: advisers mail sync [<account>] [--full] [--dry-run] [--since-days n] [--limit n] [--mailbox INBOX] [--json]'
7295
+ const parsed = familyFlags(args, { booleans: ['json', 'full', 'dry-run'], values: ['account', 'since-days', 'limit', 'mailbox'] }, usage)
7296
+ if (!parsed) return
7297
+ const flags = parsed.flags
7298
+ const mail = await loadMail()
7299
+ const store = familyStore({ write: true })
7300
+ const requested = parsed.positional[0] ?? flags.account
7301
+ let accounts
7302
+ if (requested) accounts = [String(requested)]
7303
+ else {
7304
+ const listed = mail.mailAccountList(store, { home: HOME })
7305
+ accounts = listed.accounts.filter((account) => account.status === 'active' && (account.tls === 'tls' || account.tls === 'starttls')).map((account) => account.id)
7306
+ if (!accounts.length) throw familyError('E_MAIL_CONFIG', 'no IMAP account is configured', 'add one with advisers mail account add')
7307
+ }
7308
+ const results = []
7309
+ for (const account of accounts) {
7310
+ results.push(await mail.mailSync(store, account, {
7311
+ full: flags.full === true,
7312
+ dryRun: flags['dry-run'] === true,
7313
+ sinceDays: flags['since-days'] === undefined ? undefined : familyInteger(flags['since-days'], '--since-days', 1, 3650),
7314
+ limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 200),
7315
+ mailbox: flags.mailbox,
7316
+ home: HOME,
7317
+ }))
7318
+ }
7319
+ const payload = requested ? results[0] : { ok: true, command: 'mail sync', results }
7320
+ if (flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
7321
+ for (const result of results) console.log('sync ' + result.accountId + ' ' + result.mailbox + ': fetched=' + result.fetched + ' inserted=' + result.inserted + ' skipped=' + result.skipped + ' failed=' + result.failed + ' duplicates=' + result.duplicates + (result.dryRun ? ' (dry-run)' : '') + (result.needsResync ? ' NEEDS-RESYNC(--full)' : ''))
7322
+ }
7323
+
7324
+ function mailSinceDays(value) {
7325
+ if (value === undefined) return undefined
7326
+ const text = String(value).trim()
7327
+ const match = /^(\d+)d$/.exec(text)
7328
+ if (match) return familyInteger(match[1], '--since', 1, 3650)
7329
+ return familyInteger(text, '--since', 1, 3650)
7330
+ }
7331
+
7332
+ async function mailLsCommand(args) {
7333
+ const usage = 'usage: advisers mail ls [--account a] [--client id] [--status s] [--since 30d] [--limit n] [--json]'
7334
+ const parsed = familyFlags(args, { booleans: ['json'], values: ['account', 'client', 'status', 'since', 'limit'] }, usage)
7335
+ if (!parsed) return
7336
+ const flags = parsed.flags
7337
+ const mail = await loadMail()
7338
+ const result = mail.mailList(familyStore(), {
7339
+ account: flags.account,
7340
+ clientId: flags.client,
7341
+ status: flags.status,
7342
+ sinceDays: mailSinceDays(flags.since),
7343
+ limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 500),
7344
+ })
7345
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7346
+ if (!result.messages.length) console.log('(没有邮件)')
7347
+ for (const message of result.messages) console.log(mailHumanRow(message))
7348
+ console.log('total=' + result.total + ' limit=' + result.limit + (result.truncated ? ' truncated' : ''))
7349
+ }
7350
+
7351
+ async function mailShowCommand(args) {
7352
+ const usage = 'usage: advisers mail show <id> [--body] [--json]'
7353
+ const parsed = familyFlags(args, { booleans: ['json', 'body'], values: [] }, usage)
7354
+ if (!parsed) return
7355
+ const ref = parsed.positional[0]
7356
+ if (!ref) { usageFail('missing mail message id', usage); return }
7357
+ const mail = await loadMail()
7358
+ const result = mail.mailShow(familyStore(), ref, { body: parsed.flags.body === true })
7359
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7360
+ const message = result.message
7361
+ console.log(mailHumanRow(message))
7362
+ console.log('messageId=' + (message.messageId ?? '-') + ' uid=' + message.uid + ' size=' + (message.sizeBytes ?? '-') + ' retained=' + (message.retained === true ? 'yes' : 'no') + (message.clientId ? ' client=' + message.clientId : ''))
7363
+ if (parsed.flags.body === true) {
7364
+ console.log('---')
7365
+ process.stdout.write(String(message.bodyText ?? '') + '\n')
7366
+ }
7367
+ }
7368
+
7369
+ /**
7370
+ * Authorization + consent gate for model egress of local content.
7371
+ * evaluate/authorize come from lib/policy; the consent record is bound to the
7372
+ * surface + data class + provider + base URL. An audit failure fails closed.
7373
+ */
7374
+ async function authorizeModelEgress(surface, dataClass, options = {}) {
7375
+ const policy = await loadPolicy()
7376
+ const consent = await loadConsent()
7377
+ const provider = process.env.ADVISERS_PROVIDER || 'deepseek'
7378
+ const baseUrl = process.env.ADVISERS_BASE_URL || 'https://api.deepseek.com'
7379
+ const consentFact = consent.consentFacts(HOME, { surface, dataClass, provider, baseUrl })
7380
+ let tosFacts = { accepted: true, version: '', currentVersion: '', hashOk: true }
7381
+ try {
7382
+ const tos = await loadTos()
7383
+ const { info } = resolveTosFacts(tos)
7384
+ const status = tos.acceptanceStatus({ home: HOME, version: info.version, sha256: info.sha256 })
7385
+ tosFacts = { accepted: status.accepted === true, version: String(status.record?.version ?? info.version), currentVersion: info.version, hashOk: status.reason !== 'hash_mismatch' }
7386
+ } catch {}
7387
+ const audit = (event) => {
7388
+ const store = mode === 'sqlite' ? dbStore() : undefined
7389
+ if (!store) return { ok: false }
7390
+ try {
7391
+ store.appendAudit({
7392
+ actor: 'policy',
7393
+ action: 'policy.' + String(event.surface) + '.' + String(event.policyAction ?? event.action ?? 'unknown'),
7394
+ allowed: event.allowed === true,
7395
+ reason: [String(event.phase ?? ''), String(event.code ?? event.policyCode ?? '')].filter(Boolean).join(' ').slice(0, 300),
7396
+ })
7397
+ return { ok: true }
7398
+ } catch { return { ok: false } }
7399
+ }
7400
+ const facts = {
7401
+ v: 1,
7402
+ surface,
7403
+ action: 'model-egress',
7404
+ actor: 'cli',
7405
+ interactive: Boolean(process.stdin.isTTY),
7406
+ record: options && options.record && typeof options.record === 'object' ? options.record : null,
7407
+ safety: { action: 'allow' },
7408
+ tos: tosFacts,
7409
+ consent: consentFact,
7410
+ audit: { available: mode === 'sqlite' },
7411
+ trust: { tainted: true, sourceKinds: [dataClass] },
7412
+ now: new Date().toISOString(),
7413
+ }
7414
+ const decision = policy.authorize('model-egress', facts, { audit })
7415
+ if (decision.authorized !== true) {
7416
+ const code = typeof decision.code === 'string' ? decision.code : 'E_POLICY_DENIED'
7417
+ const hint = consentFact.granted === true
7418
+ ? 'model egress is not allowed for this surface/data class; see advisers privacy --matrix'
7419
+ : 'run advisers consent grant ' + surface + ' and read the prompt before sending content to the model provider'
7420
+ throw familyError(code, String(decision.reason ?? 'policy denied model egress'), hint)
7421
+ }
7422
+ // The effect digest authorize() bound is computed from the facts (surface /
7423
+ // action / dataClass; the facts carry record=null and no top-level provider),
7424
+ // so consumeDecision() must receive exactly that shape or it refuses.
7425
+ const effectRecord = options && options.record && typeof options.record === 'object' ? { kind: String(options.record.kind ?? 'record'), secrecy: Number(options.record.secrecy ?? 0) } : null
7426
+ return { policy, token: decision.token, effect: { surface, action: 'model-egress', dataClass, ...(effectRecord ? { record: effectRecord } : {}) }, audit }
7427
+ }
7428
+
7429
+ /** Run one authorized model effect, then write its result audit row. */
7430
+ async function runAuthorizedModelEffect(authorization, effectFn) {
7431
+ const { consumeDecision } = await loadPolicy()
7432
+ const consumed = consumeDecision(authorization.token, authorization.effect)
7433
+ let result
7434
+ try {
7435
+ result = await effectFn()
7436
+ } catch (error) {
7437
+ try { authorization.audit({ surface: authorization.effect.surface, policyAction: authorization.effect.action, phase: 'result', allowed: true, decisionId: consumed.decisionId, ok: false, code: typeof error?.code === 'string' ? error.code : 'E_POLICY_EFFECT_FAILED' }) } catch {}
7438
+ throw error
7439
+ }
7440
+ const wrote = authorization.audit({ surface: authorization.effect.surface, policyAction: authorization.effect.action, phase: 'result', allowed: true, decisionId: consumed.decisionId, ok: true })
7441
+ if (wrote?.ok !== true) throw familyError('E_POLICY_AUDIT_UNAVAILABLE', 'model extraction completed but its result audit could not be written', 'the effect already happened; run advisers audit and inspect the ledger before continuing')
7442
+ return result
7443
+ }
7444
+
7445
+ async function mailExtractCommand(args) {
7446
+ const usage = 'usage: advisers mail extract [<id>...] [--all-new] [--local|--model] [--yes] [--matter id] [--limit n] [--dry-run] [--json]'
7447
+ const parsed = familyFlags(args, { booleans: ['json', 'local', 'model', 'all-new', 'dry-run', 'yes'], values: ['account', 'matter', 'limit'] }, usage)
7448
+ if (!parsed) return
7449
+ const flags = parsed.flags
7450
+ if (flags.local === true && flags.model === true) { usageFail('--local and --model are mutually exclusive', usage); return }
7451
+ const useModel = flags.model === true
7452
+ if (useModel && flags.yes !== true) throw familyError('E_MAIL_MODEL_OPT_IN', 'mail extract --model requires an explicit --yes opt-in', 'the default local path is offline; --model sends message text to your configured model provider and needs consent')
7453
+ const mail = await loadMail()
7454
+ const store = familyStore({ write: true })
7455
+ const extractOptions = {
7456
+ model: useModel,
7457
+ confirmModel: useModel && flags.yes === true,
7458
+ apiKey: process.env.ADVISERS_API_KEY,
7459
+ modelName: process.env.ADVISERS_MODEL,
7460
+ account: flags.account,
7461
+ ids: parsed.positional.length ? parsed.positional : undefined,
7462
+ all: flags['all-new'] === true,
7463
+ matterId: flags.matter,
7464
+ limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 500),
7465
+ dryRun: flags['dry-run'] === true,
7466
+ secrecy: 0,
7467
+ }
7468
+ let result
7469
+ if (useModel) {
7470
+ // Protection by matter: model egress is refused for secrecy > 0 (the lib
7471
+ // repeats the check; the policy facts also carry the record secrecy).
7472
+ let secrecy = 0
7473
+ if (flags.matter) {
7474
+ const matter = familyStore().getMatter(String(flags.matter))
7475
+ if (!matter) throw familyError('E_MATTER_NOT_FOUND', 'unknown matter: ' + flags.matter, 'advisers matter ls')
7476
+ secrecy = Number(matter.secrecy ?? 0)
7477
+ }
7478
+ if (Number.isFinite(secrecy) && secrecy > 0) throw familyError('E_MAIL_MODEL_DISABLED', 'model extraction is disabled for protected matters (secrecy > 0)', 'use the default local extraction or move the mail to an unprotected matter')
7479
+ extractOptions.secrecy = secrecy
7480
+ const authorization = await authorizeModelEgress('mail.extract', 'mail', { record: { kind: 'mail', secrecy } })
7481
+ result = await runAuthorizedModelEffect(authorization, () => mail.mailExtract(store, extractOptions))
7482
+ } else {
7483
+ result = await mail.mailExtract(store, extractOptions)
7484
+ }
7485
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7486
+ console.log('mail extract (' + result.mode + '): scanned=' + result.scanned + ' candidates=' + result.candidates.length + ' skipped=' + result.skipped + ' failed=' + result.failed + (result.dryRun ? ' (dry-run)' : ''))
7487
+ for (const candidate of result.candidates.slice(0, 20)) console.log(' ' + String(candidate.id ?? '(preview)') + ' ' + String(candidate.action ?? candidate.statement ?? candidate.text ?? '').slice(0, 120))
7488
+ if (result.safetyWarnings?.length) console.log(' safety warnings: ' + result.safetyWarnings.length)
7489
+ }
7490
+
7491
+ async function mailImportCommand(args) {
7492
+ const usage = 'usage: advisers mail import <file|dir> [--limit n] [--dry-run] [--client id] [--project id] [--json]'
7493
+ const parsed = familyFlags(args, { booleans: ['json', 'dry-run'], values: ['limit', 'client', 'project', 'account'] }, usage)
7494
+ if (!parsed) return
7495
+ const target = parsed.positional[0]
7496
+ if (!target) { usageFail('missing .eml/.mbox file or directory', usage); return }
7497
+ const mail = await loadMail()
7498
+ const result = await mail.mailImport(familyStore({ write: parsed.flags['dry-run'] !== true }), {
7499
+ path: target,
7500
+ accountId: parsed.flags.account,
7501
+ clientId: parsed.flags.client,
7502
+ projectId: parsed.flags.project,
7503
+ limit: parsed.flags.limit === undefined ? undefined : familyInteger(parsed.flags.limit, '--limit', 1, 500),
7504
+ dryRun: parsed.flags['dry-run'] === true,
7505
+ })
7506
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7507
+ console.log('mail import: files=' + result.files + ' scanned=' + result.scanned + ' inserted=' + result.inserted + ' skipped=' + result.skipped + ' failed=' + result.failed + (result.dryRun ? ' (dry-run)' : ''))
7508
+ }
7509
+
7510
+ async function mailPurgeCommand(args) {
7511
+ const usage = 'usage: advisers mail purge [--older-than 30d] [--dry-run|--yes] [--account a] [--json]'
7512
+ const parsed = familyFlags(args, { booleans: ['json', 'dry-run', 'yes'], values: ['older-than', 'account'] }, usage)
7513
+ if (!parsed) return
7514
+ let olderThanDays
7515
+ if (parsed.flags['older-than'] !== undefined) {
7516
+ const text = String(parsed.flags['older-than']).trim()
7517
+ const match = /^(\d+)d$/.exec(text)
7518
+ olderThanDays = familyInteger(match ? match[1] : text, '--older-than', 1, 3650)
7519
+ }
7520
+ let yes = parsed.flags.yes === true
7521
+ const dryRun = parsed.flags['dry-run'] === true || !yes
7522
+ if (!dryRun && process.stdin.isTTY && parsed.flags['dry-run'] !== true) {
7523
+ yes = await askYesNo(null, '永久清除保留期外的邮件正文(元数据保留)?[y/N] ', false)
7524
+ if (!yes) { console.log('已取消。'); return }
7525
+ }
7526
+ const mail = await loadMail()
7527
+ const result = mail.mailPurge(familyStore({ write: yes }), { olderThanDays, account: parsed.flags.account, dryRun: !yes })
7528
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7529
+ if (result.dryRun) console.log('dry-run: 将清除 ' + result.wouldPurge + ' 封正文(' + formatBytes(result.bytesWouldFree) + '),跳过 ' + result.skippedPending + ' 封有待处理候选;加 --yes 执行')
7530
+ else console.log('purged bodies=' + result.messagesPurged + ' bytesFreed=' + formatBytes(result.bytesFreed) + ' skippedPending=' + result.skippedPending)
7531
+ }
7532
+
7533
+ async function mailCommand(rawArgs) {
7534
+ const sub = rawArgs[0]
7535
+ try {
7536
+ if (!sub || sub === 'help' || sub === '--help') { console.log(MAIL_USAGE); return }
7537
+ if (sub === 'account') return await mailAccountCommand(rawArgs.slice(1))
7538
+ if (sub === 'sync') return await mailSyncCommand(rawArgs.slice(1))
7539
+ if (sub === 'ls' || sub === 'list') return await mailLsCommand(rawArgs.slice(1))
7540
+ if (sub === 'show') return await mailShowCommand(rawArgs.slice(1))
7541
+ if (sub === 'extract') return await mailExtractCommand(rawArgs.slice(1))
7542
+ if (sub === 'import') return await mailImportCommand(rawArgs.slice(1))
7543
+ if (sub === 'purge') return await mailPurgeCommand(rawArgs.slice(1))
7544
+ usageFail('unknown mail subcommand: ' + sub, MAIL_USAGE)
7545
+ } catch (error) { reportFamilyFailure(error) }
7546
+ }
7547
+
7548
+ /* ------------------------- receivable / payment ------------------------- */
7549
+
7550
+ const RECEIVABLE_USAGE = [
7551
+ 'usage: advisers receivable add <client-id> "<label>" --amount 8000.00 [--currency CNY] [--due YYYY-MM-DD]',
7552
+ ' [--project id] [--matter id] [--kind quote|milestone|retainer|other] [--memo text]',
7553
+ ' [--remind-offsets "-3d,-1d"] [--no-remind] [--json]',
7554
+ ' advisers receivable ls|list [--client id] [--project id] [--status open|partial|overdue|settled|all]',
7555
+ ' [--currency CNY] [--aging] [--due-within 7d|30d] [--clearance 0-3] [--limit n] [--json]',
7556
+ ' advisers receivable show <id> [--json]',
7557
+ ' advisers receivable edit <id> [--amount 9000.00|--due DATE|--memo text|--kind k|--label text] [--json]',
7558
+ ' advisers receivable void <id> [--reason text] [--json]',
7559
+ ].join('\n')
7560
+
7561
+ const PAYMENT_USAGE = [
7562
+ 'usage: advisers payment add <client-id> --amount 4000.00 [--currency CNY] [--paid-at ISO] [--method bank|wechat|alipay|cash|other]',
7563
+ ' [--receivable rcv] [--memo text] [--no-complete] [--json]',
7564
+ ' advisers payment ls|list [--client id] [--receivable rcv] [--since 90d|ISO] [--limit n] [--json]',
7565
+ ' advisers payment void <id> [--reason text] [--json]',
7566
+ ].join('\n')
7567
+
7568
+ function receivableMoney(row) {
7569
+ return String(row.amount ?? '') + ' ' + String(row.currency ?? '') + (row.state ? ' ' + row.state : '') + (row.outstanding && row.outstanding !== row.amount ? ' outstanding ' + row.outstanding : '')
7570
+ }
7571
+
7572
+ async function receivableCommand(rawArgs) {
7573
+ const sub = rawArgs[0]
7574
+ try {
7575
+ if (!sub || sub === 'help' || sub === '--help') { console.log(RECEIVABLE_USAGE); return }
7576
+ const receivable = await loadReceivablesLib()
7577
+ if (sub === 'add') {
7578
+ const usage = RECEIVABLE_USAGE
7579
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'no-remind'], values: ['amount', 'currency', 'due', 'project', 'matter', 'kind', 'memo', 'remind-offsets'] }, usage)
7580
+ if (!parsed) return
7581
+ const clientId = parsed.positional[0]
7582
+ const label = parsed.positional.slice(1).join(' ').trim()
7583
+ if (!clientId || !label) { usageFail('usage: advisers receivable add <client-id> "<label>" --amount 8000.00', usage); return }
7584
+ if (parsed.flags.amount === undefined) { usageFail('--amount is required', usage); return }
7585
+ const result = receivable.receivableAdd(familyStore({ write: true }), {
7586
+ clientId,
7587
+ label,
7588
+ amount: parsed.flags.amount,
7589
+ currency: parsed.flags.currency,
7590
+ dueAt: parsed.flags.due,
7591
+ projectId: parsed.flags.project,
7592
+ matterId: parsed.flags.matter,
7593
+ kind: parsed.flags.kind,
7594
+ memo: parsed.flags.memo,
7595
+ reminderOffsets: parsed.flags['remind-offsets'],
7596
+ noRemind: parsed.flags['no-remind'] === true,
7597
+ })
7598
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7599
+ const row = result.receivable
7600
+ console.log('added ' + (row ? row.id : '(hidden)') + ' ' + label + ' ' + (row ? receivableMoney(row) : '') + (row && row.dueAt ? ' due ' + row.dueAt : ''))
7601
+ console.log('follow-up commitment: ' + result.commitment.id)
7602
+ return
7603
+ }
7604
+ if (sub === 'ls' || sub === 'list') {
7605
+ const usage = RECEIVABLE_USAGE
7606
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'aging'], values: ['client', 'project', 'status', 'currency', 'due-within', 'clearance', 'limit'] }, usage)
7607
+ if (!parsed) return
7608
+ const flags = parsed.flags
7609
+ const store = familyStore()
7610
+ const options = {
7611
+ clientId: flags.client,
7612
+ projectId: flags.project,
7613
+ status: flags.status,
7614
+ currency: flags.currency,
7615
+ dueWithin: flags['due-within'],
7616
+ clearance: flags.clearance === undefined ? undefined : familyInteger(flags.clearance, '--clearance', 0, 3),
7617
+ limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 500),
7618
+ }
7619
+ const result = flags.aging === true ? receivable.receivablesSummary(store, options) : receivable.receivableList(store, options)
7620
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7621
+ if (flags.aging === true) {
7622
+ console.log('unsettled=' + result.unsettled + ' overdue=' + result.overdue + ' settled=' + result.settled + ' writtenOff=' + result.writtenOff)
7623
+ for (const total of result.totals) console.log(' ' + total.currency + ' amount=' + receivable.formatMinorAmount(BigInt(total.amountMinor)) + ' paid=' + receivable.formatMinorAmount(BigInt(total.paidMinor)) + ' outstanding=' + receivable.formatMinorAmount(BigInt(total.outstandingMinor)) + ' overdueCount=' + total.overdueCount + ' aging=' + JSON.stringify(total.aging))
7624
+ return
7625
+ }
7626
+ if (!result.receivables.length) console.log('(没有回款记录)')
7627
+ for (const row of result.receivables) console.log(row.id + ' ' + String(row.clientName ?? row.clientId) + ' ' + row.label + ' ' + receivableMoney(row) + (row.dueAt ? ' due ' + row.dueAt : ''))
7628
+ for (const total of result.totals) console.log('total ' + total.currency + ' outstanding=' + receivable.formatMinorAmount(BigInt(total.outstandingMinor)) + ' overdueCount=' + total.overdueCount)
7629
+ console.log('total=' + result.total + ' limit=' + result.limit + (result.truncated ? ' truncated' : '') + (result.protectedExcluded ? ' protectedExcluded=' + result.protectedExcluded : ''))
7630
+ return
7631
+ }
7632
+ if (sub === 'show') {
7633
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['clearance'] }, RECEIVABLE_USAGE)
7634
+ if (!parsed) return
7635
+ const id = parsed.positional[0]
7636
+ if (!id) { usageFail('missing receivable id', RECEIVABLE_USAGE); return }
7637
+ const result = receivable.receivableShow(familyStore(), id, { clearance: parsed.flags.clearance === undefined ? undefined : familyInteger(parsed.flags.clearance, '--clearance', 0, 3) })
7638
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7639
+ const row = result.receivable
7640
+ console.log(row.id + ' ' + row.label + ' ' + receivableMoney(row) + (row.dueAt ? ' due ' + row.dueAt : '') + (row.overdueDays ? ' overdueDays=' + row.overdueDays : ''))
7641
+ console.log('client=' + row.clientId + (row.projectId ? ' project=' + row.projectId : '') + (row.matterId ? ' matter=' + row.matterId : '') + ' commitment=' + row.commitmentId)
7642
+ for (const payment of result.payments) console.log(' payment ' + payment.id + ' ' + payment.amount + ' ' + payment.currency + ' ' + payment.paidAt + ' ' + payment.method + (payment.deletedAt ? ' [void]' : ''))
7643
+ return
7644
+ }
7645
+ if (sub === 'edit') {
7646
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'no-remind'], values: ['amount', 'due', 'memo', 'kind', 'label', 'remind-offsets'] }, RECEIVABLE_USAGE)
7647
+ if (!parsed) return
7648
+ const id = parsed.positional[0]
7649
+ if (!id) { usageFail('missing receivable id', RECEIVABLE_USAGE); return }
7650
+ const patch = {}
7651
+ if (parsed.flags.amount !== undefined) patch.amount = parsed.flags.amount
7652
+ if (parsed.flags.due !== undefined) patch.dueAt = parsed.flags.due
7653
+ if (parsed.flags.memo !== undefined) patch.memo = parsed.flags.memo
7654
+ if (parsed.flags.kind !== undefined) patch.kind = parsed.flags.kind
7655
+ if (parsed.flags.label !== undefined) patch.label = parsed.flags.label
7656
+ if (parsed.flags['no-remind'] === true) patch.noRemind = true
7657
+ else if (parsed.flags['remind-offsets'] !== undefined) patch.reminderOffsets = parsed.flags['remind-offsets']
7658
+ const result = receivable.receivableEdit(familyStore({ write: true }), id, patch)
7659
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7660
+ console.log('updated ' + id + (result.receivable ? ' ' + receivableMoney(result.receivable) : ''))
7661
+ return
7662
+ }
7663
+ if (sub === 'void') {
7664
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['reason'] }, RECEIVABLE_USAGE)
7665
+ if (!parsed) return
7666
+ const id = parsed.positional[0]
7667
+ if (!id) { usageFail('missing receivable id', RECEIVABLE_USAGE); return }
7668
+ const result = receivable.receivableVoid(familyStore({ write: true }), id, { reason: parsed.flags.reason })
7669
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7670
+ console.log('void ' + id + (result.alreadyVoid ? ' (already void)' : '') + ' commitmentReopened=' + (result.reopenedCommitment ? 'yes' : 'no') + ' commitmentDropped=' + (result.droppedCommitment ? 'yes' : 'no'))
7671
+ return
7672
+ }
7673
+ usageFail('unknown receivable subcommand: ' + sub, RECEIVABLE_USAGE)
7674
+ } catch (error) { reportFamilyFailure(error) }
7675
+ }
7676
+
7677
+ async function paymentCommand(rawArgs) {
7678
+ const sub = rawArgs[0]
7679
+ try {
7680
+ if (!sub || sub === 'help' || sub === '--help') { console.log(PAYMENT_USAGE); return }
7681
+ const money = await loadReceivablesLib()
7682
+ if (sub === 'add') {
7683
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'no-complete'], values: ['amount', 'currency', 'paid-at', 'method', 'receivable', 'commitment', 'memo'] }, PAYMENT_USAGE)
7684
+ if (!parsed) return
7685
+ const clientId = parsed.positional[0]
7686
+ if (!clientId) { usageFail('usage: advisers payment add <client-id> --amount 4000.00', PAYMENT_USAGE); return }
7687
+ if (parsed.flags.amount === undefined) { usageFail('--amount is required', PAYMENT_USAGE); return }
7688
+ const result = money.paymentAdd(familyStore({ write: true }), {
7689
+ clientId,
7690
+ amount: parsed.flags.amount,
7691
+ currency: parsed.flags.currency,
7692
+ paidAt: parsed.flags['paid-at'],
7693
+ method: parsed.flags.method,
7694
+ receivableId: parsed.flags.receivable,
7695
+ commitmentId: parsed.flags.commitment,
7696
+ memo: parsed.flags.memo,
7697
+ noComplete: parsed.flags['no-complete'] === true,
7698
+ })
7699
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7700
+ console.log('added ' + result.payment.id + ' ' + result.payment.amount + ' ' + result.payment.currency + ' ' + result.payment.paidAt + ' ' + result.payment.method + (result.receivable ? ' receivable=' + result.receivable.id : '') + (result.completedCommitment ? ' commitmentCompleted=yes' : ''))
7701
+ return
7702
+ }
7703
+ if (sub === 'ls' || sub === 'list') {
7704
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['client', 'receivable', 'since', 'limit', 'clearance'] }, PAYMENT_USAGE)
7705
+ if (!parsed) return
7706
+ const result = money.paymentList(familyStore(), {
7707
+ clientId: parsed.flags.client,
7708
+ receivableId: parsed.flags.receivable,
7709
+ since: parsed.flags.since,
7710
+ clearance: parsed.flags.clearance === undefined ? undefined : familyInteger(parsed.flags.clearance, '--clearance', 0, 3),
7711
+ limit: parsed.flags.limit === undefined ? undefined : familyInteger(parsed.flags.limit, '--limit', 1, 500),
7712
+ })
7713
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7714
+ if (!result.payments.length) console.log('(没有收款记录)')
7715
+ for (const payment of result.payments) console.log(payment.id + ' ' + payment.amount + ' ' + payment.currency + ' ' + payment.paidAt + ' ' + payment.method + (payment.receivableId ? ' rcv=' + payment.receivableId : ''))
7716
+ console.log('total=' + result.total + ' limit=' + result.limit + (result.truncated ? ' truncated' : ''))
7717
+ return
7718
+ }
7719
+ if (sub === 'void') {
7720
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['reason'] }, PAYMENT_USAGE)
7721
+ if (!parsed) return
7722
+ const id = parsed.positional[0]
7723
+ if (!id) { usageFail('missing payment id', PAYMENT_USAGE); return }
7724
+ const result = money.paymentVoid(familyStore({ write: true }), id, { reason: parsed.flags.reason })
7725
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7726
+ console.log('void ' + id + (result.alreadyVoid ? ' (already void)' : '') + ' commitmentReopened=' + (result.reopenedCommitment ? 'yes' : 'no'))
7727
+ return
7728
+ }
7729
+ usageFail('unknown payment subcommand: ' + sub, PAYMENT_USAGE)
7730
+ } catch (error) { reportFamilyFailure(error) }
7731
+ }
7732
+
7733
+ /* ------------------------------- consent -------------------------------- */
7734
+
7735
+ const CONSENT_USAGE = [
7736
+ 'usage: advisers consent status [--json]',
7737
+ ' advisers consent grant <surface> [--data-class mail|kb] [--provider deepseek] [--base-url URL] [--yes] [--json]',
7738
+ ' advisers consent revoke <surface> [--data-class mail|kb] [--provider p] [--base-url URL] [--yes] [--json]',
7739
+ ].join('\n')
7740
+
7741
+ function consentDataClassFor(surface, explicit) {
7742
+ if (explicit !== undefined) return String(explicit)
7743
+ const table = { 'mail.extract': 'mail', 'mail.sync': 'mail', 'kb.ask': 'kb', 'kb.ingest': 'kb', 'kb.search': 'kb' }
7744
+ return table[surface] ?? undefined
7745
+ }
7746
+
7747
+ async function consentCommand(rawArgs) {
7748
+ const sub = rawArgs[0]
7749
+ try {
7750
+ if (!sub || sub === 'help' || sub === '--help') { console.log(CONSENT_USAGE); return }
7751
+ const consent = await loadConsent()
7752
+ if (sub === 'status') {
7753
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: [] }, CONSENT_USAGE)
7754
+ if (!parsed) return
7755
+ const entries = consent.listConsents(HOME)
7756
+ const payload = { ok: true, command: 'consent status', path: consent.consentPath(HOME), configured: entries.length > 0, entries }
7757
+ if (parsed.flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
7758
+ console.log('consent file: ' + payload.path + (payload.configured ? '' : '(尚未记录任何同意)'))
7759
+ if (!entries.length) console.log('(没有同意的数据外发)')
7760
+ for (const entry of entries) console.log(entry.surface + ' ' + entry.dataClass + ' ' + entry.provider + (entry.baseUrl ? ' ' + entry.baseUrl : '') + ' ' + (entry.active ? 'granted ' + entry.grantedAt : 'revoked ' + entry.revokedAt))
7761
+ return
7762
+ }
7763
+ if (sub === 'grant' || sub === 'revoke') {
7764
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'yes'], values: ['data-class', 'provider', 'base-url', 'consent'] }, CONSENT_USAGE)
7765
+ if (!parsed) return
7766
+ const surface = parsed.positional[0]
7767
+ if (!surface) { usageFail('missing surface (for example mail.extract)', CONSENT_USAGE); return }
7768
+ const dataClass = consentDataClassFor(surface, parsed.flags['data-class'])
7769
+ if (!dataClass) throw familyError('E_POLICY_INVALID_FACTS', 'unknown consent data class for ' + surface, 'pass --data-class mail or --data-class kb')
7770
+ const provider = typeof parsed.flags.provider === 'string' ? parsed.flags.provider : (process.env.ADVISERS_PROVIDER || 'deepseek')
7771
+ const baseUrl = typeof parsed.flags['base-url'] === 'string' ? parsed.flags['base-url'] : (process.env.ADVISERS_BASE_URL || 'https://api.deepseek.com')
7772
+ const isTTY = Boolean(process.stdin.isTTY)
7773
+ const envOverride = process.env['ADVISERS_CONSENT_' + surface.toUpperCase().replace(/[^A-Z0-9]/g, '_')] === '1'
7774
+ const explicit = parsed.flags.yes === true || parsed.flags.consent !== undefined || envOverride
7775
+ if (sub === 'grant') {
7776
+ if (!isTTY && !explicit) throw familyError('E_CONSENT_CONFIRMATION_UNAVAILABLE', 'non-interactive consent grant requires an explicit --yes (or ADVISERS_CONSENT_<SURFACE>=1)', 'read advisers tos show and docs/PRIVACY.md first; this is a separate model-egress consent')
7777
+ if (isTTY && !explicit) {
7778
+ const answer = await askYesNo(null, '同意把 ' + dataClass + ' 内容发送给模型服务 ' + provider + (baseUrl ? ' (' + baseUrl + ')' : '') + '(' + surface + ')?[y/N] ', false)
7779
+ if (!answer) { console.log('已取消,未写入同意记录。'); return }
7780
+ }
7781
+ } else {
7782
+ if (!isTTY && !explicit) throw familyError('E_CONSENT_CONFIRMATION_UNAVAILABLE', 'non-interactive consent revoke requires an explicit --yes', 'run in a terminal to confirm the revocation')
7783
+ if (isTTY && !explicit) {
7784
+ const answer = await askYesNo(null, '撤回 ' + surface + ' 的同意?[y/N] ', false)
7785
+ if (!answer) { console.log('已取消。'); return }
7786
+ }
7787
+ }
7788
+ const audit = (event) => {
7789
+ const store = mode === 'sqlite' ? dbStore() : undefined
7790
+ if (!store) return { ok: false }
7791
+ try { store.appendAudit({ actor: 'local', action: event.action, allowed: event.ok === true, reason: String(event.surface) + ' ' + String(event.dataClass ?? '') }); return { ok: true } } catch { return { ok: false } }
7792
+ }
7793
+ const channel = isTTY ? 'tty' : 'flag'
7794
+ const result = sub === 'grant'
7795
+ ? consent.grantConsent(HOME, { surface, dataClass, provider, baseUrl, channel, audit })
7796
+ : consent.revokeConsent(HOME, { surface, dataClass, provider, baseUrl, audit })
7797
+ const payload = { ok: true, command: 'consent ' + sub, ...result, auditWritten: result.auditWritten === true }
7798
+ if (parsed.flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
7799
+ if (sub === 'grant') console.log('granted ' + surface + ' / ' + dataClass + ' / ' + provider + ' (channel=' + channel + ')')
7800
+ else console.log('revoked ' + result.revoked + ' consent entr' + (result.revoked === 1 ? 'y' : 'ies') + ' for ' + surface)
7801
+ return
7802
+ }
7803
+ usageFail('unknown consent subcommand: ' + sub, CONSENT_USAGE)
7804
+ } catch (error) { reportFamilyFailure(error) }
7805
+ }
7806
+
7807
+ function ls() {
7808
+ const matters = loadReadLedger({ matters: {} }).listMatters()
7809
+ if (!matters.length) {
7810
+ console.log('no matters yet')
7811
+ return
7812
+ }
7813
+ for (const m of matters) {
7814
+ console.log(`${m.id}\t${m.status}\tsecrecy=${m.secrecy}\t${m.title}`)
7815
+ }
7816
+ }
7817
+
7818
+ function why(id) {
7819
+ if (!id) {
7820
+ console.error('usage: advisers why <pref-id|fact-id>')
7821
+ process.exitCode = 1
7822
+ return
7823
+ }
7824
+ if (id.startsWith('fact_')) {
7825
+ const ledger = loadReadLedger({ facts: {} })
7826
+ const fact = ledger.listFacts(undefined, true).find((f) => f.id === id)
7827
+ if (!fact) { console.error(`unknown fact: ${id}`); process.exitCode = 1; return }
7828
+ console.log(`${fact.id} [${fact.authority}] ${fact.subject} ${fact.predicate} ${fact.object}`)
7829
+ console.log(`status: ${fact.status}; confidence: ${fact.confidence}`)
7830
+ for (const e of fact.evidence ?? []) console.log(`evidence: ${e.ref ?? '-'} 「${e.quote ?? ''}」`)
7831
+ return
7832
+ }
7833
+ const pref = loadReadLedger({ preferences: {} }).findPreference(id)
7834
+ if (!pref) {
7835
+ console.error(`unknown preference: ${id}`)
7836
+ process.exitCode = 1
7837
+ return
7838
+ }
7839
+ console.log(`${pref.id} [${pref.kind}/${pref.priority}] ${pref.statement}`)
7840
+ console.log(`scope: ${pref.scope.level}${pref.scope.value ? ':' + pref.scope.value : ''}`)
7841
+ console.log(`source: ${pref.source.type}${pref.source.quote ? ' — ' + pref.source.quote : ''}`)
7842
+ console.log(`confidence: ${pref.confidence}; status: ${pref.status}`)
7843
+ }
7844
+
7845
+ /**
7846
+ * `advisers forget <id>` — soft delete (fact tombstone / preference deprecated).
7847
+ *
7848
+ * 0.2.3 §3.3.8: one targeted UPDATE, no full load/save and (as in 0.2.2) no audit
7849
+ * row. An unknown id writes nothing and keeps the "unknown <kind>: <id>" text.
5972
7850
  */
5973
7851
  function forget(id) {
5974
7852
  if (!id) {
@@ -6236,6 +8114,121 @@ function applyCustomerImport(store, tables) {
6236
8114
  return { clients: clientCount, projects: projectCount, clientNotes: noteCount, reconciledDeliveries: reconciledDeliveries }
6237
8115
  }
6238
8116
 
8117
+
8118
+ /* ---------------------------------------------------------------------------
8119
+ * 0.4.0 (task-29): export --all / import --replace symmetry.
8120
+ *
8121
+ * export --all writes DATA_TABLES (KB, mail, money included). import --replace
8122
+ * validates and restores the same table list in ONE transaction: the ledger via
8123
+ * saveWithAudit, the customer tables through the 0.3.2 reference checks, and the
8124
+ * derived/auxiliary tables (sessions/turns/deliveries/audit/KB/mail/money).
8125
+ * Derived FTS tables and mail_cursors are never imported; kb_pages is dropped
8126
+ * because its inputs changed.
8127
+ * ------------------------------------------------------------------------- */
8128
+ const MONEY_IMPORT_TABLES = ['receivables', 'payments']
8129
+ // mail_cursors: server-side IMAP cursors are meaningless on another machine.
8130
+ // audit: the hash chain is keyed by THIS home's audit.key, so importing another
8131
+ // home's rows would report a broken chain; the local chain is preserved and the
8132
+ // import keeps appending to it.
8133
+ const IMPORT_TABLE_DENYLIST = new Set(['mail_cursors', 'audit'])
8134
+ const IMPORT_TABLES = DATA_TABLES.filter((table) => !IMPORT_TABLE_DENYLIST.has(table))
8135
+
8136
+ /** Validate the shape of payload.data before any write happens (all DATA_TABLES). */
8137
+ function prepareDataImport(payloadData) {
8138
+ if (!payloadData || typeof payloadData !== 'object' || Array.isArray(payloadData)) return null
8139
+ const present = IMPORT_TABLES.filter((table) => Object.prototype.hasOwnProperty.call(payloadData, table))
8140
+ if (!present.length) return null
8141
+ const tables = {}
8142
+ for (const table of IMPORT_TABLES) {
8143
+ if (!Object.prototype.hasOwnProperty.call(payloadData, table)) {
8144
+ // A pre-0.4 export has no money tables: clear them so old commitments are
8145
+ // never left with dangling money rows. Other absent tables are left as-is.
8146
+ tables[table] = MONEY_IMPORT_TABLES.includes(table) ? [] : null
8147
+ continue
8148
+ }
8149
+ const rows = payloadData[table]
8150
+ if (!Array.isArray(rows)) throw importDataError('import data.' + table + ' must be an array')
8151
+ if (rows.length > CUSTOMER_IMPORT_MAX_ROWS) throw importDataError('import data.' + table + ' has too many rows (max ' + CUSTOMER_IMPORT_MAX_ROWS + ')')
8152
+ for (let index = 0; index < rows.length; index += 1) {
8153
+ const row = rows[index]
8154
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw importDataError('import data.' + table + '[' + index + '] must be an object')
8155
+ }
8156
+ tables[table] = rows
8157
+ }
8158
+ return tables
8159
+ }
8160
+
8161
+ /**
8162
+ * Restore every exported DATA_TABLES entry inside the import transaction.
8163
+ * Throws importDataError on a dangling reference; the caller's transaction rolls
8164
+ * back and the pre-import backup stays as the recovery copy.
8165
+ */
8166
+ function applyDataImport(store, tables) {
8167
+ const report = { tables: {}, customer: null, cleared: [], kbReconciled: 0, kbPagesCleared: 0 }
8168
+ const customerPresent = CUSTOMER_IMPORT_TABLES.some((table) => Array.isArray(tables[table]))
8169
+ if (customerPresent) {
8170
+ report.customer = applyCustomerImport(store, {
8171
+ clients: Array.isArray(tables.clients) ? tables.clients : [],
8172
+ projects: Array.isArray(tables.projects) ? tables.projects : [],
8173
+ client_notes: Array.isArray(tables.client_notes) ? tables.client_notes : [],
8174
+ })
8175
+ report.tables.clients = report.customer.clients
8176
+ report.tables.projects = report.customer.projects
8177
+ report.tables.client_notes = report.customer.clientNotes
8178
+ }
8179
+ const restored = (table) => !CUSTOMER_IMPORT_TABLES.includes(table)
8180
+ for (const table of IMPORT_TABLES) {
8181
+ if (!restored(table)) continue
8182
+ const rows = tables[table]
8183
+ if (rows === null || rows === undefined) continue
8184
+ report.tables[table] = replaceCustomerTable(store, table, rows)
8185
+ }
8186
+ // KB: chunks must point at a restored document; entity ids are reconciled to
8187
+ // NULL (KB is derived data, never a reason to reject the whole import).
8188
+ if (tables.kb_documents !== null || tables.kb_chunks !== null || tables.kb_fact_links !== null) {
8189
+ const docIds = new Set(store.db.prepare('SELECT id FROM kb_documents').all().map((row) => row.id))
8190
+ for (const chunk of store.db.prepare('SELECT id, doc_id FROM kb_chunks').all()) {
8191
+ if (!docIds.has(chunk.doc_id)) throw importDataError('import data.kb_chunks references a missing document: ' + String(chunk.doc_id))
8192
+ }
8193
+ const clientIds = new Set(store.db.prepare('SELECT id FROM clients').all().map((row) => row.id))
8194
+ const projectIds = new Set(store.db.prepare('SELECT id FROM projects').all().map((row) => row.id))
8195
+ const matterIds = new Set(store.db.prepare('SELECT id FROM matters').all().map((row) => row.id))
8196
+ for (const doc of store.db.prepare('SELECT id, client_id, project_id, matter_id FROM kb_documents').all()) {
8197
+ const nextClient = doc.client_id !== null && clientIds.has(doc.client_id) ? doc.client_id : null
8198
+ const nextProject = doc.project_id !== null && projectIds.has(doc.project_id) ? doc.project_id : null
8199
+ const nextMatter = doc.matter_id !== null && matterIds.has(doc.matter_id) ? doc.matter_id : null
8200
+ if (nextClient !== doc.client_id || nextProject !== doc.project_id || nextMatter !== doc.matter_id) {
8201
+ store.db.prepare('UPDATE kb_documents SET client_id = ?, project_id = ?, matter_id = ? WHERE id = ?').run(nextClient, nextProject, nextMatter, doc.id)
8202
+ report.kbReconciled += 1
8203
+ }
8204
+ }
8205
+ for (const link of store.db.prepare('SELECT fact_id, doc_id FROM kb_fact_links').all()) {
8206
+ if (!docIds.has(link.doc_id)) { store.db.prepare('DELETE FROM kb_fact_links WHERE fact_id = ? AND doc_id = ?').run(link.fact_id, link.doc_id); report.kbReconciled += 1 }
8207
+ }
8208
+ report.kbPagesCleared = Number(store.db.prepare('DELETE FROM kb_pages').run().changes ?? 0)
8209
+ try { store.rebuildAllFtsIndexes() } catch {}
8210
+ }
8211
+ // Money: an import must not leave money rows pointing at missing entities.
8212
+ if (tables.receivables !== null || tables.payments !== null) {
8213
+ const commitmentIds = new Set(store.db.prepare('SELECT id FROM commitments').all().map((row) => row.id))
8214
+ const clientIds = new Set(store.db.prepare('SELECT id FROM clients').all().map((row) => row.id))
8215
+ const receivableById = new Map(store.db.prepare('SELECT id, commitment_id, client_id, currency FROM receivables').all().map((row) => [row.id, row]))
8216
+ for (const row of receivableById.values()) {
8217
+ if (!commitmentIds.has(row.commitment_id)) throw importDataError('import data.receivables references a missing commitment: ' + String(row.commitment_id))
8218
+ if (!clientIds.has(row.client_id)) throw importDataError('import data.receivables references a missing client: ' + String(row.client_id))
8219
+ }
8220
+ for (const payment of store.db.prepare('SELECT id, client_id, commitment_id, currency FROM payments').all()) {
8221
+ if (!clientIds.has(payment.client_id)) throw importDataError('import data.payments references a missing client: ' + String(payment.client_id))
8222
+ if (payment.commitment_id !== null && !commitmentIds.has(payment.commitment_id)) throw importDataError('import data.payments references a missing commitment: ' + String(payment.commitment_id))
8223
+ if (payment.commitment_id !== null) {
8224
+ const receivable = [...receivableById.values()].find((row) => row.commitment_id === payment.commitment_id)
8225
+ if (receivable && receivable.currency !== payment.currency) throw importDataError('import data.payments currency does not match its receivable: ' + String(payment.id))
8226
+ }
8227
+ }
8228
+ }
8229
+ return report
8230
+ }
8231
+
6239
8232
  async function importLedger(file, { replace = false } = {}) {
6240
8233
  if (!file) { console.error('usage: advisers import <file> [--replace]'); process.exitCode = 1; return }
6241
8234
  if (!replace) { console.error('import replaces the local ledger; pass --replace to confirm'); process.exitCode = 1; return }
@@ -6269,8 +8262,8 @@ async function importLedger(file, { replace = false } = {}) {
6269
8262
  }
6270
8263
  // Validate the customer-table payload shape BEFORE any write; the restore
6271
8264
  // 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) {
8265
+ let dataImport = null
8266
+ try { dataImport = prepareDataImport(payload?.data) } catch (error) {
6274
8267
  console.error('import failed: ' + error.message)
6275
8268
  process.exitCode = 1
6276
8269
  return
@@ -6285,16 +8278,26 @@ async function importLedger(file, { replace = false } = {}) {
6285
8278
  facts: Array.isArray(data.facts) ? data.facts.length : 0,
6286
8279
  preferences: Array.isArray(data.preferences) ? data.preferences.length : 0,
6287
8280
  }
6288
- if (customerImport) {
6289
- incoming.clients = customerImport.clients.length
6290
- incoming.projects = customerImport.projects.length
6291
- incoming.clientNotes = customerImport.client_notes.length
8281
+ if (dataImport) {
8282
+ // Additive per-table line: the old clients/projects/clientNotes keys stay.
8283
+ for (const table of Object.keys(dataImport)) {
8284
+ const rows = dataImport[table]
8285
+ if (!Array.isArray(rows)) continue
8286
+ incoming[table] = rows.length
8287
+ }
8288
+ incoming.clients = (dataImport.clients ?? []).length
8289
+ incoming.projects = (dataImport.projects ?? []).length
8290
+ incoming.clientNotes = (dataImport.client_notes ?? []).length
6292
8291
  }
6293
8292
  const importBackupFile = mode === 'sqlite' ? join(HOME, 'import-backup-' + Date.now() + '.db') : null
6294
8293
  console.log('! 需要确认:整库替换本地账本(不是合并)')
6295
- console.log(' 写入:' + incoming.matters + ' 个事项 / ' + incoming.commitments + ' 条承诺 / ' + incoming.facts + ' 条事实 / ' + incoming.preferences + ' 条偏好' + (customerImport ? ' / ' + incoming.clients + ' 个客户 / ' + incoming.projects + ' 个项目 / ' + incoming.clientNotes + ' 条客户备注' : ''))
8294
+ console.log(' 写入:' + incoming.matters + ' 个事项 / ' + incoming.commitments + ' 条承诺 / ' + incoming.facts + ' 条事实 / ' + incoming.preferences + ' 条偏好' + (dataImport ? ' / ' + incoming.clients + ' 个客户 / ' + incoming.projects + ' 个项目 / ' + incoming.clientNotes + ' 条客户备注' : ''))
8295
+ if (dataImport) {
8296
+ const summary = Object.keys(dataImport).filter((table) => Array.isArray(dataImport[table])).map((table) => table + '=' + dataImport[table].length).join(', ')
8297
+ console.log(' 导出表:' + summary)
8298
+ }
6296
8299
  console.log(' 备份:' + (importBackupFile ?? '(JSON store:无数据库备份,旧 state.json 会被覆盖)'))
6297
- console.log(' 不可撤销:替换后只能用上面的备份恢复;' + (customerImport ? '客户/项目/备注表按导出恢复,其余 SQLite-only 表不会合并。' : '未导入的 SQLite-only 表不会被保留。'))
8300
+ console.log(' 不可撤销:替换后只能用上面的备份恢复;' + (dataImport ? '导出的 DATA_TABLES 按同一事务恢复(派生 FTS 与 mail_cursors 除外),kb_pages 需重新生成。' : '未导入的 SQLite-only 表不会被保留。'))
6298
8301
  // import replaces the ledger wholesale; serialize it with every other store
6299
8302
  // user (P0-1) before copying the pre-import backup and writing.
6300
8303
  ensureInstanceLock()
@@ -6327,21 +8330,32 @@ async function importLedger(file, { replace = false } = {}) {
6327
8330
  try {
6328
8331
  const ledger = Ledger.fromJSON(data, LOCAL_PORTS)
6329
8332
  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.
8333
+ let dataReport = null
8334
+ if (dataImport && mode === 'sqlite') {
8335
+ // One transaction: the ledger tables (saveWithAudit) and every exported
8336
+ // DATA_TABLES entry (applyDataImport), including their cross-reference
8337
+ // validation. A bad reference throws and rolls the whole replace back; the
8338
+ // pre-import backup remains as a second net.
6335
8339
  openStore().saveWithAudit(ledger.toJSON(), audit, (innerStore) => {
6336
- customerReport = applyCustomerImport(innerStore, customerImport)
8340
+ dataReport = applyDataImport(innerStore, dataImport)
6337
8341
  })
6338
8342
  } else {
6339
8343
  saveLedgerWithAudit(ledger, audit)
6340
8344
  }
6341
8345
  console.log(`imported ${data.matters.length} matters, ${data.commitments?.length ?? 0} commitments`)
6342
- if (customerReport) {
8346
+ if (dataReport?.customer) {
8347
+ const customerReport = dataReport.customer
6343
8348
  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.')
8349
+ }
8350
+ if (dataReport) {
8351
+ const restoredTables = Object.entries(dataReport.tables)
8352
+ .filter(([table]) => !CUSTOMER_IMPORT_TABLES.includes(table))
8353
+ .map(([table, count]) => table + '=' + count)
8354
+ .join(', ')
8355
+ if (restoredTables) console.log('restored tables: ' + restoredTables)
8356
+ if (dataReport.kbReconciled) console.log('kb reconciled rows=' + dataReport.kbReconciled)
8357
+ if (dataReport.kbPagesCleared) console.log('kb_pages cleared=' + dataReport.kbPagesCleared + ' (run advisers kb page rebuild)')
8358
+ console.error('note: ledger + exported DATA_TABLES were replaced (derived FTS tables, mail_cursors and the machine-local audit chain excluded); the local audit chain stays valid.')
6345
8359
  } else if (payload?.data) {
6346
8360
  console.error('note: SQLite-only tables in the import were not merged; ledger was replaced.')
6347
8361
  }
@@ -8087,6 +10101,55 @@ async function ui(args) {
8087
10101
  await app.close()
8088
10102
  }
8089
10103
 
10104
+ let webhookSecretWarned = false
10105
+
10106
+ /** Parse remind --now into a Date (fixed instant for reproducible JSON + planning). */
10107
+ function parseRemindNow(flags) {
10108
+ if (flags.now === undefined) return { date: new Date() }
10109
+ if (typeof flags.now !== 'string' || Number.isNaN(Date.parse(flags.now))) return { error: '--now must be an ISO timestamp' }
10110
+ return { date: new Date(Date.parse(flags.now)) }
10111
+ }
10112
+
10113
+ const QUIET_HOURS_RE = /^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/
10114
+ /** Validate --quiet-hours HH:MM-HH:MM; the value is baked into the scheduler script only. */
10115
+ function parseQuietHours(value) {
10116
+ if (value === undefined) return { value: null }
10117
+ if (typeof value !== 'string' || !QUIET_HOURS_RE.test(value)) return { error: '--quiet-hours must be HH:MM-HH:MM (for example 22:00-08:00)' }
10118
+ return { value: value }
10119
+ }
10120
+
10121
+ const HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/
10122
+ function parseHhmm(value, flag) {
10123
+ if (typeof value !== 'string' || !HHMM_RE.test(value)) return { error: flag + ' must be HH:MM' }
10124
+ const parts = value.split(':').map(Number)
10125
+ return { time: value, hour: parts[0], minute: parts[1] }
10126
+ }
10127
+
10128
+ const MORNING_WINDOWS_DAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']
10129
+ /** Accept a cron day list (1-5, 1,3,5) and derive both cron and schtasks forms. */
10130
+ function parseMorningDays(value) {
10131
+ const text = value === undefined ? '1-5' : String(value).trim()
10132
+ if (!/^[0-7](?:[-,][0-7])*$/.test(text)) return { error: '--morning-days must be a cron day list like 1-5 or 1,3,5' }
10133
+ const numeric = []
10134
+ for (const part of text.split(',')) {
10135
+ if (part.includes('-')) {
10136
+ const bounds = part.split('-').map(Number)
10137
+ const from = Math.min(bounds[0], bounds[1])
10138
+ const to = Math.max(bounds[0], bounds[1])
10139
+ for (let day = from; day <= to; day++) numeric.push(day % 7)
10140
+ } else numeric.push(Number(part) % 7)
10141
+ }
10142
+ const unique = [...new Set(numeric)]
10143
+ if (!unique.length) return { error: '--morning-days must name at least one day' }
10144
+ return { cron: text, windows: unique.map((day) => MORNING_WINDOWS_DAYS[day]) }
10145
+ }
10146
+
10147
+ /** m h * * <days> cron schedule from an HH:MM time. */
10148
+ function cronScheduleFor(timeText, daysCron) {
10149
+ const parts = timeText.split(':').map(Number)
10150
+ return parts[1] + ' ' + parts[0] + ' * * ' + (daysCron ?? '*')
10151
+ }
10152
+
8090
10153
  async function remind(args) {
8091
10154
  const { flags, positional } = parseFlags(args)
8092
10155
  ensureHome()
@@ -8116,39 +10179,95 @@ async function remind(args) {
8116
10179
  mkdirSync(dir, { recursive: true, mode: 0o700 })
8117
10180
  const nodeBin = process.execPath
8118
10181
  const cli = process.argv[1]
8119
- writeFileSync(join(dir, 'remind.sh'), '#!/bin/sh\n"' + nodeBin + '" "' + cli + '" remind --deliver --notify >> "' + join(HOME, 'reminders.log') + '" 2>&1\n', { mode: 0o700 })
8120
- writeFileSync(join(dir, 'remind.ps1'), '& "' + nodeBin + '" "' + cli + '" remind --deliver --notify *>> "' + join(HOME, 'reminders.log') + '"\n', { mode: 0o700 })
8121
- writeFileSync(join(dir, 'README.txt'), 'Install one of these user-level schedules (opt-in):\nLinux: systemd --user timer or cron: 0 9 * * * sh ' + join(dir, 'remind.sh') + '\nWindows: Task Scheduler -> run remind.ps1 daily\nOr import ~/.advisers/reminders.ics into your calendar.\n')
10182
+ const quiet = parseQuietHours(flags['quiet-hours'])
10183
+ if (quiet.error) { usageFail(quiet.error, 'usage: advisers remind install [--apply] [--schedule "0 9 * * *"] [--morning [--morning-time 08:30] [--morning-days 1-5]] [--quiet-hours 22:00-08:00]'); return }
10184
+ const withMorning = flags.morning === true
10185
+ const remindArgs = [...scheduler.DEFAULT_REMIND_ARGS, ...(quiet.value ? ['--quiet-hours', quiet.value] : [])]
10186
+ const remindCommand = scheduler.buildCronCommand({ nodeBin, cliPath: cli, args: remindArgs })
10187
+ writeFileSync(join(dir, 'remind.sh'), '#!/bin/sh\n"' + nodeBin + '" "' + cli + '" ' + remindArgs.join(' ') + ' >> "' + join(HOME, 'reminders.log') + '" 2>&1\n', { mode: 0o700 })
10188
+ writeFileSync(join(dir, 'remind.ps1'), '& "' + nodeBin + '" "' + cli + '" ' + remindArgs.join(' ') + ' *>> "' + join(HOME, 'reminders.log') + '"\n', { mode: 0o700 })
10189
+ let morningCommand
10190
+ let morningPlan = null
10191
+ if (withMorning) {
10192
+ const morningTime = parseHhmm(flags['morning-time'] === undefined ? scheduler.DEFAULT_MORNING_TASK_TIME : flags['morning-time'], '--morning-time')
10193
+ if (morningTime.error) { usageFail(morningTime.error, 'usage: advisers remind install --morning [--morning-time 08:30] [--morning-days 1-5]'); return }
10194
+ const morningDays = parseMorningDays(flags['morning-days'])
10195
+ if (morningDays.error) { usageFail(morningDays.error, 'usage: advisers remind install --morning [--morning-time 08:30] [--morning-days 1-5]'); return }
10196
+ morningCommand = scheduler.buildCronCommand({ nodeBin, cliPath: cli, args: scheduler.DEFAULT_MORNING_ARGS })
10197
+ writeFileSync(join(dir, 'morning.sh'), '#!/bin/sh\n"' + nodeBin + '" "' + cli + '" ' + scheduler.DEFAULT_MORNING_ARGS.join(' ') + ' >> "' + join(HOME, 'morning.log') + '" 2>&1\n', { mode: 0o700 })
10198
+ writeFileSync(join(dir, 'morning.ps1'), '& "' + nodeBin + '" "' + cli + '" ' + scheduler.DEFAULT_MORNING_ARGS.join(' ') + ' *>> "' + join(HOME, 'morning.log') + '"\n', { mode: 0o700 })
10199
+ // The second block is opt-in: without --morning the 0.3.2 single-block
10200
+ // install (and its exact dry-run output) is unchanged.
10201
+ const blocks = process.platform === 'win32'
10202
+ ? [
10203
+ { marker: scheduler.CRON_MARKER, taskName: scheduler.DEFAULT_TASK_NAME, time: typeof flags.time === 'string' ? flags.time : scheduler.DEFAULT_TASK_TIME, schedule: 'daily', command: remindCommand },
10204
+ { marker: scheduler.MORNING_CRON_MARKER, taskName: scheduler.DEFAULT_MORNING_TASK_NAME, time: morningTime.time, schedule: 'weekly', days: morningDays.windows, command: morningCommand },
10205
+ ]
10206
+ : [
10207
+ { marker: scheduler.CRON_MARKER, schedule: typeof flags.schedule === 'string' ? flags.schedule : scheduler.DEFAULT_CRON_SCHEDULE, command: remindCommand },
10208
+ { marker: scheduler.MORNING_CRON_MARKER, schedule: cronScheduleFor(morningTime.time, morningDays.cron), command: morningCommand },
10209
+ ]
10210
+ morningPlan = { blocks, schedule: cronScheduleFor(morningTime.time, morningDays.cron), days: morningDays }
10211
+ }
10212
+ writeFileSync(join(dir, 'README.txt'), 'Install one of these user-level schedules (opt-in):\nLinux: systemd --user timer or cron: 0 9 * * * sh ' + join(dir, 'remind.sh') + '\nWindows: Task Scheduler -> run remind.ps1 daily\n' + (withMorning ? 'Morning brief: register morning.sh/.ps1 for ' + morningPlan.schedule + ' (or point Task Scheduler at morning.ps1).\n' : '') + 'Or import ~/.advisers/reminders.ics into your calendar.\n')
8122
10213
  store?.appendAudit({ actor: 'local', action: 'notify.install', allowed: true, reason: dir })
8123
10214
  console.log('scheduler scripts written: ' + dir)
8124
10215
  console.log('opt-in: import ~/.advisers/reminders.ics, or register remind.sh/.ps1 with your OS scheduler.')
8125
- const command = scheduler.buildCronCommand({ nodeBin, cliPath: cli })
10216
+ if (withMorning) console.log('morning scripts written: ' + join(dir, 'morning.sh') + ' / morning.ps1')
10217
+ const existing = apply ? await readCrontabText() : { ok: false }
10218
+ if (withMorning) {
10219
+ const plan = scheduler.planSchedulerBlocks({
10220
+ platform: process.platform,
10221
+ action: 'install',
10222
+ dryRun: !apply,
10223
+ blocks: morningPlan.blocks,
10224
+ ...(existing.ok ? { existingText: existing.text } : {}),
10225
+ })
10226
+ console.log('schedule: ' + (plan.platform === 'win32' ? scheduler.DEFAULT_TASK_NAME + ' daily ' + scheduler.DEFAULT_TASK_TIME : morningPlan.blocks[0].schedule))
10227
+ console.log('morning schedule: ' + (plan.platform === 'win32' ? scheduler.DEFAULT_MORNING_TASK_NAME + ' weekly ' + morningPlan.blocks[1].time + ' ' + morningPlan.blocks[1].days.join(',') : morningPlan.schedule))
10228
+ console.log('command: ' + remindCommand)
10229
+ console.log('morning command: ' + morningCommand)
10230
+ await applySchedulerPlan(plan, { apply })
10231
+ return
10232
+ }
8126
10233
  const schedule = typeof flags.schedule === 'string' ? flags.schedule : scheduler.DEFAULT_CRON_SCHEDULE
8127
10234
  const time = typeof flags.time === 'string' ? flags.time : scheduler.DEFAULT_TASK_TIME
8128
- const existing = apply ? await readCrontabText() : { ok: false }
10235
+ // Windows Task Scheduler has no cron expression: a user cron schedule is
10236
+ // accepted for compatibility but the task is registered daily at `time`.
10237
+ const winSchedule = process.platform === 'win32' ? 'daily' : schedule
8129
10238
  const plan = scheduler.planScheduler({
8130
10239
  platform: process.platform,
8131
10240
  action: 'install',
8132
10241
  dryRun: !apply,
8133
- command,
8134
- schedule,
10242
+ command: remindCommand,
10243
+ schedule: winSchedule,
8135
10244
  time,
8136
10245
  ...(existing.ok ? { existingText: existing.text } : {}),
8137
10246
  })
8138
10247
  console.log('schedule: ' + (plan.platform === 'win32' ? plan.taskName + ' daily ' + plan.time : plan.schedule))
8139
- console.log('command: ' + command)
10248
+ console.log('command: ' + remindCommand)
8140
10249
  await applySchedulerPlan(plan, { apply })
8141
10250
  return
8142
10251
  }
8143
10252
  if (sub === 'uninstall' || flags.uninstall) {
8144
10253
  const dir = join(HOME, 'scheduler')
8145
10254
  const existing = await readCrontabText()
8146
- const plan = scheduler.planScheduler({
8147
- platform: process.platform,
8148
- action: 'uninstall',
8149
- dryRun: !apply,
8150
- ...(existing.ok ? { existingText: existing.text } : {}),
8151
- })
10255
+ // 0.4.0: remove BOTH owned blocks precisely (remind + morning) and leave
10256
+ // every unmanaged crontab line byte-identical.
10257
+ const plan = process.platform === 'win32'
10258
+ ? scheduler.planSchedulerBlocks({
10259
+ platform: 'win32',
10260
+ action: 'uninstall',
10261
+ dryRun: !apply,
10262
+ blocks: [{ taskName: scheduler.DEFAULT_TASK_NAME }, { taskName: scheduler.DEFAULT_MORNING_TASK_NAME }],
10263
+ })
10264
+ : scheduler.planSchedulerBlocks({
10265
+ platform: process.platform,
10266
+ action: 'uninstall',
10267
+ dryRun: !apply,
10268
+ markers: [scheduler.CRON_MARKER, scheduler.MORNING_CRON_MARKER],
10269
+ ...(existing.ok ? { existingText: existing.text } : {}),
10270
+ })
8152
10271
  await applySchedulerPlan(plan, { apply })
8153
10272
  if (existsSync(dir)) rmSync(dir, { recursive: true, force: true })
8154
10273
  store?.appendAudit({ actor: 'local', action: 'notify.uninstall', allowed: true, reason: dir })
@@ -8159,38 +10278,66 @@ async function remind(args) {
8159
10278
  const dir = join(HOME, 'scheduler')
8160
10279
  console.log('scheduler scripts: ' + (existsSync(dir) ? dir : 'not installed (optional)'))
8161
10280
  console.log('reminder log: ' + join(HOME, 'reminders.log'))
8162
- const status = scheduler.readSchedulerStatus({ homeDir: HOME })
8163
- if (!status.lastRun) console.log('last run: none recorded' + (status.corrupt ? ' (status.json corrupt)' : ''))
8164
- else console.log('last run: ' + status.lastRun + ' · result=' + (status.lastResult ?? '-') + ' · count=' + (status.lastCount ?? '-') + ' · channel=' + (status.lastChannel ?? '-'))
10281
+ // 0.4.0 status v2: two sections (remind + morning). A 0.3.2 flat file is
10282
+ // mapped into the remind section by the library, so old runs still show.
10283
+ const status = scheduler.readSchedulerStatusV2({ homeDir: HOME })
10284
+ const remindStatus = status.remind ?? {}
10285
+ if (!remindStatus.lastRun) console.log('last run: none recorded' + (status.corrupt ? ' (status.json corrupt)' : ''))
10286
+ else console.log('last run: ' + remindStatus.lastRun + ' · result=' + (remindStatus.lastResult ?? '-') + ' · count=' + (remindStatus.lastCount ?? '-') + ' · channel=' + (remindStatus.lastChannel ?? '-'))
10287
+ const morningStatus = status.morning ?? {}
10288
+ if (!morningStatus.lastRun) console.log('morning: none recorded')
10289
+ else console.log('morning: ' + morningStatus.lastRun + ' · result=' + (morningStatus.lastResult ?? '-') + ' · count=' + (morningStatus.lastCount ?? '-') + ' · path=' + (morningStatus.lastPath ?? '-'))
8165
10290
  if (process.platform === 'win32') {
8166
10291
  const plan = scheduler.planWindowsStatus({})
8167
10292
  console.log('os plan: ' + plan.commands.map((entry) => entry.command + ' ' + entry.args.join(' ')).join('; ') + '(运行该命令;exit 0 表示已注册)')
10293
+ const morningPlan = scheduler.planWindowsStatus({ taskName: scheduler.DEFAULT_MORNING_TASK_NAME })
10294
+ console.log('os plan (morning): ' + morningPlan.commands.map((entry) => entry.command + ' ' + entry.args.join(' ')).join('; ') + '(运行该命令;exit 0 表示已注册)')
8168
10295
  } else if (scheduler.CRON_PLATFORMS.includes(process.platform)) {
8169
10296
  const existing = await readCrontabText()
8170
10297
  if (existing.ok) {
8171
10298
  const plan = scheduler.planCronStatus({ existingText: existing.text })
8172
10299
  console.log(plan.installed ? 'os plan: installed (' + plan.schedule + ')' : 'os plan: not installed')
10300
+ const blocks = scheduler.planCronStatusBlocks({ existingText: existing.text, markers: [scheduler.CRON_MARKER, scheduler.MORNING_CRON_MARKER] })
10301
+ const morningEntry = blocks.entries.find((entry) => entry.marker === scheduler.MORNING_CRON_MARKER)
10302
+ console.log(morningEntry && morningEntry.installed ? 'os plan (morning): installed (' + morningEntry.schedule + ')' : 'os plan (morning): not installed')
8173
10303
  } else {
8174
10304
  console.log('os plan: unknown (' + (existing.error ?? 'crontab unavailable') + ')')
10305
+ console.log('os plan (morning): unknown (' + (existing.error ?? 'crontab unavailable') + ')')
8175
10306
  }
8176
10307
  } else {
8177
10308
  console.log('os plan: unsupported platform ' + process.platform)
10309
+ console.log('os plan (morning): unsupported platform ' + process.platform)
8178
10310
  }
8179
10311
  return
8180
10312
  }
8181
10313
  const { buildReminders, toIcs } = await loadRemind()
10314
+ // 0.4.0: --now pins planning and the echoed instant, so a fixed run is
10315
+ // byte-reproducible (the same value is used by reminders/ICS/JSON/webhook).
10316
+ const nowInfo = parseRemindNow(flags)
10317
+ if (nowInfo.error) { usageFail(nowInfo.error, 'usage: advisers remind [--json] [--now ISO] [--ics [path]] [--deliver [--notify]]'); return }
10318
+ const nowDate = nowInfo.date
8182
10319
  // One prefix query instead of getMeta() per commitment (read-only store safe).
8183
10320
  const snoozed = {}
8184
10321
  for (const [key, value] of store?.listMetaByPrefix('snooze:') ?? []) snoozed[key.slice('snooze:'.length)] = value
8185
- const reminders = buildReminders(plannerLedger(), { now: new Date(), snoozedUntil: snoozed })
10322
+ const reminders = buildReminders(plannerLedger(), { now: nowDate, snoozedUntil: snoozed })
8186
10323
  if (flags.ics) {
8187
10324
  const path = typeof flags.ics === 'string' ? flags.ics : (positional[0] || join(HOME, 'reminders.ics'))
8188
- writeFileSync(path, toIcs(reminders, { now: new Date() }), { mode: 0o600 })
10325
+ writeFileSync(path, toIcs(reminders, { now: nowDate }), { mode: 0o600 })
8189
10326
  store?.appendAudit({ actor: 'local', action: 'notify.ics', allowed: true, reason: basename(path) })
8190
10327
  console.log('ics written: ' + path + ' (' + reminders.length + ' events)')
8191
10328
  return
8192
10329
  }
8193
- if (flags.json) { console.log(JSON.stringify({ now: new Date().toISOString(), reminders }, null, 2)); return }
10330
+ if (flags.json) {
10331
+ // 0.4.0 additive read model: ok/command/timezone + per-row urgency. The old
10332
+ // now/reminders keys are unchanged and --json stays a pure read (it wins over
10333
+ // --deliver/--notify exactly as in 0.3.2).
10334
+ const { buildRemindPayload } = await loadUrgency()
10335
+ const records = new Map()
10336
+ for (const commitment of plannerLedger().listCommitments()) records.set(commitment.id, commitment)
10337
+ const payload = buildRemindPayload(reminders, { now: nowDate, timezone: AGENDA_TIMEZONE, records })
10338
+ console.log(JSON.stringify(payload, null, 2))
10339
+ return
10340
+ }
8194
10341
  if (!reminders.length) {
8195
10342
  console.log('现在没有到期的提醒。')
8196
10343
  if (flags.deliver) recordReminderRun(scheduler, { count: 0, channel: 'log' })
@@ -8203,16 +10350,25 @@ async function remind(args) {
8203
10350
  // control characters before appending; otherwise one entry could forge log
8204
10351
  // lines in the user's reminder history.
8205
10352
  const actions = reminders.map((r) => sanitizeConsoleText(r.action, { max: 2000 }))
8206
- const line = new Date().toISOString() + '\t' + reminders.length + '\t' + actions.join(';') + '\n'
10353
+ const line = nowDate.toISOString() + '\t' + reminders.length + '\t' + actions.join(';') + '\n'
8207
10354
  writeFileSync(join(HOME, 'reminders.log'), line, { flag: 'a', mode: 0o600 })
8208
10355
  let channel = 'log'
8209
10356
  if (flags.notify) {
8210
10357
  const notify = await loadNotify()
8211
10358
  const local = await notify.sendNotification({ title: 'Advisers · 到期提醒', body: reminders.length + ' 条承诺到期或即将到期' })
8212
10359
  channel = local.sent ? local.channel : 'log-only'
8213
- const webhook = await notify.sendWebhookNotification(reminders)
8214
- if (webhook.sent) channel = channel === 'log-only' ? 'webhook' : channel + '+webhook'
8215
- else if (webhook.configured) console.error(sanitizeConsoleText('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''), { max: 2000 }))
10360
+ const webhook = await notify.sendWebhookNotification(reminders, { now: nowDate })
10361
+ if (webhook.sent) {
10362
+ channel = channel === 'log-only' ? 'webhook' : channel + '+webhook'
10363
+ // 0.4.0: remember whether the delivery was signed, without changing the
10364
+ // payload bytes. A configured webhook with no secret still sends but says
10365
+ // so exactly once per process (sanitised, no secret material).
10366
+ if (typeof webhook.signing === 'string' && webhook.signing !== '') channel += '+signing:' + webhook.signing
10367
+ if (webhook.warning === 'missing-secret' && !webhookSecretWarned) {
10368
+ webhookSecretWarned = true
10369
+ console.error(sanitizeConsoleText('webhook 已配置但未设置 ADVISERS_NOTIFY_WEBHOOK_SECRET:本次按未签名发送(signing=none);建议设置 secret,否则接收端无法验证请求来源。', { max: 2000 }))
10370
+ }
10371
+ } else if (webhook.configured) { console.error(sanitizeConsoleText('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''), { max: 2000 })) }
8216
10372
  }
8217
10373
  store?.appendAudit({ actor: 'local', action: 'notify.delivered', allowed: true, reason: reminders.length + ' reminders channel=' + channel })
8218
10374
  recordReminderRun(scheduler, { count: reminders.length, channel })
@@ -8246,7 +10402,15 @@ async function readCrontabText() {
8246
10402
  /** Record a successful delivery run in ~/.advisers/scheduler/status.json. */
8247
10403
  function recordReminderRun(scheduler, { count, channel }) {
8248
10404
  try {
8249
- scheduler.recordSchedulerRun({ homeDir: HOME, at: new Date(), result: 'ok', count, channel, dryRun: false })
10405
+ // 0.4.0: once a v2 status document exists (a morning --archive run writes
10406
+ // the morning section), keep writing v2 so the other section survives. A
10407
+ // fresh home keeps the 0.3.2 flat v1 layout for byte-compatible readers.
10408
+ const current = scheduler.readSchedulerStatusV2({ homeDir: HOME })
10409
+ if (current.exists && current.legacy !== true && current.corrupt !== true) {
10410
+ scheduler.recordSchedulerRunV2({ homeDir: HOME, at: new Date(), section: 'remind', result: 'ok', count, channel, dryRun: false })
10411
+ } else {
10412
+ scheduler.recordSchedulerRun({ homeDir: HOME, at: new Date(), result: 'ok', count, channel, dryRun: false })
10413
+ }
8250
10414
  } catch (error) {
8251
10415
  console.error('scheduler status not recorded: ' + error.message)
8252
10416
  }
@@ -8378,7 +10542,7 @@ async function deliver(args) {
8378
10542
  /**
8379
10543
  * `advisers mcp --stdio`: the shipped stdio entry for the MCP server.
8380
10544
  *
8381
- * The protocol surface lives in lib/mcp-server.js (7 tools incl. the pending-only
10545
+ * The protocol surface lives in lib/mcp-server.js (8 tools incl. the pending-only
8382
10546
  * candidate write + read-only pack verification, 4 read-only resources, 1 MiB
8383
10547
  * line cap, -32601/-32602/-32002/-32700). This wiring only supplies process
8384
10548
  * state: the home, the store/ledger, the version and the audit sink. Every
@@ -8405,9 +10569,26 @@ async function mcpServer() {
8405
10569
  return Ledger.fromJSON(store.load(), LOCAL_PORTS)
8406
10570
  }
8407
10571
  const { createMcpServer } = await loadMcpServer()
10572
+ // 0.3.2 P2-1: give the MCP read models the narrow commitment projection so the
10573
+ // first tools/call does not map the whole ledger. Without a SQLite store (JSON
10574
+ // mode) the options stay undefined and the server keeps the legacy path.
10575
+ const narrowCommitments = typeof store?.projectCommitmentReadModel === 'function'
10576
+ ? {
10577
+ loadCommitmentView: (options) => store.read(() => store.projectCommitmentReadModel(options)),
10578
+ loadCommitmentRecords: (ids) => store.read(() => {
10579
+ const byId = new Map()
10580
+ for (const id of ids) {
10581
+ const record = store.getCommitment(id)
10582
+ if (record) byId.set(id, record)
10583
+ }
10584
+ return byId
10585
+ }),
10586
+ }
10587
+ : {}
8408
10588
  const server = createMcpServer({
8409
10589
  store,
8410
10590
  loadLedger: loadLedgerFor,
10591
+ ...narrowCommitments,
8411
10592
  version: VERSION,
8412
10593
  audit: (entry) => store?.appendAudit(entry),
8413
10594
  })
@@ -9030,6 +11211,57 @@ async function normalizeEvidenceSources(result) {
9030
11211
  return result
9031
11212
  }
9032
11213
 
11214
+ /**
11215
+ * Typed evidence lookups injected into lib/evidence.js: the mail body table and
11216
+ * the KB chunk/page tables. The library treats a missing lookup as honest
11217
+ * not_checked/unverifiable (never missing), so a read-only command still works.
11218
+ */
11219
+ async function buildEvidenceLookups(store) {
11220
+ if (!store || typeof store.db?.prepare !== 'function') return undefined
11221
+ const lookups = {}
11222
+ try {
11223
+ const mailStore = await loadMailStore()
11224
+ lookups.mail = (selector) => {
11225
+ const ref = selector?.messageId ?? selector?.ref
11226
+ if (typeof ref !== 'string' || !ref) return null
11227
+ try { return mailStore.getMailMessage(store, ref, { includeBody: true }) } catch { return null }
11228
+ }
11229
+ } catch {}
11230
+ lookups.kbChunk = (selector) => {
11231
+ try {
11232
+ if (typeof selector?.chunkId === 'string' && selector.chunkId) return store.db.prepare('SELECT * FROM kb_chunks WHERE id = ?').get(selector.chunkId) ?? null
11233
+ if (typeof selector?.docId === 'string' && selector.docId && Number.isInteger(selector.chunkIndex)) {
11234
+ return store.db.prepare('SELECT * FROM kb_chunks WHERE doc_id = ? AND seq = ?').get(selector.docId, selector.chunkIndex) ?? null
11235
+ }
11236
+ return null
11237
+ } catch { return null }
11238
+ }
11239
+ lookups.kbPage = (selector) => {
11240
+ try {
11241
+ const id = typeof selector?.pageId === 'string' && selector.pageId
11242
+ ? selector.pageId
11243
+ : typeof selector?.docId === 'string' && selector.docId
11244
+ ? selector.docId
11245
+ : typeof selector?.ref === 'string' ? selector.ref.replace(/^kb_page:/i, '') : ''
11246
+ if (!id) return null
11247
+ return store.db.prepare('SELECT * FROM kb_pages WHERE id = ? AND deleted_at IS NULL').get(id) ?? null
11248
+ } catch { return null }
11249
+ }
11250
+ return lookups
11251
+ }
11252
+
11253
+ /** One human line for a verified evidence entry, rendered by its source type. */
11254
+ function verifiedEvidenceLine(entry) {
11255
+ const quote = String(entry?.quote ?? '').slice(0, 120)
11256
+ const type = String(entry?.type ?? 'unknown')
11257
+ if (type === 'conversation') return ' ' + String(entry.sessionId ?? '') + '#' + String(entry.turnId ?? '') + ' 「' + quote + '」'
11258
+ if (type === 'mail') return ' mail ' + String(entry.messageId ?? entry.ref ?? '') + ' 「' + quote + '」' + (entry.subject ? ' ' + String(entry.subject).slice(0, 80) : '')
11259
+ if (type === 'kb_chunk') return ' kb_chunk ' + String(entry.docId ?? '') + (entry.chunkIndex !== undefined ? '#' + entry.chunkIndex : '') + ' 「' + quote + '」'
11260
+ if (type === 'kb_page') return ' kb_page ' + String(entry.pageId ?? '') + ' 「' + quote + '」'
11261
+ if (type === 'ledger') return ' ledger ' + String(entry.ref ?? '') + ' 「' + quote + '」'
11262
+ return ' ' + type + (entry.ref ? ' ' + String(entry.ref) : '') + ' 「' + quote + '」'
11263
+ }
11264
+
9033
11265
  async function printEvidence(args) {
9034
11266
  const { flags, positional } = parseFlags(args)
9035
11267
  // Offline receipt-pack verification: reads only the given directory. It runs
@@ -9037,6 +11269,23 @@ async function printEvidence(args) {
9037
11269
  if (positional[0] === 'verify') {
9038
11270
  const dir = positional[1] ?? (typeof flags.dir === 'string' ? flags.dir : undefined)
9039
11271
  if (!dir) { console.error('usage: advisers evidence verify <dir>'); process.exitCode = 1; return }
11272
+ // 0.4.0: dispatch by manifest.format. A client status pack is verified by
11273
+ // the client-pack verifier (its own limits/semantics); everything else stays
11274
+ // on the frozen receipt verifier.
11275
+ try {
11276
+ const clientPack = await loadClientPack()
11277
+ const header = clientPack.readClientPackManifestHeader(dir)
11278
+ if (header.ok && header.format === clientPack.CLIENT_PACK_MANIFEST_FORMAT) {
11279
+ const result = clientPack.verifyClientStatusPackDir(dir)
11280
+ console.log(JSON.stringify(result, null, 2))
11281
+ if (result.code === clientPack.CLIENT_PACK_LIMIT_CODE) {
11282
+ const violation = result.limitViolation ?? {}
11283
+ console.error(sanitizeConsoleText(clientPack.CLIENT_PACK_LIMIT_CODE + ': client status pack ' + (violation.limit ?? 'limit') + ' exceeded ' + (violation.max ?? '?') + ' (actual ' + (violation.actual ?? '?') + '); refusing to verify a pack that could exhaust memory or time.', { max: 2000 }))
11284
+ }
11285
+ process.exitCode = result.ok ? 0 : 1
11286
+ return
11287
+ }
11288
+ } catch {}
9040
11289
  const { verifyReceiptPackDir, RECEIPT_LIMIT_CODE } = await loadReceiptVerify()
9041
11290
  // The verifier caps entries/depth/file size/total size/SHA256SUMS/manifest
9042
11291
  // for an untrusted pack (lib/receipt-verify.js). A pack that trips a cap is
@@ -9060,31 +11309,40 @@ async function printEvidence(args) {
9060
11309
  if (!id) { console.error('usage: advisers evidence show <id> [--json]'); process.exitCode = 1; return }
9061
11310
  const ledger = readLedgerForCommand(id.startsWith('fact_') ? { facts: {} } : id.startsWith('pref_') ? { preferences: {} } : { commitments: {} })
9062
11311
  let result
11312
+ const lookups = await buildEvidenceLookups(store)
9063
11313
  try {
9064
11314
  const { evidenceForCommitment, evidenceForFact, evidenceForPreference } = await loadEvidence()
9065
- if (id.startsWith('cm_')) result = evidenceForCommitment(store, ledger, id)
9066
- else if (id.startsWith('fact_')) result = evidenceForFact(store, ledger, id)
9067
- else if (id.startsWith('pref_')) result = evidenceForPreference(store, ledger, id)
11315
+ if (id.startsWith('cm_')) result = evidenceForCommitment(store, ledger, id, undefined, { lookup: lookups })
11316
+ else if (id.startsWith('fact_')) result = evidenceForFact(store, ledger, id, undefined, { lookup: lookups })
11317
+ else if (id.startsWith('pref_')) result = evidenceForPreference(store, ledger, id, undefined, { lookup: lookups })
9068
11318
  else { console.error('unknown evidence id prefix (want cm_/fact_/pref_)'); process.exitCode = 1; return }
9069
11319
  } catch (error) { console.error(error.message); process.exitCode = 1; return }
9070
11320
  if (!result || (!result.commitment && !result.fact && !result.preference)) { console.error(`not found: ${id}`); process.exitCode = 1; return }
9071
11321
  await normalizeEvidenceSources(result)
9072
11322
  const unverifiable = Array.isArray(result.unverifiable) ? result.unverifiable : []
11323
+ const notChecked = Array.isArray(result.notChecked) ? result.notChecked : []
9073
11324
  const manualSources = unverifiable.filter((item) => item && (item.kind === 'manual' || item.type === 'manual'))
11325
+ // 0.4.0: prefer the resolver summary (four-state byKind, notCheckedCount,
11326
+ // verificationBasis); fall back to the 0.3.2 tally for legacy result objects.
9074
11327
  const summary = {
9075
- byKind: { observed: result.sources.length, manual: manualSources.length },
11328
+ byKind: result.byKind && typeof result.byKind === 'object' ? result.byKind : { observed: result.sources.length, manual: manualSources.length },
9076
11329
  missing: result.missing.length,
9077
11330
  unverifiable: unverifiable.length,
9078
11331
  operatorEntered: manualSources.length,
11332
+ notCheckedCount: Number.isInteger(result.notCheckedCount) ? result.notCheckedCount : notChecked.length,
11333
+ verificationBasis: typeof result.verificationBasis === 'string' ? result.verificationBasis : 'build-time',
9079
11334
  }
9080
11335
  if (flags.json) { console.log(JSON.stringify(Object.assign({}, result, { summary: summary }), null, 2)); return }
9081
11336
  const label = result.commitment ? `${result.commitment.action}` : result.fact ? `${result.fact.subject} ${result.fact.predicate}` : result.preference?.statement
9082
11337
  console.log(`${id} ${label ?? ''}`)
9083
- if (!result.sources.length && !unverifiable.length) console.log(' (没有可回溯来源)')
9084
- for (const s of result.sources) console.log(` ${s.sessionId}#${s.turnId} 「${(s.quote ?? '').slice(0, 120)}」`)
11338
+ if (!result.sources.length && !unverifiable.length && !notChecked.length) console.log(' (没有可回溯来源)')
11339
+ for (const s of result.sources) console.log(verifiedEvidenceLine(s))
9085
11340
  for (const m of result.missing) console.log(` MISSING ${m.reason}${m.ref ? ` ${m.ref}` : ''}`)
11341
+ for (const item of notChecked) console.log(` NOT CHECKED ${String(item.type ?? 'unknown')} ${String(item.reason ?? 'not_checked')}${item.ref ? ' ' + String(item.ref) : ''}`)
9086
11342
  for (const item of unverifiable) console.log(` MANUAL 操作者录入(未外部核验,不是缺失) 「${(item.quote ?? '').slice(0, 120)}」 sha256:${String(item.quoteSha256 ?? '').slice(0, 16)}`)
9087
11343
  if (unverifiable.length) console.log(' 说明:manual/operator-entered 证据由用户手工录入;本地无法外部核验,不计入 missing。')
11344
+ if (notChecked.length) console.log(' 说明:not-checked 指本地没有对应的类型化查找能力/记录(如邮件正文未留存);它既不是 resolved,也不是 missing。')
11345
+ console.log(' 校验口径:' + summary.verificationBasis + '——本地解析只证明构建时状态,不代表第三方审计或不可伪造。')
9088
11346
  }
9089
11347
 
9090
11348
  /**
@@ -9131,6 +11389,7 @@ async function evidencePack(args) {
9131
11389
  preferences: ledger.listPreferences({ includeCandidates: false }).map((p) => p.id),
9132
11390
  }
9133
11391
  const { buildEvidencePack, toDocxRows, verifyPack, EvidencePackLimitError } = await loadEvidence()
11392
+ const lookups = await buildEvidenceLookups(store)
9134
11393
  let pack
9135
11394
  try {
9136
11395
  // Performance audit P1-1: --all was parsed but never forwarded, so the
@@ -9145,6 +11404,7 @@ async function evidencePack(args) {
9145
11404
  all: flags.all === true,
9146
11405
  clearance: 0,
9147
11406
  protectedPolicy: ids ? 'error' : 'exclude',
11407
+ lookups,
9148
11408
  })
9149
11409
  } catch (error) {
9150
11410
  if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
@@ -9263,6 +11523,189 @@ async function verifyDeliveryArtifacts(files) {
9263
11523
  * --ids narrows/extends it). The old evidence-only path stays on
9264
11524
  * `deliveries --pack`.
9265
11525
  */
11526
+ /**
11527
+ * Resolve the optional client/project scope of `deliveries --receipt`.
11528
+ * Returns null when the pack is unscoped (historical local-all behaviour).
11529
+ * Every lookup fails closed: an unknown id is E_CLIENT_NOT_FOUND /
11530
+ * E_PROJECT_NOT_FOUND, and a project that belongs to another client is
11531
+ * E_PROJECT_CLIENT_MISMATCH (the same codes as the client commands).
11532
+ */
11533
+ function receiptSubjectOf(store, flags) {
11534
+ if (flags.client === true || flags.project === true) {
11535
+ throw customerError('E_USAGE', '--client/--project require an id', 'advisers deliveries --receipt --client <client-id>')
11536
+ }
11537
+ const clientId = typeof flags.client === 'string' ? flags.client.trim() : ''
11538
+ const projectId = typeof flags.project === 'string' ? flags.project.trim() : ''
11539
+ if (!clientId && !projectId) return null
11540
+ let project = null
11541
+ if (projectId) {
11542
+ project = store.getProject(projectId)
11543
+ if (!project) throw customerError('E_PROJECT_NOT_FOUND', 'unknown project: ' + projectId, 'advisers project list')
11544
+ }
11545
+ const resolvedClientId = clientId || project.clientId
11546
+ const client = store.getClient(resolvedClientId)
11547
+ if (!client) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + resolvedClientId, 'advisers client list')
11548
+ if (project && project.clientId !== client.id) {
11549
+ throw customerError('E_PROJECT_CLIENT_MISMATCH', 'project ' + project.id + ' belongs to client ' + project.clientId, 'advisers project list --client ' + client.id)
11550
+ }
11551
+ const matters = project ? store.listMattersByProject(project.id) : store.listMattersByClient(client.id)
11552
+ return {
11553
+ kind: project ? 'project' : 'client',
11554
+ id: project ? project.id : client.id,
11555
+ name: project ? project.name : client.name,
11556
+ client: client,
11557
+ project: project,
11558
+ matterIds: matters.map((matter) => matter.id),
11559
+ matterIdSet: new Set(matters.map((matter) => matter.id)),
11560
+ }
11561
+ }
11562
+
11563
+ /**
11564
+ * Effective secrecy of one delivery row: max(client.secrecyDefault, matter
11565
+ * secrecy). A row with an unresolvable matter is treated as protected
11566
+ * (Infinity), never guessed. This is the 0.3.2 receipt rule for local-all
11567
+ * packs too: a client marked secret cannot leak through a receipt.
11568
+ */
11569
+ function receiptRowSecrecy(store, ledger, row, clientById) {
11570
+ let level = itemMatterSecrecy(ledger, row.matterId)
11571
+ let clientId = row.clientId || null
11572
+ if (!clientId && row.matterId) {
11573
+ try { clientId = ledger.getMatter(row.matterId)?.clientId ?? null } catch { clientId = null }
11574
+ }
11575
+ if (clientId) {
11576
+ let client = clientById.get(clientId)
11577
+ if (client === undefined) {
11578
+ try { client = store.getClient(clientId) ?? null } catch { client = null }
11579
+ clientById.set(clientId, client)
11580
+ }
11581
+ if (client) level = Math.max(level, Number(client.secrecyDefault) || 0)
11582
+ }
11583
+ return level
11584
+ }
11585
+
11586
+ /**
11587
+ * Evidence ids for one receipt subject: only the subject's matters.
11588
+ * Global facts/preferences (no matter association) are excluded unless
11589
+ * --include-global is explicit; the count of excluded global rows is reported
11590
+ * without their content.
11591
+ */
11592
+ function receiptEvidenceIds(ledger, subject, includeGlobal) {
11593
+ const ids = { commitments: [], facts: [], preferences: [] }
11594
+ let excludedGlobal = 0
11595
+ for (const row of ledger.listCommitments()) {
11596
+ if (!subject.matterIdSet.has(row.matterId)) continue
11597
+ if (itemMatterSecrecy(ledger, row.matterId) > 0) continue
11598
+ ids.commitments.push(row.id)
11599
+ }
11600
+ for (const row of ledger.listFacts()) {
11601
+ const matterId = typeof row.matterId === 'string' ? row.matterId : ''
11602
+ if (matterId) {
11603
+ if (!subject.matterIdSet.has(matterId)) continue
11604
+ if (itemMatterSecrecy(ledger, matterId) > 0) continue
11605
+ } else if (!includeGlobal) {
11606
+ excludedGlobal += 1
11607
+ continue
11608
+ }
11609
+ ids.facts.push(row.id)
11610
+ }
11611
+ for (const row of ledger.listPreferences({ includeCandidates: false })) {
11612
+ const scope = row && row.scope
11613
+ const matterId = scope && scope.level === 'matter' && typeof scope.value === 'string' ? scope.value : ''
11614
+ if (matterId) {
11615
+ if (!subject.matterIdSet.has(matterId)) continue
11616
+ if (itemMatterSecrecy(ledger, matterId) > 0) continue
11617
+ } else if (!includeGlobal) {
11618
+ excludedGlobal += 1
11619
+ continue
11620
+ }
11621
+ ids.preferences.push(row.id)
11622
+ }
11623
+ return { ids: ids, excludedGlobal: excludedGlobal }
11624
+ }
11625
+
11626
+ /** Matter id of one evidence record ('' for a global record). */
11627
+ function receiptEvidenceMatterId(record, kind) {
11628
+ if (!record || typeof record !== 'object') return ''
11629
+ if (kind === 'preference') {
11630
+ const scope = record.scope
11631
+ return scope && scope.level === 'matter' && typeof scope.value === 'string' ? scope.value : ''
11632
+ }
11633
+ return typeof record.matterId === 'string' ? record.matterId : ''
11634
+ }
11635
+
11636
+ /** Effective secrecy of one evidence record: max(client default, matter secrecy). */
11637
+ function receiptEvidenceRecordSecrecy(store, ledger, record, kind, clientById) {
11638
+ const matterId = receiptEvidenceMatterId(record, kind)
11639
+ if (!matterId) return 0
11640
+ let level = itemMatterSecrecy(ledger, matterId)
11641
+ let clientId = null
11642
+ try { clientId = ledger.getMatter(matterId)?.clientId ?? null } catch { clientId = null }
11643
+ if (clientId) {
11644
+ let client = clientById.get(clientId)
11645
+ if (client === undefined) {
11646
+ try { client = store.getClient(clientId) ?? null } catch { client = null }
11647
+ clientById.set(clientId, client)
11648
+ }
11649
+ if (client) level = Math.max(level, Number(client.secrecyDefault) || 0)
11650
+ }
11651
+ return level
11652
+ }
11653
+
11654
+ /**
11655
+ * Local-all receipt evidence: the same client-level secrecy rule as the
11656
+ * delivery rows, so a client marked secret cannot leak through the evidence
11657
+ * section while its deliveries are correctly excluded.
11658
+ */
11659
+ function receiptGlobalEvidenceIds(store, ledger, clientById) {
11660
+ const ids = { commitments: [], facts: [], preferences: [] }
11661
+ // Matter-level secrecy stays with buildEvidencePack (it counts those rows as
11662
+ // evidence.protectedExcluded, the historical A-1 behaviour). Only a
11663
+ // client-level default above 0 is pre-filtered here, because the evidence
11664
+ // builder cannot see client rows; those are reported separately so the two
11665
+ // counts never double-count.
11666
+ const keep = (row, kind, into) => {
11667
+ const matterId = receiptEvidenceMatterId(row, kind)
11668
+ const matterLevel = matterId ? itemMatterSecrecy(ledger, matterId) : 0
11669
+ if (matterLevel > 0) { into.push(row.id); return }
11670
+ if (matterId && receiptEvidenceRecordSecrecy(store, ledger, row, kind, clientById) > 0) {
11671
+ protectedExcluded += 1
11672
+ return
11673
+ }
11674
+ into.push(row.id)
11675
+ }
11676
+ let protectedExcluded = 0
11677
+ for (const row of ledger.listCommitments()) keep(row, 'commitment', ids.commitments)
11678
+ for (const row of ledger.listFacts()) keep(row, 'fact', ids.facts)
11679
+ for (const row of ledger.listPreferences({ includeCandidates: false })) keep(row, 'preference', ids.preferences)
11680
+ return { ids: ids, protectedExcluded: protectedExcluded }
11681
+ }
11682
+
11683
+ /** Explicit --ids on a local-all receipt: fail closed when any id is protected. */
11684
+ function receiptExplicitEvidenceProtected(store, ledger, ids, clientById) {
11685
+ const records = new Map()
11686
+ for (const row of ledger.listCommitments()) records.set(row.id, { kind: 'commitment', record: row })
11687
+ for (const row of ledger.listFacts()) records.set(row.id, { kind: 'fact', record: row })
11688
+ for (const row of ledger.listPreferences({ includeCandidates: false })) records.set(row.id, { kind: 'preference', record: row })
11689
+ let protectedCount = 0
11690
+ for (const id of ids) {
11691
+ const found = records.get(id)
11692
+ if (!found) continue
11693
+ if (receiptEvidenceRecordSecrecy(store, ledger, found.record, found.kind, clientById) > 0) protectedCount += 1
11694
+ }
11695
+ return protectedCount
11696
+ }
11697
+
11698
+ /**
11699
+ * `advisers deliveries --receipt`: build a delivery receipt pack.
11700
+ *
11701
+ * 0.3.2: the pack can be scoped to one client or project. A subject pack only
11702
+ * copies that subject's delivered artifacts and evidence (global facts and
11703
+ * preferences need --include-global), records `subject`/`scope` in the v2
11704
+ * manifest, and states in README.txt/receipt.docx that it contains one
11705
+ * subject's data. The unscoped historical form remains, but is now labelled
11706
+ * scope=local-all: it contains every local customer's data and must not be
11707
+ * forwarded to a third party.
11708
+ */
9266
11709
  async function receiptPack(args) {
9267
11710
  const { flags } = parseFlags(args)
9268
11711
  ensureHome()
@@ -9271,25 +11714,73 @@ async function receiptPack(args) {
9271
11714
  const ledger = loadLedger()
9272
11715
  const denied = egressDeniedReason(ledger.getMatter(activeMatterId(ledger)), 'evidence')
9273
11716
  if (denied) { console.error(denied); process.exitCode = 1; return }
11717
+ if ((flags.client !== undefined || flags.project !== undefined) && flags.ids !== undefined) {
11718
+ console.error('E_USAGE: --ids cannot be combined with --client/--project (a subject pack derives its evidence scope from the subject)')
11719
+ process.exitCode = 1
11720
+ return
11721
+ }
9274
11722
  const ids = typeof flags.ids === 'string' ? flags.ids.split(',').map((item) => item.trim()).filter(Boolean) : undefined
9275
11723
  if (ids && !ids.length) { console.error('--ids is empty'); process.exitCode = 1; return }
9276
11724
  const deliveryLimit = Math.max(1, Math.min(2000, Number(flags.limit) || 100))
11725
+ let subject = null
11726
+ try {
11727
+ subject = receiptSubjectOf(store, flags)
11728
+ } catch (error) {
11729
+ console.error('error: ' + String(error?.message ?? error))
11730
+ if (error?.hint) console.error('hint: ' + error.hint)
11731
+ process.exitCode = 1
11732
+ return
11733
+ }
11734
+ // A receipt pack is generated at clearance 0 and is meant to leave the
11735
+ // machine; a client whose default secrecy is above 0 fails closed instead of
11736
+ // producing an empty pack that looks successful.
11737
+ if (subject && Number(subject.client?.secrecyDefault) > 0) {
11738
+ console.error('E_SECRECY_BLOCKED: client ' + subject.client.id + ' has secrecyDefault ' + subject.client.secrecyDefault + ', but a receipt pack is generated at clearance 0')
11739
+ console.error('hint: lower the client secrecy (advisers client ...), or use a local export instead of a shareable receipt')
11740
+ process.exitCode = 1
11741
+ return
11742
+ }
11743
+ // 0.3.2: how many scoped deliveries exist before the readable/limit filters,
11744
+ // so a bounded pack is never mistaken for the whole set (the default limit is
11745
+ // 100, max 2000, and older receipt packs are excluded).
11746
+ let deliveriesTotal = null
11747
+ try {
11748
+ deliveriesTotal = subject
11749
+ ? store.countDeliveriesForScope({
11750
+ clientId: subject.kind === 'client' ? subject.client.id : null,
11751
+ projectId: subject.kind === 'project' ? subject.project.id : null,
11752
+ matterIds: subject.matterIds,
11753
+ })
11754
+ : store.db.prepare("SELECT COUNT(*) AS n FROM deliveries WHERE COALESCE(tool, '') != 'receipt-pack'").get().n
11755
+ } catch { deliveriesTotal = null }
11756
+ const rows = subject
11757
+ ? store.listDeliveriesForScope({
11758
+ clientId: subject.kind === 'client' ? subject.client.id : null,
11759
+ projectId: subject.kind === 'project' ? subject.project.id : null,
11760
+ matterIds: subject.matterIds,
11761
+ limit: deliveryLimit,
11762
+ })
11763
+ : store.listDeliveries(deliveryLimit)
9277
11764
  // A receipt pack records itself as a delivery for discoverability, but a new
9278
11765
  // receipt must not recursively copy older receipt packs (unbounded growth).
9279
- const rows = store.listDeliveries(deliveryLimit).filter((row) => row.tool !== 'receipt-pack')
9280
- if (!rows.length) {
9281
- console.error('没有交付记录可生成回执包;先运行 `advisers deliver` / `advisers office` / `advisers template`。')
11766
+ const scopedRows = rows.filter((row) => row.tool !== 'receipt-pack')
11767
+ const deliveriesTruncated = Number.isInteger(deliveriesTotal) ? deliveriesTotal > scopedRows.length : false
11768
+ if (!scopedRows.length) {
11769
+ console.error(subject
11770
+ ? '没有该' + (subject.kind === 'client' ? '客户' : '项目') + '的交付记录可生成回执包;先运行 `advisers deliver` / `advisers office` / `advisers template`。'
11771
+ : '没有交付记录可生成回执包;先运行 `advisers deliver` / `advisers office` / `advisers template`。')
9282
11772
  process.exitCode = 1
9283
11773
  return
9284
11774
  }
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.
11775
+ // A receipt may span many matters. A row from a protected matter (or from a
11776
+ // client with a protected default) is never copied/read; only a count is
11777
+ // reported. Receipts have no per-delivery explicit selection (--ids names
11778
+ // evidence ids), so this path is exclude-only.
11779
+ const clientSecrecyCache = new Map()
9289
11780
  const visibleRows = []
9290
11781
  let protectedDeliveries = 0
9291
- for (const row of rows) {
9292
- if (itemMatterSecrecy(ledger, row.matterId) > 0) {
11782
+ for (const row of scopedRows) {
11783
+ if (receiptRowSecrecy(store, ledger, row, clientSecrecyCache) > 0) {
9293
11784
  protectedDeliveries += 1
9294
11785
  continue
9295
11786
  }
@@ -9312,38 +11803,75 @@ async function receiptPack(args) {
9312
11803
  tool: row.tool ?? null,
9313
11804
  createdAt: row.createdAt ?? null,
9314
11805
  validation: row.validation ?? null,
9315
- files,
11806
+ files: files,
11807
+ matterId: row.matterId ?? undefined,
11808
+ clientId: row.clientId ?? undefined,
11809
+ projectId: row.projectId ?? undefined,
11810
+ templateName: row.templateName ?? undefined,
11811
+ templateVersion: row.templateVersion ?? undefined,
11812
+ quoteNo: row.quoteNo ?? undefined,
11813
+ dataSha256: row.dataSha256 ?? undefined,
9316
11814
  })
9317
11815
  }
9318
11816
  if (!deliveries.length) {
9319
11817
  if (skippedFiles.length) console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
9320
- if (protectedDeliveries) console.error(`另有 ${protectedDeliveries} 条交付记录属于受保护事项(secrecy>0),已排除。`)
11818
+ if (protectedDeliveries) console.error('另有 ' + protectedDeliveries + ' 条交付记录属于受保护事项或受保护客户(secrecy>0),已排除。')
9321
11819
  else if (!skippedFiles.length) console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
9322
11820
  if (skippedFiles.length) console.error('缺失:' + skippedFiles.slice(0, 5).join('; '))
9323
11821
  process.exitCode = 1
9324
11822
  return
9325
11823
  }
9326
11824
  if (skippedFiles.length) console.error('注意:' + skippedFiles.length + ' 个交付文件缺失,已跳过(回执只覆盖仍存在的文件)。')
9327
-
9328
11825
  const verifyResults = await verifyDeliveryArtifacts(deliveries.flatMap((delivery) => delivery.files))
9329
11826
  const { buildEvidencePack, buildReceiptPack, EvidencePackLimitError } = await loadEvidence()
11827
+ const lookups = await buildEvidenceLookups(store)
9330
11828
  let evidence
11829
+ let evidenceGlobalExcluded = 0
11830
+ let evidenceClientDefaultExcluded = 0
9331
11831
  try {
9332
- const targetIds = ids ?? {
9333
- commitments: ledger.listCommitments().map((row) => row.id),
9334
- facts: ledger.listFacts().map((row) => row.id),
9335
- preferences: ledger.listPreferences({ includeCandidates: false }).map((row) => row.id),
9336
- }
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
- })
11832
+ if (subject) {
11833
+ const scoped = receiptEvidenceIds(ledger, subject, flags['include-global'] === true)
11834
+ evidenceGlobalExcluded = scoped.excludedGlobal
11835
+ evidence = buildEvidencePack({
11836
+ store: store,
11837
+ ledger: ledger,
11838
+ ids: scoped.ids,
11839
+ all: flags.all === true,
11840
+ clearance: 0,
11841
+ protectedPolicy: 'error',
11842
+ lookups,
11843
+ })
11844
+ } else {
11845
+ // A-1 (0.2.5) + 0.3.2: per-item clearance is max(client default, matter
11846
+ // secrecy) for the evidence section too, so the local-all pack cannot
11847
+ // leak a client-protected record while its deliveries are excluded.
11848
+ let targetIds
11849
+ if (ids) {
11850
+ const protectedCount = receiptExplicitEvidenceProtected(store, ledger, ids, clientSecrecyCache)
11851
+ if (protectedCount > 0) {
11852
+ console.error('E_SECRECY_BLOCKED: refusing to export ' + protectedCount + ' evidence item(s) selected by --ids: their matter or client secrecy is above the receipt clearance 0')
11853
+ console.error('hint: remove those ids from --ids; protected records are never partially exported')
11854
+ process.exitCode = 1
11855
+ return
11856
+ }
11857
+ targetIds = ids
11858
+ } else {
11859
+ const scoped = receiptGlobalEvidenceIds(store, ledger, clientSecrecyCache)
11860
+ targetIds = scoped.ids
11861
+ evidenceClientDefaultExcluded = scoped.protectedExcluded
11862
+ }
11863
+ evidence = buildEvidencePack({
11864
+ store: store,
11865
+ ledger: ledger,
11866
+ ids: targetIds,
11867
+ all: flags.all === true,
11868
+ clearance: 0,
11869
+ // Explicit --ids fail closed (A-1); the bulk path excludes protected
11870
+ // rows and reports them through evidence.protectedExcluded.
11871
+ protectedPolicy: ids ? 'error' : 'exclude',
11872
+ lookups,
11873
+ })
11874
+ }
9347
11875
  } catch (error) {
9348
11876
  if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
9349
11877
  console.error('error: ' + error.message)
@@ -9357,24 +11885,26 @@ async function receiptPack(args) {
9357
11885
  const out = typeof flags.out === 'string'
9358
11886
  ? flags.out
9359
11887
  : join(HOME, 'receipts', 'receipt-' + new Date().toISOString().replace(/[:.]/g, '-'))
9360
- // Generate receipt.docx with the office DOCX submodule when available (fast,
9361
- // nicer table) or the built-in deterministic writer otherwise.
9362
11888
  const docxModule = await importOfficeSubmodule('docx')
9363
11889
  const docxBuilder = typeof docxModule?.buildDocx === 'function'
9364
11890
  ? async (spec) => docxModule.buildDocx(spec)
9365
11891
  : false
11892
+ const scope = subject ? 'subject' : 'local-all'
11893
+ const command = 'advisers deliveries --receipt' + (subject ? ' --' + subject.kind + ' ' + subject.id : '')
9366
11894
  let pack
9367
11895
  try {
9368
11896
  pack = await buildReceiptPack({
9369
- deliveries,
9370
- evidence,
9371
- verifyResults,
9372
- docxBuilder,
11897
+ deliveries: deliveries,
11898
+ subject: subject ? { kind: subject.kind, id: subject.id, name: subject.name } : undefined,
11899
+ scope: scope,
11900
+ evidence: evidence,
11901
+ verifyResults: verifyResults,
11902
+ docxBuilder: docxBuilder,
9373
11903
  env: {
9374
11904
  advisersVersion: VERSION,
9375
11905
  nodeVersion: process.version,
9376
11906
  platform: process.platform,
9377
- command: 'advisers deliveries --receipt',
11907
+ command: command,
9378
11908
  },
9379
11909
  recipient: parseReceiptRecipient(flags.recipient),
9380
11910
  anchors: [],
@@ -9388,13 +11918,13 @@ async function receiptPack(args) {
9388
11918
  }
9389
11919
  const summary = pack.summary
9390
11920
  const evidenceProtectedExcluded = Number.isInteger(evidence?.summary?.protectedExcluded) ? evidence.summary.protectedExcluded : 0
9391
- const protectedExcluded = protectedDeliveries + evidenceProtectedExcluded
11921
+ const protectedExcluded = protectedDeliveries + evidenceProtectedExcluded + evidenceClientDefaultExcluded
9392
11922
  try {
9393
11923
  recordDeliveryWithAudit({
9394
11924
  files: [join(summary.outDir, 'manifest.json'), join(summary.outDir, 'README.txt'), join(summary.outDir, 'SHA256SUMS'), join(summary.outDir, 'receipt.docx')],
9395
11925
  tool: 'receipt-pack',
9396
- title: 'delivery receipt pack',
9397
- validation: 'receipt-pack-v1.1: ' + summary.verifyStatus,
11926
+ title: subject ? 'delivery receipt pack (' + subject.kind + ' ' + subject.id + ')' : 'delivery receipt pack',
11927
+ validation: 'receipt-pack-v2: ' + summary.verifyStatus,
9398
11928
  audit: {
9399
11929
  actor: 'local',
9400
11930
  action: 'receipt.pack',
@@ -9404,6 +11934,7 @@ async function receiptPack(args) {
9404
11934
  ' deliveries/' +
9405
11935
  summary.fileCount +
9406
11936
  ' files' +
11937
+ (subject ? ', scope=' + subject.kind + ':' + subject.id : ', scope=local-all') +
9407
11938
  (protectedDeliveries ? ', ' + protectedDeliveries + ' protected deliveries excluded' : '') +
9408
11939
  (evidenceProtectedExcluded ? ', ' + evidenceProtectedExcluded + ' protected evidence excluded' : ''),
9409
11940
  },
@@ -9412,13 +11943,17 @@ async function receiptPack(args) {
9412
11943
  const { verifyReceiptPackDir, RECEIPT_LIMIT_CODE } = await loadReceiptVerify()
9413
11944
  const verification = verifyReceiptPackDir(summary.outDir)
9414
11945
  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 }))
9415
- console.log(JSON.stringify({
11946
+ const payload = {
9416
11947
  ok: verification.ok,
9417
11948
  format: summary.format,
9418
11949
  version: summary.version,
11950
+ scope: scope,
11951
+ subject: subject ? { kind: subject.kind, id: subject.id, name: subject.name } : null,
9419
11952
  out: summary.outDir,
9420
11953
  replaced: summary.replaced ?? null,
9421
11954
  deliveryCount: summary.deliveryCount,
11955
+ deliveriesTotal: deliveriesTotal,
11956
+ deliveriesTruncated: deliveriesTruncated,
9422
11957
  fileCount: summary.fileCount,
9423
11958
  verifyStatus: summary.verifyStatus,
9424
11959
  anchored: summary.anchored,
@@ -9427,21 +11962,23 @@ async function receiptPack(args) {
9427
11962
  receiptSha256: summary.receiptSha256,
9428
11963
  evidence: summary.evidence,
9429
11964
  clearance: 0,
9430
- protectedExcluded,
11965
+ protectedExcluded: protectedExcluded,
9431
11966
  deliveriesProtectedExcluded: protectedDeliveries,
9432
- evidenceProtectedExcluded,
9433
- files: summary.files,
9434
- skippedFiles,
9435
- verification: {
9436
- ok: verification.ok,
9437
- errors: verification.errors,
9438
- warnings: verification.warnings,
9439
- checksumCount: verification.checksumCount,
9440
- },
9441
- }, null, 2))
11967
+ evidenceProtectedExcluded: evidenceProtectedExcluded,
11968
+ }
11969
+ if (subject) payload.evidenceGlobalExcluded = evidenceGlobalExcluded
11970
+ if (evidenceClientDefaultExcluded > 0) payload.evidenceClientDefaultExcluded = evidenceClientDefaultExcluded
11971
+ payload.files = summary.files
11972
+ payload.skippedFiles = skippedFiles
11973
+ payload.verification = {
11974
+ ok: verification.ok,
11975
+ errors: verification.errors,
11976
+ warnings: verification.warnings,
11977
+ checksumCount: verification.checksumCount,
11978
+ }
11979
+ console.log(JSON.stringify(payload, null, 2))
9442
11980
  if (!verification.ok) process.exitCode = 1
9443
11981
  }
9444
-
9445
11982
  function link(sub, from, to, type) {
9446
11983
  const ledger = loadLedger()
9447
11984
  if (sub === 'ls' || !sub) {
@@ -9948,6 +12485,9 @@ const KNOWN_COMMANDS = new Set([
9948
12485
  'forget', 'sync', 'vault', 'export', 'import', 'backup', 'backups', 'restore', 'brief', 'review', 'research', 'capture', 'policy',
9949
12486
  'office-edit', 'office-read', 'verify', 'office', 'routine', 'template', 'link', 'bridge', 'soul', 'tos',
9950
12487
  'matter', 'agenda', 'morning',
12488
+ // 0.4.0: KB / mail / money / consent commands are gated like every other
12489
+ // command (unknown names keep the plain error instead of the gate).
12490
+ 'kb', 'fact', 'mail', 'receivable', 'payment', 'consent',
9951
12491
  // 0.3.0 customer entities: reads and writes both go through the L1/TOS gate
9952
12492
  // (they touch the local ledger); there is no exempt customer command.
9953
12493
  'client', 'project',
@@ -10263,8 +12803,22 @@ async function tosCommand(argv) {
10263
12803
  await tosGate()
10264
12804
 
10265
12805
  if (!command) {
10266
- if (process.stdin.isTTY) await repl()
10267
- else help()
12806
+ // 0.4.0: a TTY with no command enters the readline shell (lib/shell.js);
12807
+ // stdin not a TTY keeps the frozen 0.3.x "print help, exit 0" path.
12808
+ if (process.stdin.isTTY) {
12809
+ const shellResult = await runShellEntry()
12810
+ if (shellResult.entered) {
12811
+ process.exitCode = shellResult.exitCode
12812
+ } else if (shellResult.reason === 'json-unsupported') {
12813
+ console.error('advisers: E_USAGE: --json is not supported by the interactive shell; use `advisers tui --once --json` or a CLI command with --json.')
12814
+ process.exitCode = 1
12815
+ } else {
12816
+ // ADVISERS_NO_SHELL=1 (or an unusable stream pair) keeps the old REPL.
12817
+ await repl()
12818
+ }
12819
+ } else {
12820
+ help()
12821
+ }
10268
12822
  } else if (command === 'version' || command === '--version' || command === '-v') {
10269
12823
  console.log(VERSION)
10270
12824
  } else if (command === 'help' || command === '--help') {
@@ -10528,13 +13082,18 @@ if (!command) {
10528
13082
  else { store.upsertSessionSummary({ conversationId, summary: old.summary, throughSeq: old.throughSeq, pins: old.pins }); console.log(`restored summary v${version}`) }
10529
13083
  } else { console.error('usage: advisers compact ls|rollback <version>'); process.exitCode = 1 }
10530
13084
  } else if (command === 'search') {
10531
- const q = args.join(' ').trim()
10532
- if (!q) { console.error('usage: advisers search <text>'); process.exitCode = 1 }
13085
+ // 0.4.0 additive routing: --scope turns|kb|pages|facts|all. Without --scope
13086
+ // the 0.3.2 bytes are unchanged (turn search, human lines).
13087
+ if (args.includes('--scope')) await scopedSearch(args)
10533
13088
  else {
10534
- // 0.2.3: turn search is a pure read (lock-free; reads the WAL snapshot).
10535
- const rows = readStoreOrExit()?.searchTurns(q, { limit: 10 }) ?? []
10536
- if (!rows.length) console.log('没有匹配')
10537
- for (const r of rows) console.log(`${r.seq}\t${r.role}\t${r.content.replace(/\s+/g, ' ').slice(0, 160)}`)
13089
+ const q = args.join(' ').trim()
13090
+ if (!q) { console.error('usage: advisers search <text>'); process.exitCode = 1 }
13091
+ else {
13092
+ // 0.2.3: turn search is a pure read (lock-free; reads the WAL snapshot).
13093
+ const rows = readStoreOrExit()?.searchTurns(q, { limit: 10 }) ?? []
13094
+ if (!rows.length) console.log('没有匹配')
13095
+ for (const r of rows) console.log(`${r.seq}\t${r.role}\t${r.content.replace(/\s+/g, ' ').slice(0, 160)}`)
13096
+ }
10538
13097
  }
10539
13098
  } else if (command === 'nudge') {
10540
13099
  const sub = args[0]
@@ -10556,13 +13115,25 @@ if (!command) {
10556
13115
  // it through the lock-free store.
10557
13116
  const sources = args.includes('--sources')
10558
13117
  const asJson = args.includes('--json')
10559
- if (asJson || sources) {
13118
+ const limitInfo = parseTodayLimit(args)
13119
+ if (limitInfo.error) {
13120
+ usageFail(limitInfo.error, 'usage: advisers today [--calendar] [--sources] [--json] [--limit n]')
13121
+ } else if (asJson && limitInfo.limit !== null && !sources && mode === 'sqlite') {
13122
+ // 0.3.2 fast path: classify the narrow projection, then hydrate only the
13123
+ // capped bucket rows (full Commitment entities, same order).
13124
+ await today(loadOpenCommitmentRowsForToday(), {
13125
+ calendar: args.includes('--calendar'),
13126
+ json: true,
13127
+ limit: limitInfo.limit,
13128
+ hydrate: hydrateCommitmentsForToday,
13129
+ })
13130
+ } else if (asJson || sources) {
10560
13131
  // The JSON contract and --sources need full commitment entities (evidence).
10561
13132
  // 0.3.0 P0-T1: 'table' reads the table without the status index, so the
10562
13133
  // historical rowid order is kept with no ORDER BY rowid TEMP B-TREE spill
10563
13134
  // (today --json used to write 10 MB per run at a 200k-row ledger).
10564
13135
  const ledger = readLedgerForCommand({ commitments: sources ? {} : { status: 'open', order: 'table' } })
10565
- await today(ledger.openCommitments(), { calendar: args.includes('--calendar'), sources, json: asJson, ledger })
13136
+ await today(ledger.openCommitments(), { calendar: args.includes('--calendar'), sources, json: asJson, ledger, limit: limitInfo.limit })
10566
13137
  } else {
10567
13138
  // Human view: six columns + the cached classification (0.2.3 hot path).
10568
13139
  await today(loadOpenCommitmentRowsForToday(), { calendar: args.includes('--calendar') })
@@ -10637,7 +13208,10 @@ if (!command) {
10637
13208
  } else if (candidate.kind === 'commitment') {
10638
13209
  const input = {
10639
13210
  ...candidate.payload,
10640
- matterId: candidate.payload.matterId ?? s.firstActiveMatter?.()?.id,
13211
+ // Mail/KB candidates may arrive before any matter exists; a
13212
+ // commitment must always point at a real matter (SQLite binds
13213
+ // undefined as an error, and the ledger tolerates no dangling).
13214
+ matterId: candidate.payload.matterId ?? s.firstActiveMatter?.()?.id ?? resolveDeliveryMatterId(s),
10641
13215
  evidence: candidate.evidence.map(commitmentEvidence),
10642
13216
  }
10643
13217
  s.insertCommitment(core.createCommitment(opsPorts, input))
@@ -10674,13 +13248,25 @@ if (!command) {
10674
13248
  } else if (command === 'matter') {
10675
13249
  await matterCommand(args)
10676
13250
  } else if (command === 'client') {
10677
- clientCommand(args)
13251
+ await clientCommand(args)
10678
13252
  } else if (command === 'project') {
10679
13253
  projectCommand(args)
10680
13254
  } else if (command === 'agenda') {
10681
13255
  await agendaCommand(args)
10682
13256
  } else if (command === 'morning') {
10683
13257
  await morningReportCommand(args)
13258
+ } else if (command === 'kb') {
13259
+ await kbCommand(args)
13260
+ } else if (command === 'fact') {
13261
+ await factCommand(args)
13262
+ } else if (command === 'mail') {
13263
+ await mailCommand(args)
13264
+ } else if (command === 'receivable') {
13265
+ await receivableCommand(args)
13266
+ } else if (command === 'payment') {
13267
+ await paymentCommand(args)
13268
+ } else if (command === 'consent') {
13269
+ await consentCommand(args)
10684
13270
  } else if (command === 'digest') {
10685
13271
  if (args[0] === 'morning') await morningReportCommand(args.slice(1))
10686
13272
  else {