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/lib/mcp-server.js CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  } from './evidence.js'
37
37
  import { buildReminders } from './remind.js'
38
38
  import { inspectCaptureText } from './capture.js'
39
+ import { listClientRows, readClientStatus } from './customer-read.js'
39
40
  import { classify, redact, safetyErrorFrom } from './safety/index.js'
40
41
 
41
42
  /**
@@ -76,6 +77,11 @@ export const MCP_OUTPUT_LIMITS = Object.freeze({
76
77
  whoRows: 20,
77
78
  reminders: 20,
78
79
  evidenceItems: 20,
80
+ clients: 20,
81
+ clientsMax: 50,
82
+ clientTimeline: 20,
83
+ clientTimelineMax: 50,
84
+ clientOpen: 20,
79
85
  })
80
86
  /**
81
87
  * Last-resort byte budget for one tool/resource payload. The per-tool row caps
@@ -86,7 +92,7 @@ export const MCP_OUTPUT_LIMITS = Object.freeze({
86
92
  * classifier never turns a large ledger into CONTENT_BLOCKED.
87
93
  */
88
94
  export const MCP_MAX_RESULT_BYTES = 64 * 1024
89
- const PAYLOAD_LIST_KEYS = Object.freeze(['commitments', 'mine', 'waiting', 'reminders', 'sources', 'missing'])
95
+ const PAYLOAD_LIST_KEYS = Object.freeze(['commitments', 'mine', 'waiting', 'reminders', 'sources', 'missing', 'clients', 'projects', 'timeline'])
90
96
  /** Receipt directories are small; refuse to slurp anything huge. */
91
97
  export const MAX_PACK_FILE_BYTES = 512 * 1024
92
98
  export const MAX_PACK_SUMS_BYTES = 64 * 1024
@@ -104,6 +110,7 @@ export const TOOL_NAMES = Object.freeze([
104
110
  'advisers_who',
105
111
  'advisers_evidence',
106
112
  'advisers_remind',
113
+ 'advisers_clients',
107
114
  'advisers_capture_candidate',
108
115
  'advisers_pack_verify',
109
116
  ])
@@ -113,6 +120,7 @@ export const RESOURCE_URIS = Object.freeze([
113
120
  'advisers://commitments',
114
121
  'advisers://who',
115
122
  'advisers://evidence',
123
+ 'advisers://clients',
116
124
  ])
117
125
 
