advisers 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/advisers.js CHANGED
@@ -736,6 +736,35 @@ function loadOpenCommitmentRowsForToday() {
736
736
  return readProjection((store) => store.projectOpenCommitmentsForToday()) ?? []
737
737
  }
738
738
 
739
+ /**
740
+ * 0.3.2: parse `today --json --limit N` (additive cap; N full Commitment rows
741
+ * per bucket, counts stay the true totals). Requires --json and is not
742
+ * combinable with --sources, which needs the full evidence rows.
743
+ */
744
+ function parseTodayLimit(args) {
745
+ const index = args.indexOf('--limit')
746
+ if (index === -1) return { limit: null }
747
+ const raw = args[index + 1]
748
+ if (typeof raw !== 'string' || !/^[1-9][0-9]*$/.test(raw)) return { error: '--limit must be an integer 1..10000' }
749
+ const value = Number(raw)
750
+ if (value < 1 || value > 10000) return { error: '--limit must be an integer 1..10000' }
751
+ if (!args.includes('--json')) return { error: '--limit requires --json (the human view has its own cap)' }
752
+ if (args.includes('--sources')) return { error: '--limit cannot be combined with --sources (the source rows need full evidence)' }
753
+ return { limit: value }
754
+ }
755
+
756
+ /** Full Commitment entities for the capped today --json rows, id order preserved. */
757
+ function hydrateCommitmentsForToday(ids) {
758
+ if (!Array.isArray(ids) || !ids.length) return []
759
+ const store = readStoreOrExit()
760
+ if (!store) return []
761
+ try {
762
+ return store.read(() => ids.map((id) => store.getCommitment(id)).filter(Boolean))
763
+ } catch {
764
+ return []
765
+ }
766
+ }
767
+
739
768
  /** Narrow commitment rows for reminder planning (remind / tui). */