118
126
  const RESOURCE_DEFINITIONS = Object.freeze([
@@ -140,6 +148,12 @@ const RESOURCE_DEFINITIONS = Object.freeze([
140
148
  description: 'Evidence traceback index for commitments, facts and preferences (counts only).',
141
149
  mimeType: 'application/json',
142
150
  },
151
+ {
152
+ uri: 'advisers://clients',
153
+ name: 'clients',
154
+ description: 'Active client rows as compact read-only projections (exact counts and next due date; no note text or conversation bodies), capped with total/truncated/limit and clearance/protectedExcluded.',
155
+ mimeType: 'application/json',
156
+ },
143
157
  ])
144
158
 
145
159
  const READ_ONLY_ANNOTATIONS = Object.freeze({
@@ -455,9 +469,21 @@ export function readReceiptDirectory(dir) {
455
469
  * (0.2.5 A-2). Every read model excludes records whose matter secrecy is
456
470
  * above it and reports `protectedExcluded`; 0 (fail closed) is the
457
471
  * default and a client cannot raise it through a tool argument.
472
+ * @param {Function} [options.loadCommitmentView] 0.3.2 P2-1 narrow read model:
473
+ * `(options: {all: boolean, clearance: number}) => {rows, total,
474
+ * protectedExcluded}` where rows are the positional projection from
475
+ * `SqliteStore.projectCommitmentReadModel()` (id/debtor/creditor/action/
476
+ * dueAt/status/matterId/reminderOffsets/hidden). When supplied, today /
477
+ * commit_ls / who / remind read this projection instead of loading the
478
+ * full ledger. Omitted => the legacy ledger path is used unchanged
479
+ * (embedders/tests that pass `ledger` never change behaviour).
480
+ * @param {Function} [options.loadCommitmentRecords] 0.3.2 P2-1 hydration for
481
+ * `advisers_who` (whose payload is full Commitment rows): `(ids: string[])
482
+ * => Map<string, object> | object[]`. Only the capped <= 20 rows per
483
+ * bucket are hydrated; omitted => the narrow who path is not used.
458
484
  * @returns {{protocolVersion: string, handle: Function, handleLine: Function, serve: Function, tools: Function, resources: Function}}
459
485
  */
460
- export function createMcpServer({ store, ledger, loadLedger, loadStore, version = '0.0.0', audit, readPack, now = () => new Date(), clearance = 0 } = {}) {
486
+ export function createMcpServer({ store, ledger, loadLedger, loadStore, loadCommitmentView, loadCommitmentRecords, version = '0.0.0', audit, readPack, now = () => new Date(), clearance = 0 } = {}) {
461
487
  const serverVersion = String(version ?? '0.0.0')
462
488
  // Protocol version agreed by the last legacy `initialize` (advisory only:
463
489
  // the legacy method surface is identical for every supported revision).
@@ -474,6 +500,30 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
474
500
  let resolvedLedger = ledger
475
501
  let resolvedStore = store
476
502
  const ledgerCache = new Map()
503
+ // 0.3.2 P2-1: process-level cache of the narrow commitment view, keyed like
504
+ // the legacy ledger cache (the snapshot is taken on first use and reused until
505
+ // the process exits; refresh semantics are unchanged).
506
+ const commitmentViewCache = new Map()
507
+ function commitmentView(options = {}) {
508
+ if (typeof loadCommitmentView !== 'function') return null
509
+ const key = String(options.all === true) + ':' + String(options.clearance ?? clearanceLevel)
510
+ if (commitmentViewCache.has(key)) return commitmentViewCache.get(key)
511
+ const view = loadCommitmentView(options)
512
+ commitmentViewCache.set(key, view)
513
+ return view
514
+ }
515
+ /** Normalize loadCommitmentRecords() output to an id -> record Map. */
516
+ function commitmentRecordsById(ids) {
517
+ const loaded = loadCommitmentRecords(ids)
518
+ if (loaded instanceof Map) return loaded
519
+ const byId = new Map()
520
+ if (Array.isArray(loaded)) {
521
+ for (const record of loaded) {
522
+ if (record && typeof record.id === 'string' && record.id) byId.set(record.id, record)
523
+ }
524
+ }
525
+ return byId
526
+ }
477
527
  function ledgerFor(kind = 'full') {
478
528
  if (resolvedLedger !== undefined) return resolvedLedger
479
529
  if (ledgerCache.has(kind)) return ledgerCache.get(kind)
@@ -544,6 +594,19 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
544
594
  /* ------------------------------ read models ------------------------------ */
545
595
 
546
596
  function todayData() {
597
+ const narrow = commitmentView({ all: false, clearance: clearanceLevel })
598
+ if (narrow) {
599
+ const visible = narrow.rows.filter((row) => !row.hidden)
600
+ const commitments = visible.slice(0, MCP_OUTPUT_LIMITS.todayCommitments)
601
+ return {
602
+ open: visible.length,
603
+ commitments: commitments.map((c) => ({ id: c.id, debtor: c.debtor, creditor: c.creditor, action: c.action, dueAt: c.dueAt })),
604
+ clearance: clearanceLevel,
605
+ protectedExcluded: narrow.protectedExcluded,
606
+ total: visible.length,
607
+ truncated: visible.length > commitments.length,
608
+ }
609
+ }
547
610
  const open = requireLedger('commitments').openCommitments()
548
611
  const view = splitByClearance('commitment', open)
549
612
  // Cap AFTER clearance and BEFORE the egress classifier: `open` and `total`
@@ -560,6 +623,21 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
560
623
  }
561
624
 
562
625
  function commitListData(all, requestedLimit) {
626
+ const narrow = commitmentView({ all: true, clearance: clearanceLevel })
627
+ if (narrow) {
628
+ const statusFiltered = all ? narrow.rows : narrow.rows.filter((row) => row.status === 'open')
629
+ const visible = statusFiltered.filter((row) => !row.hidden)
630
+ const limit = Number.isInteger(requestedLimit) ? requestedLimit : MCP_OUTPUT_LIMITS.commitRows
631
+ const commitments = visible.slice(0, limit)
632
+ return {
633
+ commitments: commitments.map((c) => ({ id: c.id, status: c.status, action: c.action, dueAt: c.dueAt, creditor: c.creditor })),
634
+ clearance: clearanceLevel,
635
+ protectedExcluded: statusFiltered.length - visible.length,
636
+ total: visible.length,
637
+ truncated: visible.length > commitments.length,
638
+ limit,
639
+ }
640
+ }
563
641
  const rows = requireLedger('commitments')
564
642
  .listCommitments()
565
643
  .filter((c) => all || c.status === 'open')
@@ -577,6 +655,30 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
577
655
  }
578
656
 
579
657
  function whoData() {
658
+ const narrow = commitmentView({ all: false, clearance: clearanceLevel })
659
+ if (narrow) {
660
+ const visible = narrow.rows.filter((row) => !row.hidden)
661
+ const mine = visible.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
662
+ const waiting = visible.filter((c) => c.debtor === 'third' || String(c.debtor).startsWith('third:'))
663
+ const limit = MCP_OUTPUT_LIMITS.whoRows
664
+ // who returns full Commitment rows (the frozen v1 shape with
665
+ // evidence/matterId/timezone/...), so hydrate only the capped page.
666
+ const hydrate = (list) => {
667
+ const capped = list.slice(0, limit)
668
+ if (typeof loadCommitmentRecords !== 'function' || !capped.length) return capped
669
+ const byId = commitmentRecordsById(capped.map((row) => row.id))
670
+ return capped.map((row) => byId.get(row.id) ?? row)
671
+ }
672
+ return {
673
+ mine: hydrate(mine),
674
+ waiting: hydrate(waiting),
675
+ clearance: clearanceLevel,
676
+ protectedExcluded: narrow.protectedExcluded,
677
+ mineTotal: mine.length,
678
+ waitingTotal: waiting.length,
679
+ truncated: mine.length > limit || waiting.length > limit,
680
+ }
681
+ }
580
682
  const open = requireLedger('commitments').openCommitments()
581
683
  const view = splitByClearance('commitment', open)
582
684
  const mine = view.visible.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
@@ -594,6 +696,33 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
594
696
  }
595
697
 
596
698
  function remindData() {
699
+ const narrow = commitmentView({ all: true, clearance: clearanceLevel })
700
+ if (narrow) {
701
+ const hiddenIds = new Set()
702
+ for (const row of narrow.rows) if (row.hidden) hiddenIds.add(row.id)
703
+ let reminders
704
+ try {
705
+ // buildReminders only needs listCommitments(); the narrow rows carry the
706
+ // fields it reads (id/action/dueAt/status/reminderOffsets).
707
+ reminders = buildReminders({ listCommitments: () => narrow.rows }, { now: nowDate() })
708
+ } catch {
709
+ throw new ToolError('reminder planning failed')
710
+ }
711
+ const visible = []
712
+ let protectedExcluded = 0
713
+ for (const reminder of reminders) {
714
+ if (hiddenIds.has(reminder.commitmentId)) protectedExcluded += 1
715
+ else visible.push(reminder)
716
+ }
717
+ const capped = visible.slice(0, MCP_OUTPUT_LIMITS.reminders)
718
+ return {
719
+ reminders: capped,
720
+ clearance: clearanceLevel,
721
+ protectedExcluded,
722
+ total: visible.length,
723
+ truncated: visible.length > capped.length,
724
+ }
725
+ }
597
726
  const ledgerApi = requireLedger('commitments')
598
727
  let reminders
599
728
  try {
@@ -700,6 +829,49 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
700
829
  }
701
830
  }
702
831
 
832
+ /* ----------------------------- customer reads ---------------------------- */
833
+
834
+ /**
835
+ * Customer entities are SQLite-only (schema v21). A JSON store (storeFor()
836
+ * returns undefined), a legacy embedder store without the customer API or a
837
+ * store opened before the customer tables existed is a structured ToolError,
838
+ * never a crash and never fake empty data.
839
+ */
840
+ function requireCustomerStore() {
841
+ const storeApi = storeFor()
842
+ if (!storeApi || typeof storeApi.read !== 'function' || typeof storeApi.listClients !== 'function'
843
+ || typeof storeApi.getClient !== 'function' || typeof storeApi.listMattersByClient !== 'function') {
844
+ throw new ToolError('customer data requires the SQLite ledger (ADVISERS_STORE=sqlite)')
845
+ }
846
+ return storeApi
847
+ }
848
+
849
+ function clientsListData(all, requestedLimit) {
850
+ const storeApi = requireCustomerStore()
851
+ const limit = Number.isInteger(requestedLimit) ? requestedLimit : MCP_OUTPUT_LIMITS.clients
852
+ const result = listClientRows(storeApi, { clearance: clearanceLevel, limit, includeArchived: all === true })
853
+ return {
854
+ clients: result.rows,
855
+ total: result.total,
856
+ truncated: result.total > result.rows.length,
857
+ limit: result.limit,
858
+ clearance: clearanceLevel,
859
+ protectedExcluded: result.protectedExcluded,
860
+ }
861
+ }
862
+
863
+ function clientsShowData(args) {
864
+ const id = requireString(args, 'id', { min: 1, max: 120 })
865
+ const timelineLimit = optionalLimit(args, 'timelineLimit', MCP_OUTPUT_LIMITS.clientTimelineMax)
866
+ const view = readClientStatus(requireCustomerStore(), id, {
867
+ clearance: clearanceLevel,
868
+ timelineLimit: timelineLimit === undefined ? MCP_OUTPUT_LIMITS.clientTimeline : timelineLimit,
869
+ openLimit: MCP_OUTPUT_LIMITS.clientOpen,
870
+ })
871
+ if (!view) throw new ToolError('unknown client id')
872
+ return view
873
+ }
874
+
703
875
  /* ------------------------------ write tools ------------------------------ */
704
876
 
705
877
  function captureCandidate(args) {
@@ -834,6 +1006,33 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
834
1006
  annotations: READ_ONLY_ANNOTATIONS,
835
1007
  run: () => remindData(),
836
1008
  },
1009
+ {
1010
+ name: 'advisers_clients',
1011
+ description:
1012
+ 'Read-only customer projection: list active clients (all=true includes archived) or show one client by id. Rows carry exact counts, nextDueAt, clearance and protectedExcluded; show adds project summaries, open mine/waiting items and a derived delivery/commitment timeline. Note text and conversation bodies are never returned. At most ' +
1013
+ MCP_OUTPUT_LIMITS.clients + ' client rows are returned (limit 1..' + MCP_OUTPUT_LIMITS.clientsMax + '); timelineLimit (1..' + MCP_OUTPUT_LIMITS.clientTimelineMax + ') caps the show timeline. ' +
1014
+ CLEARANCE_NOTE,
1015
+ inputSchema: {
1016
+ type: 'object',
1017
+ properties: {
1018
+ action: { type: 'string', enum: ['list', 'show'], description: 'list: client rows; show: one client view.' },
1019
+ id: { type: 'string', description: 'Client id (cl_…). Required when action is show.' },
1020
+ all: { type: 'boolean', description: 'Include archived clients (action=list).' },
1021
+ limit: { type: 'integer', minimum: 1, maximum: MCP_OUTPUT_LIMITS.clientsMax, description: 'Max client rows for action=list (default ' + MCP_OUTPUT_LIMITS.clients + ', max ' + MCP_OUTPUT_LIMITS.clientsMax + ').' },
1022
+ timelineLimit: { type: 'integer', minimum: 1, maximum: MCP_OUTPUT_LIMITS.clientTimelineMax, description: 'Max timeline rows for action=show (default ' + MCP_OUTPUT_LIMITS.clientTimeline + ', max ' + MCP_OUTPUT_LIMITS.clientTimelineMax + ').' },
1023
+ },
1024
+ required: ['action'],
1025
+ },
1026
+ annotations: READ_ONLY_ANNOTATIONS,
1027
+ run: (args) => {
1028
+ const action = optionalEnum(args, 'action', ['list', 'show'], undefined)
1029
+ if (action === undefined) throw invalidParams('action must be one of list, show')
1030
+ if (action === 'list') {
1031
+ return clientsListData(optionalBoolean(args, 'all'), optionalLimit(args, 'limit', MCP_OUTPUT_LIMITS.clientsMax))
1032
+ }
1033
+ return clientsShowData(args)
1034
+ },
1035
+ },
837
1036
  { ...CAPTURE_TOOL, run: (args) => captureCandidate(args) },
838
1037
  { ...PACK_VERIFY_TOOL, run: (args) => verifyReceipt(args) },
839
1038
  ].map((tool) => ({ ...tool, write: tool.write === true }))
@@ -992,6 +1191,7 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
992
1191
  if (uri === 'advisers://today') data = todayData()
993
1192
  else if (uri === 'advisers://commitments') data = commitListData(true)
994
1193
  else if (uri === 'advisers://who') data = whoData()
1194
+ else if (uri === 'advisers://clients') data = clientsListData(false)
995
1195
  else data = evidenceIndex()
996
1196
  await recordAudit({ actor: 'mcp', action: 'mcp.call', allowed: true, reason: 'resource:' + uri })
997
1197
  const bounded = boundPayload(data)
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Offline verifier for Advisers delivery receipt packs (format v1.1).
2
+ * Offline verifier for Advisers delivery receipt packs (manifest v1 and v2).
3
3
  *
4
4
  * A receipt pack is a directory produced by buildReceiptPack in lib/evidence.js:
5
5
  *
@@ -43,9 +43,11 @@ import {
43
43
  MAX_QUOTE_CHARS,
44
44
  RECEIPT_DELIVERIES_PREFIX,
45
45
  RECEIPT_MANIFEST_FORMAT,
46
- RECEIPT_MANIFEST_VERSION,
46
+ RECEIPT_MANIFEST_VERSIONS,
47
47
  RECEIPT_REQUIRED_FILES,
48
+ RECEIPT_SCOPES,
48
49
  RECEIPT_SHA256SUMS_FILE,
50
+ RECEIPT_SUBJECT_KINDS,
49
51
  isUnsafePackPath,
50
52
  sha256Hex,
51
53
  } from './evidence.js'
@@ -127,6 +129,10 @@ function isNonNegativeInteger(value) {
127
129
  return Number.isInteger(value) && value >= 0
128
130
  }
129
131
 
132
+ function isNonEmptyString(value) {
133
+ return typeof value === 'string' && value.length > 0
134
+ }
135
+
130
136
  /**
131
137
  * Parse the strict receipt-pack SHA256SUMS format. SHA256SUMS must not list
132
138
  * itself (it cannot contain its own digest).
@@ -292,7 +298,7 @@ function checkDocxStructure(file, limits) {
292
298
  return { zip, hasDocument, bytes }
293
299
  }
294
300
 
295
- // --- manifest schema (format v1; keep it in sync with buildReceiptPack) ------
301
+ // --- manifest schema (format v1/v2; keep it in sync with buildReceiptPack) ----
296
302
 
297
303
  function validateGenerator(generator, errors) {
298
304
  if (!isPlainObject(generator)) {
@@ -327,12 +333,72 @@ function validateRecipient(recipient, errors) {
327
333
  }
328
334
  }
329
335
 
330
- function validateDelivery(delivery, index, sums, deliveryFiles, errors) {
336
+ // --- manifest v2 additions (subject / scope / row-level lineage) -------------
337
+
338
+ function validateSubject(subject, errors) {
339
+ const where = 'manifest.subject'
340
+ if (!isPlainObject(subject)) {
341
+ addError(errors, 'schema: ' + where + ' must be an object')
342
+ return
343
+ }
344
+ if (!RECEIPT_SUBJECT_KINDS.includes(subject.kind)) {
345
+ addError(errors, 'schema: ' + where + '.kind must be one of ' + RECEIPT_SUBJECT_KINDS.map((kind) => '"' + kind + '"').join(', '))
346
+ }
347
+ if (subject.kind === 'none') {
348
+ if ('id' in subject || 'name' in subject) {
349
+ addError(errors, "schema: " + where + " must not carry id/name when kind is 'none'")
350
+ }
351
+ return
352
+ }
353
+ for (const key of ['id', 'name']) {
354
+ if (key in subject && !isNonEmptyString(subject[key])) {
355
+ addError(errors, 'schema: ' + where + '.' + key + ' must be a non-empty string')
356
+ }
357
+ }
358
+ if (!isNonEmptyString(subject.id) && !isNonEmptyString(subject.name)) {
359
+ addError(errors, 'schema: ' + where + ' requires at least one of id/name')
360
+ }
361
+ }
362
+
363
+ function validateScope(scope, errors) {
364
+ if (!RECEIPT_SCOPES.includes(scope)) {
365
+ addError(errors, 'schema: manifest.scope must be one of ' + RECEIPT_SCOPES.map((value) => '"' + value + '"').join(', '))
366
+ }
367
+ }
368
+
369
+ /** v2-only row lineage. v1 rows keep their exact old validation. */
370
+ function validateDeliveryLineage(delivery, where, errors) {
371
+ for (const key of ['clientId', 'projectId', 'matterId']) {
372
+ if (key in delivery && !isNonEmptyString(delivery[key])) {
373
+ addError(errors, 'schema: ' + where + '.' + key + ' must be a non-empty string')
374
+ }
375
+ }
376
+ if (!('template' in delivery)) return
377
+ const template = delivery.template
378
+ if (!isPlainObject(template)) {
379
+ addError(errors, 'schema: ' + where + '.template must be an object')
380
+ return
381
+ }
382
+ for (const key of ['name', 'version']) {
383
+ if (!isNonEmptyString(template[key])) {
384
+ addError(errors, 'schema: ' + where + '.template.' + key + ' must be a non-empty string')
385
+ }
386
+ }
387
+ if ('quoteNo' in template && !isNonEmptyString(template.quoteNo)) {
388
+ addError(errors, 'schema: ' + where + '.template.quoteNo must be a non-empty string')
389
+ }
390
+ if ('dataSha256' in template && !isSha256Hex(template.dataSha256)) {
391
+ addError(errors, 'schema: ' + where + '.template.dataSha256 must be 64 lowercase hex characters')
392
+ }
393
+ }
394
+
395
+ function validateDelivery(delivery, index, sums, deliveryFiles, errors, version) {
331
396
  const where = 'manifest.deliveries[' + index + ']'
332
397
  if (!isPlainObject(delivery)) {
333
398
  addError(errors, 'schema: ' + where + ' must be an object')
334
399
  return
335
400
  }
401
+ if (version === 2) validateDeliveryLineage(delivery, where, errors)
336
402
  if (typeof delivery.id !== 'string' || !delivery.id) addError(errors, 'schema: ' + where + '.id must be a non-empty string')
337
403
  if (!('title' in delivery) || !(delivery.title === null || typeof delivery.title === 'string')) {
338
404
  addError(errors, 'schema: ' + where + '.title must be a string or null')
@@ -550,12 +616,23 @@ function validateReceiptManifest(manifest, sums, errors, result) {
550
616
  if (manifest.format !== RECEIPT_MANIFEST_FORMAT) {
551
617
  addError(errors, 'schema: manifest.format must be ' + RECEIPT_MANIFEST_FORMAT)
552
618
  }
553
- if (manifest.version !== RECEIPT_MANIFEST_VERSION) {
554
- addError(errors, 'schema: manifest.version must be ' + RECEIPT_MANIFEST_VERSION)
619
+ // v1 packs were written by 0.2.x/0.3.x and must keep verifying exactly as
620
+ // before; v2 adds subject/scope/lineage checks below. Anything else is drift.
621
+ if (!RECEIPT_MANIFEST_VERSIONS.includes(manifest.version)) {
622
+ addError(
623
+ errors,
624
+ 'schema: manifest.version must be ' + RECEIPT_MANIFEST_VERSIONS.join(' or ') + ' (got ' + JSON.stringify(manifest.version) + ')',
625
+ )
555
626
  }
556
627
  if (!isIsoDate(manifest.createdAt)) addError(errors, 'schema: manifest.createdAt must be an ISO-8601 UTC timestamp')
557
628
  validateGenerator(manifest.generator, errors)
558
629
  validateRecipient(manifest.recipient, errors)
630
+ const version = manifest.version
631
+ if (version === 2) {
632
+ if (!('scope' in manifest)) addError(errors, 'schema: manifest.scope is required for manifest version 2')
633
+ else validateScope(manifest.scope, errors)
634
+ if ('subject' in manifest) validateSubject(manifest.subject, errors)
635
+ }
559
636
 
560
637
  const deliveryFiles = new Map()
561
638
  if (!Array.isArray(manifest.deliveries) || manifest.deliveries.length === 0) {
@@ -567,7 +644,7 @@ function validateReceiptManifest(manifest, sums, errors, result) {
567
644
  if (ids.has(delivery.id)) addError(errors, 'schema: manifest.deliveries[' + index + '].id is duplicated: ' + delivery.id)
568
645
  else ids.add(delivery.id)
569
646
  }
570
- validateDelivery(delivery, index, sums, deliveryFiles, errors)
647
+ validateDelivery(delivery, index, sums, deliveryFiles, errors, version)
571
648
  })
572
649
  }
573
650
 
package/lib/sqlite.js CHANGED
@@ -2293,6 +2293,63 @@ CREATE TABLE IF NOT EXISTS task_runs (
2293
2293
  return this.db.prepare(sql).all(...params, limit).map(mapDeliveryRow)
2294
2294
  }
2295
2295
 
2296
+ /**
2297
+ * Delivery rows for one receipt subject (0.3.2): row ownership by the
2298
+ * subject's current matter ids OR the generation-time client/project
2299
+ * snapshot columns. The union is deliberate — a delivery recorded for the
2300
+ * client stays scoped to it even after the matter is re-linked, and a row
2301
+ * whose lineage is missing is found through its matter.
2302
+ *
2303
+ * @param {{clientId?: string|null, projectId?: string|null, matterIds?: string[], limit?: number}} [scope]
2304
+ */
2305
+ listDeliveriesForScope({ clientId = null, projectId = null, matterIds = [], limit = 100 } = {}) {
2306
+ const clauses = []
2307
+ const params = []
2308
+ const ids = Array.isArray(matterIds) ? matterIds.filter((id) => typeof id === 'string' && id) : []
2309
+ if (ids.length) {
2310
+ clauses.push('matter_id IN (' + ids.map(() => '?').join(',') + ')')
2311
+ params.push(...ids)
2312
+ }
2313
+ if (clientId !== null && clientId !== undefined && clientId !== '') {
2314
+ clauses.push('client_id = ?')
2315
+ params.push(clientId)
2316
+ }
2317
+ if (projectId !== null && projectId !== undefined && projectId !== '') {
2318
+ clauses.push('project_id = ?')
2319
+ params.push(projectId)
2320
+ }
2321
+ if (!clauses.length) return []
2322
+ const sql = 'SELECT * FROM deliveries WHERE (' + clauses.join(' OR ') + ') ORDER BY created_at DESC, rowid DESC LIMIT ?'
2323
+ return this.db.prepare(sql).all(...params, limit).map(mapDeliveryRow)
2324
+ }
2325
+
2326
+ /**
2327
+ * Count delivery rows for one receipt subject without loading files.
2328
+ * Mirrors listDeliveriesForScope's scope predicate; receipt packs themselves
2329
+ * are excluded so a new receipt cannot count older receipt packs.
2330
+ */
2331
+ countDeliveriesForScope({ clientId = null, projectId = null, matterIds = [], excludeReceiptPacks = true } = {}) {
2332
+ const scopeClauses = []
2333
+ const params = []
2334
+ const ids = Array.isArray(matterIds) ? matterIds.filter((id) => typeof id === 'string' && id) : []
2335
+ if (ids.length) {
2336
+ scopeClauses.push('matter_id IN (' + ids.map(() => '?').join(',') + ')')
2337
+ params.push(...ids)
2338
+ }
2339
+ if (clientId !== null && clientId !== undefined && clientId !== '') {
2340
+ scopeClauses.push('client_id = ?')
2341
+ params.push(clientId)
2342
+ }
2343
+ if (projectId !== null && projectId !== undefined && projectId !== '') {
2344
+ scopeClauses.push('project_id = ?')
2345
+ params.push(projectId)
2346
+ }
2347
+ if (!scopeClauses.length) return 0
2348
+ const clauses = ['(' + scopeClauses.join(' OR ') + ')']
2349
+ if (excludeReceiptPacks) clauses.push("COALESCE(tool, '') != 'receipt-pack'")
2350
+ return this.db.prepare('SELECT COUNT(*) AS n FROM deliveries WHERE ' + clauses.join(' AND ')).get(...params).n
2351
+ }
2352
+
2296
2353
  getMeta(key) {
2297
2354
  return this.db.prepare('SELECT value FROM meta WHERE key = ?').get(key)?.value
2298
2355
  }
@@ -3789,6 +3846,84 @@ CREATE TABLE IF NOT EXISTS task_runs (
3789
3846
  return this._project('SELECT DISTINCT creditor FROM commitments', [], (row) => row[0])
3790
3847
  }
3791
3848
 
3849
+ /**
3850
+ * MCP narrow commitment read model (0.3.2 P2-1).
3851
+ *
3852
+ * The four MCP list tools (today / commit_ls / who / remind) previously mapped
3853
+ * every commitment entity (`SELECT *` + JSON.parse per row + a Ledger Map) just
3854
+ * to drop almost all rows before serialization. This projection selects only
3855
+ * the eight columns those read models need and applies the per-item clearance
3856
+ * gate here, in rowid (insertion) order:
3857
+ *
3858
+ * - `WHERE status = 'open'` when `all` is false; every status otherwise;
3859
+ * - `NOT INDEXED` keeps the natural table/rowid order, which is exactly the
3860
+ * order `loadCommitments()` (+ its `ORDER BY rowid`) used to produce, so the
3861
+ * MCP output stays byte-identical;
3862
+ * - `hidden = secrecy > clearance`. The secrecy rule mirrors
3863
+ * `lib/evidence.js` `evidenceRecordSecrecy()` exactly: no matter id -> 0, a
3864
+ * matter id missing from the matters table -> Infinity, a null/non-finite
3865
+ * matter secrecy -> 0/Infinity (fail closed);
3866
+ * - `reminder_offsets` is parsed only when it is a JSON array, matching
3867
+ * `mapCommitmentRow` (remind needs the custom offsets).
3868
+ *
3869
+ * `total` is the number of scanned rows (visible + hidden); subtract
3870
+ * `protectedExcluded` for the visible count. No write, no schema/index change.
3871
+ *
3872
+ * @param {{ all?: boolean, clearance?: number }} [options]
3873
+ * @returns {{rows: Array<object>, total: number, protectedExcluded: number}}
3874
+ */
3875
+ projectCommitmentReadModel({ all = false, clearance = 0 } = {}) {
3876
+ const sql = all
3877
+ ? 'SELECT id, debtor, creditor, action, due_at, status, matter_id, reminder_offsets FROM commitments NOT INDEXED'
3878
+ : "SELECT id, debtor, creditor, action, due_at, status, matter_id, reminder_offsets FROM commitments NOT INDEXED WHERE status = 'open'"
3879
+ const statement = this.db.prepare(sql)
3880
+ if (typeof statement.setReturnArrays === 'function') statement.setReturnArrays(true)
3881
+ const raw = statement.all()
3882
+ const matterRows = this.db.prepare('SELECT id, secrecy FROM matters').all()
3883
+ const secrecyById = new Map()
3884
+ for (const matter of matterRows) secrecyById.set(matter.id, matter.secrecy)
3885
+ const numericClearance = Number(clearance)
3886
+ const level = Number.isFinite(numericClearance) && numericClearance >= 0 ? numericClearance : 0
3887
+ const rows = []
3888
+ let protectedExcluded = 0
3889
+ for (const row of raw) {
3890
+ const matterId = row[6]
3891
+ let secrecy = 0
3892
+ if (typeof matterId === 'string' && matterId) {
3893
+ if (!secrecyById.has(matterId)) {
3894
+ secrecy = Number.POSITIVE_INFINITY
3895
+ } else {
3896
+ const matterLevel = Number(secrecyById.get(matterId))
3897
+ secrecy = Number.isFinite(matterLevel) ? matterLevel : Number.POSITIVE_INFINITY
3898
+ }
3899
+ }
3900
+ const hidden = secrecy > level
3901
+ if (hidden) protectedExcluded += 1
3902
+ let offsets
3903
+ if (row[7] != null) {
3904
+ try {
3905
+ const parsed = JSON.parse(row[7])
3906
+ if (Array.isArray(parsed)) offsets = parsed
3907
+ } catch {
3908
+ // Corrupt JSON degrades to "no custom offsets", exactly like mapCommitmentRow.
3909
+ }
3910
+ }
3911
+ rows.push({
3912
+ id: row[0],
3913
+ debtor: row[1],
3914
+ creditor: row[2],
3915
+ action: row[3],
3916
+ dueAt: row[4] ?? undefined,
3917
+ status: row[5],
3918
+ matterId: row[6] ?? undefined,
3919
+ ...(offsets === undefined ? {} : { reminderOffsets: offsets }),
3920
+ hidden,
3921
+ })
3922
+ }
3923
+ return { rows, total: rows.length, protectedExcluded }
3924
+ }
3925
+
3926
+
3792
3927
  loadPreferences({ status, kind } = {}) {
3793
3928
  const where = []
3794
3929
  const params = []
package/lib/tui/labels.js CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * 0.3.0 ships Simplified Chinese human-facing text. This table is the kernel's single
5
5
  * place for display words so callers can inject a different table (tests use it to
6
- * prove no bare literals leak into render logic) and so the 0.3.1 i18n seam can
6
+ * prove no bare literals leak into render logic) and so the 0.3.2 i18n seam can
7
7
  * re-export or replace it without touching render.js.
8
8
  *
9
9
  * Machine-facing strings (command names, flags, JSON keys, error codes) are English
package/lib/tui/render.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * and the read-only snapshot. No I/O, no readline, no clock, no store access.
4
4
  *
5
5
  * The same functions serve three consumers, which is the point of the kernel:
6
- * - the future interactive shell (0.3.1) and the existing CLI human output;
6
+ * - the future interactive shell (0.3.2) and the existing CLI human output;
7
7
  * - --once / redirected / --plain / --accessible byte snapshots;
8
8
  * - golden unit tests.
9
9
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "advisers",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "A staff of AI advisers: a cordis-native personal secretary runtime with scoped memory, commitments, and reviewable routines.",
5
5
  "keywords": [
6
6
  "cordis",
@@ -36,8 +36,8 @@
36
36
  ],
37
37
  "dependencies": {
38
38
  "@pdf-lib/fontkit": "^1.1.1",
39
- "advisers-core": "0.3.0",
40
- "advisers-policy-strict": "0.3.0",
39
+ "advisers-core": "0.3.2",
40
+ "advisers-policy-strict": "0.3.2",
41
41
  "jszip": "^3.10.2",
42
42
  "pdf-lib": "^1.17.1",
43
43
  "pdfjs-dist": "^6.5.438"
@@ -61,7 +61,7 @@
61
61
  "test": "node --experimental-strip-types --test test/*.test.js"
62
62
  },
63
63
  "peerDependencies": {
64
- "advisers-office": "0.3.0"
64
+ "advisers-office": "0.3.2"
65
65
  },
66
66
  "peerDependenciesMeta": {
67
67
  "advisers-office": {