740
769
  function loadReminderRows({ includeUndated = false } = {}) {
741
770
  return readProjection((store) => store.projectCommitmentsForReminders({ includeUndated }))
@@ -1061,7 +1090,7 @@ const CONTRACTS_DISCOVERY = Object.freeze({
1061
1090
  mcpTools: 1,
1062
1091
  mcpResources: 1,
1063
1092
  mcpProtocol: '2024-11-05',
1064
- dshTools: 1,
1093
+ dshTools: 2,
1065
1094
  petBrief: 2,
1066
1095
  })
1067
1096
  function friendlyError(error) {
@@ -1180,7 +1209,7 @@ Usage:
1180
1209
  advisers history recent conversations
1181
1210
  advisers search <text> full-text search old turns
1182
1211
  advisers compact ls|rollback summary versions
1183
- advisers today [--calendar] [--sources] [--json]
1212
+ advisers today [--calendar] [--sources] [--json [--limit n]]
1184
1213
  one-screen today/week/waiting view (+ local events)
1185
1214
  advisers remind [--json] [--ics [path]] [--deliver [--notify]] due reminders + ICS/VALARM export
1186
1215
  advisers remind install|uninstall|status [--apply] [--schedule "0 9 * * *"]
@@ -1233,6 +1262,7 @@ Usage:
1233
1262
  [--limit n] [--clearance 0-3] [--json]
1234
1263
  advisers client archive <id> [--dry-run] [--json]
1235
1264
  advisers client merge <from> <into> [--dry-run] [--json]
1265
+ advisers client export <id> [--format md|docx] [--out <file>] [--redact-names] [--json]
1236
1266
  advisers client note add <id> "<summary>" [--kind k] [--at ISO] [--project id] [--matter id] [--json]
1237
1267
  advisers client note list <id> [--project id] [--limit n] [--json]
1238
1268
  advisers project add <client-id> "<name>" [--start YYYY-MM-DD] [--end YYYY-MM-DD]
@@ -1269,7 +1299,7 @@ Usage:
1269
1299
  advisers capture --from-transcript <file> 转写稿导入→候选(不录音/不入会)
1270
1300
  advisers capture --from-imap 只读 IMAP 导入(EXAMINE/FETCH;env 凭据)
1271
1301
  advisers ui [--port n] 本地只读视图(127.0.0.1,GET only)
1272
- advisers mcp --stdio MCP server(7 工具 + 4 resources;写入口仅 pending 候选/回执校验)
1302
+ advisers mcp --stdio MCP server(8 工具 + 5 resources;写入口仅 pending 候选/回执校验)
1273
1303
  advisers evidence show <id> [--json] 承诺/事实/偏好→原文来源
1274
1304
  advisers deliver [--commit id] [--type confirmation|weekly|statement|ledger] [--format docx|xlsx|pdf] [--out f] 交付物
1275
1305
  advisers deliveries --pack [--out dir] [--ids ...] [--all] 证据包(manifest/README/SHA256SUMS + DOCX 回执;默认上限 2000)
@@ -1520,7 +1550,7 @@ function purgeMatter(id, confirmed) {
1520
1550
  function parseFlags(args) {
1521
1551
  const flags = {}
1522
1552
  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'])
1553
+ 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'])
1524
1554
  for (let i = 0; i < args.length; i++) {
1525
1555
  if (args[i].startsWith('--')) {
1526
1556
  const key = args[i].slice(2)
@@ -2216,6 +2246,7 @@ const CUSTOMER_USAGE = {
2216
2246
  projectList: 'usage: advisers project list [--client <id>] [--all] [--limit n] [--json]',
2217
2247
  projectShow: 'usage: advisers project show <id> [--timeline-limit n] [--clearance 0-3] [--json]',
2218
2248
  projectArchive: 'usage: advisers project archive <id> [--dry-run] [--json]',
2249
+ export: 'usage: advisers client export <id> [--format md|docx] [--out <file>] [--redact-names] [--json]',
2219
2250
  }
2220
2251
 
2221
2252
  /** An application error with a stable E_* code and optional actionable hint. */
@@ -2687,6 +2718,7 @@ function clientUsage() {
2687
2718
  console.log(' ' + CUSTOMER_USAGE.merge)
2688
2719
  console.log(' ' + CUSTOMER_USAGE.note)
2689
2720
  console.log(' ' + CUSTOMER_USAGE.noteList)
2721
+ console.log(' ' + CUSTOMER_USAGE.export)
2690
2722
  console.log('客户是归属维度:matter 通过 --client/--project 挂到客户;commitments/facts 仍只挂 matter。')
2691
2723
  }
2692
2724
 
@@ -3042,6 +3074,153 @@ function clientNoteList(rest) {
3042
3074
  } catch (error) { reportCustomerFailure(error) }
3043
3075
  }
3044
3076
 
3077
+ /**
3078
+ * `advisers client export <id>`: deterministic, external-facing client status
3079
+ * sheet (markdown or DOCX). It is written at clearance 0, never contains
3080
+ * evidence quotes or note bodies, and states its own scope/limits: it is a
3081
+ * status summary, not a statement of account, contract or legal advice.
3082
+ *
3083
+ * The file is created 0600 (directory 0700) and its SHA-256 is reported in the
3084
+ * JSON summary so a recipient can verify the bytes out of band.
3085
+ */
3086
+ async function clientExport(rest) {
3087
+ const usage = CUSTOMER_USAGE.export
3088
+ try {
3089
+ const parsed = customerFlags(rest, { booleans: ['json', 'redact-names'], values: ['format', 'out'] }, usage)
3090
+ const id = customerIdArg(parsed.positional, 0, 'a client id', usage)
3091
+ const format = parsed.flags.format === undefined ? 'md' : String(parsed.flags.format).toLowerCase()
3092
+ if (format !== 'md' && format !== 'docx') throw customerError('E_USAGE', '--format must be md or docx', usage)
3093
+ if (parsed.flags.out !== undefined && (typeof parsed.flags.out !== 'string' || !parsed.flags.out.trim())) {
3094
+ throw customerError('E_USAGE', '--out requires a file path', usage)
3095
+ }
3096
+ if (!customerStoreOrFail()) return
3097
+ const store = readStoreOrExit()
3098
+ const clearance = 0
3099
+ const generatedAt = new Date().toISOString()
3100
+ const data = store.read(() => {
3101
+ const view = readClientView(store, id)
3102
+ const filtered = clearCustomerView(view, clearance)
3103
+ const counts = customerClientCounts(store, view, filtered, clearance)
3104
+ const timeline = customerTimeline(view, filtered, { kinds: ['delivery', 'commitment'], limit: 20 })
3105
+ const open = customerOpenBuckets(view, filtered)
3106
+ const redact = parsed.flags['redact-names'] === true
3107
+ const projectRows = view.projects
3108
+ .filter((project) => project.status !== 'archived')
3109
+ .map((project) => {
3110
+ const summary = customerProjectOfClientCounts(store, view, filtered, project, clearance)
3111
+ return {
3112
+ id: project.id,
3113
+ name: redact ? '(已隐去)' : project.name,
3114
+ status: project.status,
3115
+ counts: summary.counts,
3116
+ nextDueAt: summary.nextDueAt,
3117
+ }
3118
+ })
3119
+ return {
3120
+ client: view.client,
3121
+ displayName: redact ? '(已隐去)' : view.client.name,
3122
+ aliases: redact ? [] : view.client.aliases,
3123
+ projects: projectRows,
3124
+ counts: counts,
3125
+ open: {
3126
+ mine: open.mine.map((row) => ({ id: row.id, action: row.action, dueAt: row.dueAt ?? null, projectId: row.projectId ?? null })),
3127
+ waiting: open.waiting.map((row) => ({ id: row.id, action: row.action, dueAt: row.dueAt ?? null, projectId: row.projectId ?? null })),
3128
+ },
3129
+ nextDueAt: customerNextDueAt(filtered.open),
3130
+ timeline: timeline.items.map((item) => ({ at: item.at, kind: item.kind, title: item.title, status: item.status ?? null })),
3131
+ timelineTotal: timeline.total,
3132
+ timelineTruncated: timeline.truncated,
3133
+ protectedExcluded: filtered.protectedExcluded,
3134
+ }
3135
+ })
3136
+ const disclaimer = '本文件是状态说明,不是对账单、合同、法律意见或送达证明;本地生成、无签名、未锚定(仅本地自证)。SHA-256 仅用于检测生成后的改动。'
3137
+ const scopeLine = '范围:本文件只含客户 ' + data.client.id + '(' + data.displayName + ')的数据;其他客户数据、全局 facts/preferences、对话原文与备注正文不在本文件内。'
3138
+ const sections = []
3139
+ sections.push({ heading: '概况', paragraphs: [
3140
+ '客户:' + data.displayName + ' (' + data.client.id + ') · 状态 ' + data.client.status + (data.aliases.length ? ' · 别名 ' + data.aliases.join('/') : ''),
3141
+ '事项 ' + data.counts.matters + '(归档 ' + data.counts.mattersArchived + ') · 未完成 我方 ' + data.counts.openMine + ' / 等待对方 ' + data.counts.openWaiting + ' · 逾期 ' + data.counts.overdue + ' · 交付 ' + data.counts.deliveries + ' · 备注 ' + data.counts.notes + '(仅计数)',
3142
+ '下一截止:' + (data.nextDueAt || '无'),
3143
+ '受保护事项(clearance=0 不可见,仅计数):' + data.protectedExcluded,
3144
+ ] })
3145
+ sections.push({ heading: '进行中的项目', paragraphs: data.projects.length
3146
+ ? data.projects.map((project) => project.id + ' ' + project.name + ' ' + project.status + ' · 事项 ' + project.counts.matters + ' · 未完成 ' + (project.counts.openMine + project.counts.openWaiting) + ' · 下一截止 ' + (project.nextDueAt || '无'))
3147
+ : ['(没有进行中的项目)'] })
3148
+ const openLines = (title, rows) => {
3149
+ const out = [title + '(' + rows.length + '):']
3150
+ if (!rows.length) out.push('(无)')
3151
+ for (const row of rows.slice(0, 20)) out.push('- ' + (row.dueAt ? row.dueAt + ' ' : '') + row.action + (row.projectId ? ' [' + row.projectId + ']' : ''))
3152
+ return out
3153
+ }
3154
+ sections.push({ heading: '待办', paragraphs: [...openLines('我方欠客户', data.open.mine), ...openLines('等待对方', data.open.waiting)] })
3155
+ sections.push({ heading: '最近时间线', paragraphs: data.timeline.length
3156
+ ? data.timeline.map((item) => String(item.at).replace('T', ' ').slice(0, 16) + ' ' + item.kind + ' ' + item.title + (item.status ? ' [' + item.status + ']' : ''))
3157
+ : ['(没有可展示的时间线条目)'] })
3158
+ sections.push({ heading: '边界与校验', paragraphs: [scopeLine, disclaimer, '生成时间:' + generatedAt + ' · advisers ' + VERSION + ' · clearance=0'] })
3159
+ const markdown = ['# 客户状态包 · ' + data.displayName, '', '> ' + scopeLine, '> ' + disclaimer, '',
3160
+ ...sections.flatMap((section) => ['## ' + section.heading, '', ...section.paragraphs, ''])].join('\n')
3161
+ let buffer
3162
+ if (format === 'docx') {
3163
+ let buildDocx
3164
+ try {
3165
+ buildDocx = await loadOfficeOperation('docx', 'buildDocx')
3166
+ } catch {}
3167
+ if (typeof buildDocx !== 'function') {
3168
+ throw customerError('E_USAGE', '--format docx 需要可选的 advisers-office 包(当前不可用)', 'advisers client export ' + data.client.id + ' --format md')
3169
+ }
3170
+ buffer = await buildDocx({ title: '客户状态包 · ' + data.displayName, sections: sections })
3171
+ } else {
3172
+ buffer = Buffer.from(markdown, 'utf8')
3173
+ }
3174
+ const out = typeof parsed.flags.out === 'string'
3175
+ ? parsed.flags.out.trim()
3176
+ : join(HOME, 'exports', 'client-' + data.client.id + '-' + generatedAt.replace(/[:.]/g, '-') + '.' + format)
3177
+ const dir = dirname(out)
3178
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
3179
+ try { chmodSync(dir, 0o700) } catch {}
3180
+ writeFileSync(out, buffer, { mode: 0o600 })
3181
+ try { chmodSync(out, 0o600) } catch {}
3182
+ const sha256 = createHash('sha256').update(buffer).digest('hex')
3183
+ // A client status sheet is an external-facing artifact: record the export
3184
+ // (ids/counts only, no names) even though it does not mutate the ledger.
3185
+ try {
3186
+ const writeStore = dbStore()
3187
+ if (writeStore) {
3188
+ writeStore.appendAudit({
3189
+ actor: 'local',
3190
+ action: 'client.export',
3191
+ allowed: true,
3192
+ reason: 'client ' + data.client.id + ' format=' + format + ' bytes=' + buffer.length + ' protected=' + data.protectedExcluded,
3193
+ })
3194
+ }
3195
+ } catch {}
3196
+ const payload = {
3197
+ ok: true,
3198
+ command: 'client export',
3199
+ format: format,
3200
+ scope: 'client',
3201
+ subject: { kind: 'client', id: data.client.id, name: data.displayName },
3202
+ out: out,
3203
+ bytes: buffer.length,
3204
+ sha256: sha256,
3205
+ generatedAt: generatedAt,
3206
+ clearance: clearance,
3207
+ protectedExcluded: data.protectedExcluded,
3208
+ counts: data.counts,
3209
+ nextDueAt: data.nextDueAt,
3210
+ timelineCount: data.timeline.length,
3211
+ timelineTotal: data.timelineTotal,
3212
+ timelineTruncated: data.timelineTruncated,
3213
+ disclaimer: true,
3214
+ }
3215
+ const human = [
3216
+ '已生成客户状态包(' + format + '):' + out,
3217
+ '客户:' + data.displayName + ' (' + data.client.id + ') · 事项 ' + data.counts.matters + ' · 未完成 我方 ' + data.counts.openMine + ' / 等待对方 ' + data.counts.openWaiting,
3218
+ 'clearance=0 · 受保护事项仅计数:' + data.protectedExcluded + ' · sha256=' + sha256,
3219
+ '边界:状态说明,不是对账单/合同/法律意见;不含对话原文与备注正文。',
3220
+ ]
3221
+ customerPrint(parsed.flags.json === true, payload, human)
3222
+ } catch (error) { reportCustomerFailure(error) }
3223
+ }
3045
3224
  function clientCommand(rawArgs) {
3046
3225
  const sub = rawArgs[0]
3047
3226
  const rest = rawArgs.slice(1)
@@ -3050,6 +3229,7 @@ function clientCommand(rawArgs) {
3050
3229
  if (sub === 'list' || sub === 'ls') return clientList(rest)
3051
3230
  if (sub === 'show') return clientShow(rest)
3052
3231
  if (sub === 'timeline') return clientTimeline(rest)
3232
+ if (sub === 'export') return clientExport(rest)
3053
3233
  if (sub === 'archive') return clientArchive(rest)
3054
3234
  if (sub === 'merge') return clientMerge(rest)
3055
3235
  if (sub === 'note') return clientNote(rest)
@@ -3802,7 +3982,7 @@ async function printSources(ledger) {
3802
3982
  for (const r of rows.slice(0, 20)) console.log(` ${r.commitmentId} ${r.action} ← ${r.label} (${r.ref ?? '-'}) 「${r.quote.slice(0, 80)}」`)
3803
3983
  }
3804
3984
 
3805
- async function today(openRows, { calendar = false, sources = false, json = false, ledger = null } = {}) {
3985
+ async function today(openRows, { calendar = false, sources = false, json = false, ledger = null, limit = null, hydrate = null } = {}) {
3806
3986
  const nowMs = Date.now()
3807
3987
  const localDay = localDayOf(nowMs)
3808
3988
  const weekAhead = nowMs + 7 * 86400_000
@@ -3850,17 +4030,32 @@ async function today(openRows, { calendar = false, sources = false, json = false
3850
4030
  }
3851
4031
  if (json) {
3852
4032
  // JSON contract v1 (docs/CLI-JSON.md): same classification as the human view.
4033
+ // 0.3.2 additive `--limit N`: each bucket keeps at most N full Commitment
4034
+ // entities (hydrated on demand); `counts`/`next` stay the true totals. The
4035
+ // flagless output is byte-identical to v1.
4036
+ const capped = (list) => (limit === null ? list : list.slice(0, limit))
4037
+ const materialize = (list) => {
4038
+ const kept = capped(list)
4039
+ if (limit === null || typeof hydrate !== 'function' || !kept.length) return kept
4040
+ const hydrated = hydrate(kept.map((row) => row.id))
4041
+ const byId = new Map((Array.isArray(hydrated) ? hydrated : []).map((row) => [row.id, row]))
4042
+ return kept.map((row) => byId.get(row.id) ?? row)
4043
+ }
3853
4044
  const payload = {
3854
4045
  now: new Date(nowMs).toISOString(),
3855
4046
  localDay,
3856
4047
  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,
4048
+ overdue: materialize(overdue),
4049
+ today: materialize(todayDue),
4050
+ week: materialize(week),
4051
+ waiting: materialize(waiting),
4052
+ noDue: materialize(noDue),
3862
4053
  next: next ? { id: next.id, action: next.action, dueAt: next.dueAt } : null,
3863
4054
  }
4055
+ if (limit !== null) {
4056
+ payload.limit = limit
4057
+ payload.truncated = [overdue, todayDue, week, waiting, noDue].some((list) => list.length > limit)
4058
+ }
3864
4059
  if (calendar) {
3865
4060
  const calendarToday = await calendarOccurrencesToday()
3866
4061
  payload.calendar = calendarToday.occurrences
@@ -8378,7 +8573,7 @@ async function deliver(args) {
8378
8573
  /**
8379
8574
  * `advisers mcp --stdio`: the shipped stdio entry for the MCP server.
8380
8575
  *
8381
- * The protocol surface lives in lib/mcp-server.js (7 tools incl. the pending-only
8576
+ * The protocol surface lives in lib/mcp-server.js (8 tools incl. the pending-only
8382
8577
  * candidate write + read-only pack verification, 4 read-only resources, 1 MiB
8383
8578
  * line cap, -32601/-32602/-32002/-32700). This wiring only supplies process
8384
8579
  * state: the home, the store/ledger, the version and the audit sink. Every
@@ -8405,9 +8600,26 @@ async function mcpServer() {
8405
8600
  return Ledger.fromJSON(store.load(), LOCAL_PORTS)
8406
8601
  }
8407
8602
  const { createMcpServer } = await loadMcpServer()
8603
+ // 0.3.2 P2-1: give the MCP read models the narrow commitment projection so the
8604
+ // first tools/call does not map the whole ledger. Without a SQLite store (JSON
8605
+ // mode) the options stay undefined and the server keeps the legacy path.
8606
+ const narrowCommitments = typeof store?.projectCommitmentReadModel === 'function'
8607
+ ? {
8608
+ loadCommitmentView: (options) => store.read(() => store.projectCommitmentReadModel(options)),
8609
+ loadCommitmentRecords: (ids) => store.read(() => {
8610
+ const byId = new Map()
8611
+ for (const id of ids) {
8612
+ const record = store.getCommitment(id)
8613
+ if (record) byId.set(id, record)
8614
+ }
8615
+ return byId
8616
+ }),
8617
+ }
8618
+ : {}
8408
8619
  const server = createMcpServer({
8409
8620
  store,
8410
8621
  loadLedger: loadLedgerFor,
8622
+ ...narrowCommitments,
8411
8623
  version: VERSION,
8412
8624
  audit: (entry) => store?.appendAudit(entry),
8413
8625
  })
@@ -9263,6 +9475,189 @@ async function verifyDeliveryArtifacts(files) {
9263
9475
  * --ids narrows/extends it). The old evidence-only path stays on
9264
9476
  * `deliveries --pack`.
9265
9477
  */
9478
+ /**
9479
+ * Resolve the optional client/project scope of `deliveries --receipt`.
9480
+ * Returns null when the pack is unscoped (historical local-all behaviour).
9481
+ * Every lookup fails closed: an unknown id is E_CLIENT_NOT_FOUND /
9482
+ * E_PROJECT_NOT_FOUND, and a project that belongs to another client is
9483
+ * E_PROJECT_CLIENT_MISMATCH (the same codes as the client commands).
9484
+ */
9485
+ function receiptSubjectOf(store, flags) {
9486
+ if (flags.client === true || flags.project === true) {
9487
+ throw customerError('E_USAGE', '--client/--project require an id', 'advisers deliveries --receipt --client <client-id>')
9488
+ }
9489
+ const clientId = typeof flags.client === 'string' ? flags.client.trim() : ''
9490
+ const projectId = typeof flags.project === 'string' ? flags.project.trim() : ''
9491
+ if (!clientId && !projectId) return null
9492
+ let project = null
9493
+ if (projectId) {
9494
+ project = store.getProject(projectId)
9495
+ if (!project) throw customerError('E_PROJECT_NOT_FOUND', 'unknown project: ' + projectId, 'advisers project list')
9496
+ }
9497
+ const resolvedClientId = clientId || project.clientId
9498
+ const client = store.getClient(resolvedClientId)
9499
+ if (!client) throw customerError('E_CLIENT_NOT_FOUND', 'unknown client: ' + resolvedClientId, 'advisers client list')
9500
+ if (project && project.clientId !== client.id) {
9501
+ throw customerError('E_PROJECT_CLIENT_MISMATCH', 'project ' + project.id + ' belongs to client ' + project.clientId, 'advisers project list --client ' + client.id)
9502
+ }
9503
+ const matters = project ? store.listMattersByProject(project.id) : store.listMattersByClient(client.id)
9504
+ return {
9505
+ kind: project ? 'project' : 'client',
9506
+ id: project ? project.id : client.id,
9507
+ name: project ? project.name : client.name,
9508
+ client: client,
9509
+ project: project,
9510
+ matterIds: matters.map((matter) => matter.id),
9511
+ matterIdSet: new Set(matters.map((matter) => matter.id)),
9512
+ }
9513
+ }
9514
+
9515
+ /**
9516
+ * Effective secrecy of one delivery row: max(client.secrecyDefault, matter
9517
+ * secrecy). A row with an unresolvable matter is treated as protected
9518
+ * (Infinity), never guessed. This is the 0.3.2 receipt rule for local-all
9519
+ * packs too: a client marked secret cannot leak through a receipt.
9520
+ */
9521
+ function receiptRowSecrecy(store, ledger, row, clientById) {
9522
+ let level = itemMatterSecrecy(ledger, row.matterId)
9523
+ let clientId = row.clientId || null
9524
+ if (!clientId && row.matterId) {
9525
+ try { clientId = ledger.getMatter(row.matterId)?.clientId ?? null } catch { clientId = null }
9526
+ }
9527
+ if (clientId) {
9528
+ let client = clientById.get(clientId)
9529
+ if (client === undefined) {
9530
+ try { client = store.getClient(clientId) ?? null } catch { client = null }
9531
+ clientById.set(clientId, client)
9532
+ }
9533
+ if (client) level = Math.max(level, Number(client.secrecyDefault) || 0)
9534
+ }
9535
+ return level
9536
+ }
9537
+
9538
+ /**
9539
+ * Evidence ids for one receipt subject: only the subject's matters.
9540
+ * Global facts/preferences (no matter association) are excluded unless
9541
+ * --include-global is explicit; the count of excluded global rows is reported
9542
+ * without their content.
9543
+ */
9544
+ function receiptEvidenceIds(ledger, subject, includeGlobal) {
9545
+ const ids = { commitments: [], facts: [], preferences: [] }
9546
+ let excludedGlobal = 0
9547
+ for (const row of ledger.listCommitments()) {
9548
+ if (!subject.matterIdSet.has(row.matterId)) continue
9549
+ if (itemMatterSecrecy(ledger, row.matterId) > 0) continue
9550
+ ids.commitments.push(row.id)
9551
+ }
9552
+ for (const row of ledger.listFacts()) {
9553
+ const matterId = typeof row.matterId === 'string' ? row.matterId : ''
9554
+ if (matterId) {
9555
+ if (!subject.matterIdSet.has(matterId)) continue
9556
+ if (itemMatterSecrecy(ledger, matterId) > 0) continue
9557
+ } else if (!includeGlobal) {
9558
+ excludedGlobal += 1
9559
+ continue
9560
+ }
9561
+ ids.facts.push(row.id)
9562
+ }
9563
+ for (const row of ledger.listPreferences({ includeCandidates: false })) {
9564
+ const scope = row && row.scope
9565
+ const matterId = scope && scope.level === 'matter' && typeof scope.value === 'string' ? scope.value : ''
9566
+ if (matterId) {
9567
+ if (!subject.matterIdSet.has(matterId)) continue
9568
+ if (itemMatterSecrecy(ledger, matterId) > 0) continue
9569
+ } else if (!includeGlobal) {
9570
+ excludedGlobal += 1
9571
+ continue
9572
+ }
9573
+ ids.preferences.push(row.id)
9574
+ }
9575
+ return { ids: ids, excludedGlobal: excludedGlobal }
9576
+ }
9577
+
9578
+ /** Matter id of one evidence record ('' for a global record). */
9579
+ function receiptEvidenceMatterId(record, kind) {
9580
+ if (!record || typeof record !== 'object') return ''
9581
+ if (kind === 'preference') {
9582
+ const scope = record.scope
9583
+ return scope && scope.level === 'matter' && typeof scope.value === 'string' ? scope.value : ''
9584
+ }
9585
+ return typeof record.matterId === 'string' ? record.matterId : ''
9586
+ }
9587
+
9588
+ /** Effective secrecy of one evidence record: max(client default, matter secrecy). */
9589
+ function receiptEvidenceRecordSecrecy(store, ledger, record, kind, clientById) {
9590
+ const matterId = receiptEvidenceMatterId(record, kind)
9591
+ if (!matterId) return 0
9592
+ let level = itemMatterSecrecy(ledger, matterId)
9593
+ let clientId = null
9594
+ try { clientId = ledger.getMatter(matterId)?.clientId ?? null } catch { clientId = null }
9595
+ if (clientId) {
9596
+ let client = clientById.get(clientId)
9597
+ if (client === undefined) {
9598
+ try { client = store.getClient(clientId) ?? null } catch { client = null }
9599
+ clientById.set(clientId, client)
9600
+ }
9601
+ if (client) level = Math.max(level, Number(client.secrecyDefault) || 0)
9602
+ }
9603
+ return level
9604
+ }
9605
+
9606
+ /**
9607
+ * Local-all receipt evidence: the same client-level secrecy rule as the
9608
+ * delivery rows, so a client marked secret cannot leak through the evidence
9609
+ * section while its deliveries are correctly excluded.
9610
+ */
9611
+ function receiptGlobalEvidenceIds(store, ledger, clientById) {
9612
+ const ids = { commitments: [], facts: [], preferences: [] }
9613
+ // Matter-level secrecy stays with buildEvidencePack (it counts those rows as
9614
+ // evidence.protectedExcluded, the historical A-1 behaviour). Only a
9615
+ // client-level default above 0 is pre-filtered here, because the evidence
9616
+ // builder cannot see client rows; those are reported separately so the two
9617
+ // counts never double-count.
9618
+ const keep = (row, kind, into) => {
9619
+ const matterId = receiptEvidenceMatterId(row, kind)
9620
+ const matterLevel = matterId ? itemMatterSecrecy(ledger, matterId) : 0
9621
+ if (matterLevel > 0) { into.push(row.id); return }
9622
+ if (matterId && receiptEvidenceRecordSecrecy(store, ledger, row, kind, clientById) > 0) {
9623
+ protectedExcluded += 1
9624
+ return
9625
+ }
9626
+ into.push(row.id)
9627
+ }
9628
+ let protectedExcluded = 0
9629
+ for (const row of ledger.listCommitments()) keep(row, 'commitment', ids.commitments)
9630
+ for (const row of ledger.listFacts()) keep(row, 'fact', ids.facts)
9631
+ for (const row of ledger.listPreferences({ includeCandidates: false })) keep(row, 'preference', ids.preferences)
9632
+ return { ids: ids, protectedExcluded: protectedExcluded }
9633
+ }
9634
+
9635
+ /** Explicit --ids on a local-all receipt: fail closed when any id is protected. */
9636
+ function receiptExplicitEvidenceProtected(store, ledger, ids, clientById) {
9637
+ const records = new Map()
9638
+ for (const row of ledger.listCommitments()) records.set(row.id, { kind: 'commitment', record: row })
9639
+ for (const row of ledger.listFacts()) records.set(row.id, { kind: 'fact', record: row })
9640
+ for (const row of ledger.listPreferences({ includeCandidates: false })) records.set(row.id, { kind: 'preference', record: row })
9641
+ let protectedCount = 0
9642
+ for (const id of ids) {
9643
+ const found = records.get(id)
9644
+ if (!found) continue
9645
+ if (receiptEvidenceRecordSecrecy(store, ledger, found.record, found.kind, clientById) > 0) protectedCount += 1
9646
+ }
9647
+ return protectedCount
9648
+ }
9649
+
9650
+ /**
9651
+ * `advisers deliveries --receipt`: build a delivery receipt pack.
9652
+ *
9653
+ * 0.3.2: the pack can be scoped to one client or project. A subject pack only
9654
+ * copies that subject's delivered artifacts and evidence (global facts and
9655
+ * preferences need --include-global), records `subject`/`scope` in the v2
9656
+ * manifest, and states in README.txt/receipt.docx that it contains one
9657
+ * subject's data. The unscoped historical form remains, but is now labelled
9658
+ * scope=local-all: it contains every local customer's data and must not be
9659
+ * forwarded to a third party.
9660
+ */
9266
9661
  async function receiptPack(args) {
9267
9662
  const { flags } = parseFlags(args)
9268
9663
  ensureHome()
@@ -9271,25 +9666,73 @@ async function receiptPack(args) {
9271
9666
  const ledger = loadLedger()
9272
9667
  const denied = egressDeniedReason(ledger.getMatter(activeMatterId(ledger)), 'evidence')
9273
9668
  if (denied) { console.error(denied); process.exitCode = 1; return }
9669
+ if ((flags.client !== undefined || flags.project !== undefined) && flags.ids !== undefined) {
9670
+ console.error('E_USAGE: --ids cannot be combined with --client/--project (a subject pack derives its evidence scope from the subject)')
9671
+ process.exitCode = 1
9672
+ return
9673
+ }
9274
9674
  const ids = typeof flags.ids === 'string' ? flags.ids.split(',').map((item) => item.trim()).filter(Boolean) : undefined
9275
9675
  if (ids && !ids.length) { console.error('--ids is empty'); process.exitCode = 1; return }
9276
9676
  const deliveryLimit = Math.max(1, Math.min(2000, Number(flags.limit) || 100))
9677
+ let subject = null
9678
+ try {
9679
+ subject = receiptSubjectOf(store, flags)
9680
+ } catch (error) {
9681
+ console.error('error: ' + String(error?.message ?? error))
9682
+ if (error?.hint) console.error('hint: ' + error.hint)
9683
+ process.exitCode = 1
9684
+ return
9685
+ }
9686
+ // A receipt pack is generated at clearance 0 and is meant to leave the
9687
+ // machine; a client whose default secrecy is above 0 fails closed instead of
9688
+ // producing an empty pack that looks successful.
9689
+ if (subject && Number(subject.client?.secrecyDefault) > 0) {
9690
+ console.error('E_SECRECY_BLOCKED: client ' + subject.client.id + ' has secrecyDefault ' + subject.client.secrecyDefault + ', but a receipt pack is generated at clearance 0')
9691
+ console.error('hint: lower the client secrecy (advisers client ...), or use a local export instead of a shareable receipt')
9692
+ process.exitCode = 1
9693
+ return
9694
+ }
9695
+ // 0.3.2: how many scoped deliveries exist before the readable/limit filters,
9696
+ // so a bounded pack is never mistaken for the whole set (the default limit is
9697
+ // 100, max 2000, and older receipt packs are excluded).
9698
+ let deliveriesTotal = null
9699
+ try {
9700
+ deliveriesTotal = subject
9701
+ ? store.countDeliveriesForScope({
9702
+ clientId: subject.kind === 'client' ? subject.client.id : null,
9703
+ projectId: subject.kind === 'project' ? subject.project.id : null,
9704
+ matterIds: subject.matterIds,
9705
+ })
9706
+ : store.db.prepare("SELECT COUNT(*) AS n FROM deliveries WHERE COALESCE(tool, '') != 'receipt-pack'").get().n
9707
+ } catch { deliveriesTotal = null }
9708
+ const rows = subject
9709
+ ? store.listDeliveriesForScope({
9710
+ clientId: subject.kind === 'client' ? subject.client.id : null,
9711
+ projectId: subject.kind === 'project' ? subject.project.id : null,
9712
+ matterIds: subject.matterIds,
9713
+ limit: deliveryLimit,
9714
+ })
9715
+ : store.listDeliveries(deliveryLimit)
9277
9716
  // A receipt pack records itself as a delivery for discoverability, but a new
9278
9717
  // 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`。')
9718
+ const scopedRows = rows.filter((row) => row.tool !== 'receipt-pack')
9719
+ const deliveriesTruncated = Number.isInteger(deliveriesTotal) ? deliveriesTotal > scopedRows.length : false
9720
+ if (!scopedRows.length) {
9721
+ console.error(subject
9722
+ ? '没有该' + (subject.kind === 'client' ? '客户' : '项目') + '的交付记录可生成回执包;先运行 `advisers deliver` / `advisers office` / `advisers template`。'
9723
+ : '没有交付记录可生成回执包;先运行 `advisers deliver` / `advisers office` / `advisers template`。')
9282
9724
  process.exitCode = 1
9283
9725
  return
9284
9726
  }
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.
9727
+ // A receipt may span many matters. A row from a protected matter (or from a
9728
+ // client with a protected default) is never copied/read; only a count is
9729
+ // reported. Receipts have no per-delivery explicit selection (--ids names
9730
+ // evidence ids), so this path is exclude-only.
9731
+ const clientSecrecyCache = new Map()
9289
9732
  const visibleRows = []
9290
9733
  let protectedDeliveries = 0
9291
- for (const row of rows) {
9292
- if (itemMatterSecrecy(ledger, row.matterId) > 0) {
9734
+ for (const row of scopedRows) {
9735
+ if (receiptRowSecrecy(store, ledger, row, clientSecrecyCache) > 0) {
9293
9736
  protectedDeliveries += 1
9294
9737
  continue
9295
9738
  }
@@ -9312,38 +9755,72 @@ async function receiptPack(args) {
9312
9755
  tool: row.tool ?? null,
9313
9756
  createdAt: row.createdAt ?? null,
9314
9757
  validation: row.validation ?? null,
9315
- files,
9758
+ files: files,
9759
+ matterId: row.matterId ?? undefined,
9760
+ clientId: row.clientId ?? undefined,
9761
+ projectId: row.projectId ?? undefined,
9762
+ templateName: row.templateName ?? undefined,
9763
+ templateVersion: row.templateVersion ?? undefined,
9764
+ quoteNo: row.quoteNo ?? undefined,
9765
+ dataSha256: row.dataSha256 ?? undefined,
9316
9766
  })
9317
9767
  }
9318
9768
  if (!deliveries.length) {
9319
9769
  if (skippedFiles.length) console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
9320
- if (protectedDeliveries) console.error(`另有 ${protectedDeliveries} 条交付记录属于受保护事项(secrecy>0),已排除。`)
9770
+ if (protectedDeliveries) console.error('另有 ' + protectedDeliveries + ' 条交付记录属于受保护事项或受保护客户(secrecy>0),已排除。')
9321
9771
  else if (!skippedFiles.length) console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
9322
9772
  if (skippedFiles.length) console.error('缺失:' + skippedFiles.slice(0, 5).join('; '))
9323
9773
  process.exitCode = 1
9324
9774
  return
9325
9775
  }
9326
9776
  if (skippedFiles.length) console.error('注意:' + skippedFiles.length + ' 个交付文件缺失,已跳过(回执只覆盖仍存在的文件)。')
9327
-
9328
9777
  const verifyResults = await verifyDeliveryArtifacts(deliveries.flatMap((delivery) => delivery.files))
9329
9778
  const { buildEvidencePack, buildReceiptPack, EvidencePackLimitError } = await loadEvidence()
9330
9779
  let evidence
9780
+ let evidenceGlobalExcluded = 0
9781
+ let evidenceClientDefaultExcluded = 0
9331
9782
  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
- })
9783
+ if (subject) {
9784
+ const scoped = receiptEvidenceIds(ledger, subject, flags['include-global'] === true)
9785
+ evidenceGlobalExcluded = scoped.excludedGlobal
9786
+ evidence = buildEvidencePack({
9787
+ store: store,
9788
+ ledger: ledger,
9789
+ ids: scoped.ids,
9790
+ all: flags.all === true,
9791
+ clearance: 0,
9792
+ protectedPolicy: 'error',
9793
+ })
9794
+ } else {
9795
+ // A-1 (0.2.5) + 0.3.2: per-item clearance is max(client default, matter
9796
+ // secrecy) for the evidence section too, so the local-all pack cannot
9797
+ // leak a client-protected record while its deliveries are excluded.
9798
+ let targetIds
9799
+ if (ids) {
9800
+ const protectedCount = receiptExplicitEvidenceProtected(store, ledger, ids, clientSecrecyCache)
9801
+ if (protectedCount > 0) {
9802
+ 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')
9803
+ console.error('hint: remove those ids from --ids; protected records are never partially exported')
9804
+ process.exitCode = 1
9805
+ return
9806
+ }
9807
+ targetIds = ids
9808
+ } else {
9809
+ const scoped = receiptGlobalEvidenceIds(store, ledger, clientSecrecyCache)
9810
+ targetIds = scoped.ids
9811
+ evidenceClientDefaultExcluded = scoped.protectedExcluded
9812
+ }
9813
+ evidence = buildEvidencePack({
9814
+ store: store,
9815
+ ledger: ledger,
9816
+ ids: targetIds,
9817
+ all: flags.all === true,
9818
+ clearance: 0,
9819
+ // Explicit --ids fail closed (A-1); the bulk path excludes protected
9820
+ // rows and reports them through evidence.protectedExcluded.
9821
+ protectedPolicy: ids ? 'error' : 'exclude',
9822
+ })
9823
+ }
9347
9824
  } catch (error) {
9348
9825
  if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
9349
9826
  console.error('error: ' + error.message)
@@ -9357,24 +9834,26 @@ async function receiptPack(args) {
9357
9834
  const out = typeof flags.out === 'string'
9358
9835
  ? flags.out
9359
9836
  : 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
9837
  const docxModule = await importOfficeSubmodule('docx')
9363
9838
  const docxBuilder = typeof docxModule?.buildDocx === 'function'
9364
9839
  ? async (spec) => docxModule.buildDocx(spec)
9365
9840
  : false
9841
+ const scope = subject ? 'subject' : 'local-all'
9842
+ const command = 'advisers deliveries --receipt' + (subject ? ' --' + subject.kind + ' ' + subject.id : '')
9366
9843
  let pack
9367
9844
  try {
9368
9845
  pack = await buildReceiptPack({
9369
- deliveries,
9370
- evidence,
9371
- verifyResults,
9372
- docxBuilder,
9846
+ deliveries: deliveries,
9847
+ subject: subject ? { kind: subject.kind, id: subject.id, name: subject.name } : undefined,
9848
+ scope: scope,
9849
+ evidence: evidence,
9850
+ verifyResults: verifyResults,
9851
+ docxBuilder: docxBuilder,
9373
9852
  env: {
9374
9853
  advisersVersion: VERSION,
9375
9854
  nodeVersion: process.version,
9376
9855
  platform: process.platform,
9377
- command: 'advisers deliveries --receipt',
9856
+ command: command,
9378
9857
  },
9379
9858
  recipient: parseReceiptRecipient(flags.recipient),
9380
9859
  anchors: [],
@@ -9388,13 +9867,13 @@ async function receiptPack(args) {
9388
9867
  }
9389
9868
  const summary = pack.summary
9390
9869
  const evidenceProtectedExcluded = Number.isInteger(evidence?.summary?.protectedExcluded) ? evidence.summary.protectedExcluded : 0
9391
- const protectedExcluded = protectedDeliveries + evidenceProtectedExcluded
9870
+ const protectedExcluded = protectedDeliveries + evidenceProtectedExcluded + evidenceClientDefaultExcluded
9392
9871
  try {
9393
9872
  recordDeliveryWithAudit({
9394
9873
  files: [join(summary.outDir, 'manifest.json'), join(summary.outDir, 'README.txt'), join(summary.outDir, 'SHA256SUMS'), join(summary.outDir, 'receipt.docx')],
9395
9874
  tool: 'receipt-pack',
9396
- title: 'delivery receipt pack',
9397
- validation: 'receipt-pack-v1.1: ' + summary.verifyStatus,
9875
+ title: subject ? 'delivery receipt pack (' + subject.kind + ' ' + subject.id + ')' : 'delivery receipt pack',
9876
+ validation: 'receipt-pack-v2: ' + summary.verifyStatus,
9398
9877
  audit: {
9399
9878
  actor: 'local',
9400
9879
  action: 'receipt.pack',
@@ -9404,6 +9883,7 @@ async function receiptPack(args) {
9404
9883
  ' deliveries/' +
9405
9884
  summary.fileCount +
9406
9885
  ' files' +
9886
+ (subject ? ', scope=' + subject.kind + ':' + subject.id : ', scope=local-all') +
9407
9887
  (protectedDeliveries ? ', ' + protectedDeliveries + ' protected deliveries excluded' : '') +
9408
9888
  (evidenceProtectedExcluded ? ', ' + evidenceProtectedExcluded + ' protected evidence excluded' : ''),
9409
9889
  },
@@ -9412,13 +9892,17 @@ async function receiptPack(args) {
9412
9892
  const { verifyReceiptPackDir, RECEIPT_LIMIT_CODE } = await loadReceiptVerify()
9413
9893
  const verification = verifyReceiptPackDir(summary.outDir)
9414
9894
  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({
9895
+ const payload = {
9416
9896
  ok: verification.ok,
9417
9897
  format: summary.format,
9418
9898
  version: summary.version,
9899
+ scope: scope,
9900
+ subject: subject ? { kind: subject.kind, id: subject.id, name: subject.name } : null,
9419
9901
  out: summary.outDir,
9420
9902
  replaced: summary.replaced ?? null,
9421
9903
  deliveryCount: summary.deliveryCount,
9904
+ deliveriesTotal: deliveriesTotal,
9905
+ deliveriesTruncated: deliveriesTruncated,
9422
9906
  fileCount: summary.fileCount,
9423
9907
  verifyStatus: summary.verifyStatus,
9424
9908
  anchored: summary.anchored,
@@ -9427,21 +9911,23 @@ async function receiptPack(args) {
9427
9911
  receiptSha256: summary.receiptSha256,
9428
9912
  evidence: summary.evidence,
9429
9913
  clearance: 0,
9430
- protectedExcluded,
9914
+ protectedExcluded: protectedExcluded,
9431
9915
  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))
9916
+ evidenceProtectedExcluded: evidenceProtectedExcluded,
9917
+ }
9918
+ if (subject) payload.evidenceGlobalExcluded = evidenceGlobalExcluded
9919
+ if (evidenceClientDefaultExcluded > 0) payload.evidenceClientDefaultExcluded = evidenceClientDefaultExcluded
9920
+ payload.files = summary.files
9921
+ payload.skippedFiles = skippedFiles
9922
+ payload.verification = {
9923
+ ok: verification.ok,
9924
+ errors: verification.errors,
9925
+ warnings: verification.warnings,
9926
+ checksumCount: verification.checksumCount,
9927
+ }
9928
+ console.log(JSON.stringify(payload, null, 2))
9442
9929
  if (!verification.ok) process.exitCode = 1
9443
9930
  }
9444
-
9445
9931
  function link(sub, from, to, type) {
9446
9932
  const ledger = loadLedger()
9447
9933
  if (sub === 'ls' || !sub) {
@@ -10556,13 +11042,25 @@ if (!command) {
10556
11042
  // it through the lock-free store.
10557
11043
  const sources = args.includes('--sources')
10558
11044
  const asJson = args.includes('--json')
10559
- if (asJson || sources) {
11045
+ const limitInfo = parseTodayLimit(args)
11046
+ if (limitInfo.error) {
11047
+ usageFail(limitInfo.error, 'usage: advisers today [--calendar] [--sources] [--json] [--limit n]')
11048
+ } else if (asJson && limitInfo.limit !== null && !sources && mode === 'sqlite') {
11049
+ // 0.3.2 fast path: classify the narrow projection, then hydrate only the
11050
+ // capped bucket rows (full Commitment entities, same order).
11051
+ await today(loadOpenCommitmentRowsForToday(), {
11052
+ calendar: args.includes('--calendar'),
11053
+ json: true,
11054
+ limit: limitInfo.limit,
11055
+ hydrate: hydrateCommitmentsForToday,
11056
+ })
11057
+ } else if (asJson || sources) {
10560
11058
  // The JSON contract and --sources need full commitment entities (evidence).
10561
11059
  // 0.3.0 P0-T1: 'table' reads the table without the status index, so the
10562
11060
  // historical rowid order is kept with no ORDER BY rowid TEMP B-TREE spill
10563
11061
  // (today --json used to write 10 MB per run at a 200k-row ledger).
10564
11062
  const ledger = readLedgerForCommand({ commitments: sources ? {} : { status: 'open', order: 'table' } })
10565
- await today(ledger.openCommitments(), { calendar: args.includes('--calendar'), sources, json: asJson, ledger })
11063
+ await today(ledger.openCommitments(), { calendar: args.includes('--calendar'), sources, json: asJson, ledger, limit: limitInfo.limit })
10566
11064
  } else {
10567
11065
  // Human view: six columns + the cached classification (0.2.3 hot path).
10568
11066
  await today(loadOpenCommitmentRowsForToday(), { calendar: args.includes('--calendar') })