advisers 0.3.1 → 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/evidence.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * E3: evidence chain, evidence pack (v1) and delivery receipt pack (v1.1).
2
+ * E3: evidence chain, evidence pack (v1) and delivery receipt pack
3
+ * (v1.1 / manifest v2).
3
4
  *
4
5
  * Every ledger row that claims something about the world must point back to the
5
6
  * conversation turn it came from. This module walks those pointers (a turn is
@@ -1141,7 +1142,7 @@ export function verifyPack(files) {
1141
1142
  }
1142
1143
 
1143
1144
  // ---------------------------------------------------------------------------
1144
- // delivery receipt pack v1.1
1145
+ // delivery receipt pack v1.1 / manifest v2
1145
1146
  //
1146
1147
  // Competitive report 21-w2-delivery-trust.md §2.2 and hardening
1147
1148
  // 13-gap-inventory.md P1-2: the evidence pack above is an evidence pack; a
@@ -1155,7 +1156,20 @@ export function verifyPack(files) {
1155
1156
  // ---------------------------------------------------------------------------
1156
1157
 
1157
1158
  export const RECEIPT_MANIFEST_FORMAT = 'advisers-delivery-receipt-pack'
1158
- export const RECEIPT_MANIFEST_VERSION = 1
1159
+ /**
1160
+ * Current manifest version written by buildReceiptPack. v2 adds the optional
1161
+ * top-level `subject` and the mandatory `scope`, plus optional row-level
1162
+ * lineage (`clientId`/`projectId`/`matterId`/`template`). v1 packs stay
1163
+ * verifiable: lib/receipt-verify.js accepts every version in
1164
+ * RECEIPT_MANIFEST_VERSIONS.
1165
+ */
1166
+ export const RECEIPT_MANIFEST_VERSION = 2
1167
+ /** Manifest versions the offline verifier accepts (v1 packs must keep verifying). */
1168
+ export const RECEIPT_MANIFEST_VERSIONS = Object.freeze([1, 2])
1169
+ /** Allowed manifest.subject.kind values (manifest v2). */
1170
+ export const RECEIPT_SUBJECT_KINDS = Object.freeze(['client', 'project', 'matter', 'none'])
1171
+ /** Allowed manifest.scope values (manifest v2). */
1172
+ export const RECEIPT_SCOPES = Object.freeze(['subject', 'local-all'])
1159
1173
  export const RECEIPT_SHA256SUMS_FILE = 'SHA256SUMS'
1160
1174
  /** Files every receipt pack must carry; SHA256SUMS covers all of them. */
1161
1175
  export const RECEIPT_REQUIRED_FILES = Object.freeze(['manifest.json', 'README.txt', 'receipt.docx'])
@@ -1292,6 +1306,65 @@ function normalizeDeliveryFile(file, deliveryId, fileIndex) {
1292
1306
  throw new TypeError('delivery ' + deliveryId + ' file #' + (fileIndex + 1) + ' must be a path string or an object')
1293
1307
  }
1294
1308
 
1309
+ // --- optional row-level lineage (manifest v2) --------------------------------
1310
+
1311
+ /**
1312
+ * Validate one optional delivery lineage id. Empty/null means "not recorded"
1313
+ * and keeps the v1 manifest shape (the key is not written at all).
1314
+ */
1315
+ function receiptLineageId(value, deliveryId, field) {
1316
+ if (value === undefined || value === null || value === '') return null
1317
+ if (typeof value !== 'string') {
1318
+ throw new TypeError('delivery ' + deliveryId + ' ' + field + ' must be a non-empty string')
1319
+ }
1320
+ const text = value.trim()
1321
+ if (!text) throw new TypeError('delivery ' + deliveryId + ' ' + field + ' must be a non-empty string')
1322
+ return text
1323
+ }
1324
+
1325
+ function receiptLineageString(value, deliveryId, field) {
1326
+ if (value === undefined || value === null || value === '') return null
1327
+ if (typeof value !== 'string' || !value.trim()) {
1328
+ throw new TypeError('delivery ' + deliveryId + ' ' + field + ' must be a non-empty string')
1329
+ }
1330
+ return value.trim()
1331
+ }
1332
+
1333
+ /**
1334
+ * Row-level template lineage: flat templateName/templateVersion/quoteNo/
1335
+ * dataSha256 inputs become one manifest.deliveries[].template object. Nothing is
1336
+ * written when the row carries none of them. name+version identify a template,
1337
+ * so a partial pair is rejected instead of silently recorded.
1338
+ */
1339
+ function receiptDeliveryTemplate(delivery, deliveryId) {
1340
+ const anyPresent = ['templateName', 'templateVersion', 'quoteNo', 'dataSha256'].some(
1341
+ (key) => delivery[key] !== undefined && delivery[key] !== null && delivery[key] !== '',
1342
+ )
1343
+ if (!anyPresent) return null
1344
+ const name = receiptLineageString(delivery.templateName, deliveryId, 'templateName')
1345
+ const version = receiptLineageString(delivery.templateVersion, deliveryId, 'templateVersion')
1346
+ if (name === null || version === null) {
1347
+ throw new TypeError(
1348
+ 'delivery ' + deliveryId + ' template lineage requires both templateName and templateVersion' +
1349
+ ' (quoteNo/dataSha256 are additional and optional)',
1350
+ )
1351
+ }
1352
+ const template = { name, version }
1353
+ const quoteNo = receiptLineageString(delivery.quoteNo, deliveryId, 'quoteNo')
1354
+ if (quoteNo !== null) template.quoteNo = quoteNo
1355
+ if (delivery.dataSha256 !== undefined && delivery.dataSha256 !== null && delivery.dataSha256 !== '') {
1356
+ if (typeof delivery.dataSha256 !== 'string') {
1357
+ throw new TypeError('delivery ' + deliveryId + ' dataSha256 must be 64 lowercase hex characters')
1358
+ }
1359
+ const dataSha256 = delivery.dataSha256.trim().toLowerCase()
1360
+ if (!isSha256Hex(dataSha256)) {
1361
+ throw new TypeError('delivery ' + deliveryId + ' dataSha256 must be 64 lowercase hex characters')
1362
+ }
1363
+ template.dataSha256 = dataSha256
1364
+ }
1365
+ return template
1366
+ }
1367
+
1295
1368
  function normalizeReceiptDeliveries(deliveries) {
1296
1369
  const input = Array.isArray(deliveries) ? deliveries : deliveries ? [deliveries] : []
1297
1370
  if (!input.length) {
@@ -1341,6 +1414,11 @@ function normalizeReceiptDeliveries(deliveries) {
1341
1414
  tool: receiptText(delivery.tool),
1342
1415
  createdAt: receiptDateText(delivery.createdAt !== undefined ? delivery.createdAt : delivery.created_at, null),
1343
1416
  validation,
1417
+ // Manifest v2 lineage: null means "not recorded" and is never written.
1418
+ clientId: receiptLineageId(delivery.clientId, id, 'clientId'),
1419
+ projectId: receiptLineageId(delivery.projectId, id, 'projectId'),
1420
+ matterId: receiptLineageId(delivery.matterId, id, 'matterId'),
1421
+ template: receiptDeliveryTemplate(delivery, id),
1344
1422
  files,
1345
1423
  }
1346
1424
  })
@@ -1622,6 +1700,73 @@ function normalizeReceiptAnchors(anchors) {
1622
1700
  })
1623
1701
  }
1624
1702
 
1703
+ // --- subject / scope (manifest v2) ------------------------------------------
1704
+
1705
+ /**
1706
+ * Normalize the optional manifest.subject.
1707
+ *
1708
+ * `{kind:'client'|'project'|'matter', id?, name?}` needs at least one of
1709
+ * id/name; `{kind:'none'}` explicitly declares "no single subject" and must
1710
+ * not carry id/name. Unknown kinds, wrong types and empty strings fail closed
1711
+ * (returning `null` would silently drop a claim the caller asked to record).
1712
+ *
1713
+ * @returns {{kind: string, id?: string, name?: string}|null}
1714
+ */
1715
+ function normalizeReceiptSubject(subject) {
1716
+ if (subject === undefined || subject === null || subject === '') return null
1717
+ if (typeof subject !== 'object' || Array.isArray(subject)) {
1718
+ throw new TypeError('subject must be an object {kind, id?, name?}')
1719
+ }
1720
+ if (!RECEIPT_SUBJECT_KINDS.includes(subject.kind)) {
1721
+ throw new TypeError(
1722
+ 'subject.kind must be one of ' + RECEIPT_SUBJECT_KINDS.map((kind) => "'" + kind + "'").join(', '),
1723
+ )
1724
+ }
1725
+ const subjectField = (value, field) => {
1726
+ if (value === undefined || value === null || value === '') return null
1727
+ if (typeof value !== 'string' || !value.trim()) {
1728
+ throw new TypeError('subject.' + field + ' must be a non-empty string')
1729
+ }
1730
+ return value.trim()
1731
+ }
1732
+ const id = subjectField(subject.id, 'id')
1733
+ const name = subjectField(subject.name, 'name')
1734
+ if (subject.kind === 'none') {
1735
+ if (id !== null || name !== null) throw new TypeError("subject.kind 'none' must not carry id or name")
1736
+ return { kind: 'none' }
1737
+ }
1738
+ if (id === null && name === null) {
1739
+ throw new TypeError("subject.kind '" + subject.kind + "' requires subject.id or subject.name")
1740
+ }
1741
+ const out = { kind: subject.kind }
1742
+ if (id !== null) out.id = id
1743
+ if (name !== null) out.name = name
1744
+ return out
1745
+ }
1746
+
1747
+ /**
1748
+ * Normalize manifest scope (v2 mandatory field).
1749
+ *
1750
+ * Default: a subject with kind client/project/matter means 'subject'; no
1751
+ * subject (or `{kind:'none'}`) means 'local-all'. Contradictory explicit
1752
+ * combinations fail closed instead of producing a pack whose warning lies.
1753
+ */
1754
+ function normalizeReceiptScope(scope, subject) {
1755
+ if (scope === undefined || scope === null || scope === '') {
1756
+ return subject && subject.kind !== 'none' ? 'subject' : 'local-all'
1757
+ }
1758
+ if (scope !== 'subject' && scope !== 'local-all') {
1759
+ throw new TypeError("scope must be 'subject' or 'local-all'")
1760
+ }
1761
+ if (scope === 'subject' && (!subject || subject.kind === 'none')) {
1762
+ throw new TypeError("scope 'subject' requires a subject with kind 'client', 'project' or 'matter'")
1763
+ }
1764
+ if (scope === 'local-all' && subject && subject.kind !== 'none') {
1765
+ throw new TypeError("scope 'local-all' cannot carry a subject with kind 'client', 'project' or 'matter'")
1766
+ }
1767
+ return scope
1768
+ }
1769
+
1625
1770
  // --- minimal deterministic DOCX writer (fallback when advisers-office is not
1626
1771
  // --- installed; a DOCX is a ZIP with [Content_Types].xml + word/document.xml) ----
1627
1772
 
@@ -1790,6 +1935,39 @@ function receiptRecipientLabel(recipient) {
1790
1935
  return parts.length ? parts.join(' ') : 'recorded (see manifest.json)'
1791
1936
  }
1792
1937
 
1938
+ /** Human label for manifest.subject: "<kind> <name> (<id>)". */
1939
+ function receiptSubjectLabel(subject) {
1940
+ if (!subject) return 'none'
1941
+ const label = subject.name && subject.id ? subject.name + ' (' + subject.id + ')' : subject.name || subject.id || ''
1942
+ return (subject.kind + ' ' + label).trim()
1943
+ }
1944
+
1945
+ /**
1946
+ * The one place that turns scope + subject into the Chinese/English warning
1947
+ * printed by README.txt and receipt.docx. Keeping it here makes the two
1948
+ * documents unable to disagree about what the pack contains.
1949
+ */
1950
+ function receiptScopeLines(subject, scope) {
1951
+ if (scope === 'subject' && subject && subject.kind !== 'none') {
1952
+ const label = receiptSubjectLabel(subject)
1953
+ return {
1954
+ zh: '本包只含 ' + label + ' 的数据,全局 facts/preferences 默认不含。',
1955
+ en: 'This pack contains only the data of ' + label + '; global facts/preferences are not included by default.',
1956
+ }
1957
+ }
1958
+ return {
1959
+ zh: '本包含本机全部客户数据,勿直接发给第三方。',
1960
+ en: 'This pack contains all customer data on this machine; do not send it directly to a third party.',
1961
+ }
1962
+ }
1963
+
1964
+ function receiptScopeHeaderLine(subject, scope) {
1965
+ if (scope === 'subject' && subject && subject.kind !== 'none') {
1966
+ return 'subject (only ' + receiptSubjectLabel(subject) + '; global facts/preferences not included by default)'
1967
+ }
1968
+ return 'local-all (ALL customer data on this machine; do not send it to a third party)'
1969
+ }
1970
+
1793
1971
  function receiptDocxSpec(input) {
1794
1972
  const {
1795
1973
  createdAt,
@@ -1802,7 +1980,10 @@ function receiptDocxSpec(input) {
1802
1980
  anchors,
1803
1981
  deliveryFiles,
1804
1982
  receiptSha256,
1983
+ subject,
1984
+ scope,
1805
1985
  } = input
1986
+ const scopeLines = receiptScopeLines(subject, scope)
1806
1987
  const summary = [
1807
1988
  '包格式:' + RECEIPT_MANIFEST_FORMAT + ' v' + RECEIPT_MANIFEST_VERSION,
1808
1989
  '生成时间:' + createdAt,
@@ -1810,6 +1991,8 @@ function receiptDocxSpec(input) {
1810
1991
  '生成环境:Advisers ' + (generator.advisersVersion || 'unknown') + ' / Node ' + generator.nodeVersion + ' / ' + generator.platform,
1811
1992
  '模板:' + (generator.templateName ? generator.templateName + (generator.templateVersion ? '@' + generator.templateVersion : '') : '未记录'),
1812
1993
  '交付:' + deliveries.length + ' 项 / 文件 ' + deliveryFiles.length + ' 个',
1994
+ '数据范围:' + scopeLines.zh,
1995
+ 'Scope: ' + scopeLines.en,
1813
1996
  '校验结果:' + (verifyStatus === 'passed' ? '通过' : verifyStatus === 'failed' ? '未通过' : '未记录'),
1814
1997
  '时间锚:' + (anchors.length ? anchors.length + ' 条(外部锚,需按适配器另行验证)' : '未锚定(仅本地自证)'),
1815
1998
  ]
@@ -1890,7 +2073,8 @@ function buildReceiptSums(fileContents) {
1890
2073
  }
1891
2074
 
1892
2075
  function buildReceiptReadme(input) {
1893
- const { createdAt, generator, recipient, deliveries, evidence, verifyResults, verifyStatus, anchors, manifestDigest } = input
2076
+ const { createdAt, generator, recipient, deliveries, evidence, verifyResults, verifyStatus, anchors, manifestDigest, subject, scope } = input
2077
+ const scopeLines = receiptScopeLines(subject, scope)
1894
2078
  const lines = [
1895
2079
  'Advisers delivery receipt pack',
1896
2080
  '==============================',
@@ -1902,6 +2086,8 @@ function buildReceiptReadme(input) {
1902
2086
  'template: ' + (generator.templateName ? generator.templateName + (generator.templateVersion ? ' v' + generator.templateVersion : '') : 'not recorded'),
1903
2087
  'command: ' + (generator.command || 'not recorded'),
1904
2088
  'deliveries: ' + deliveries.length,
2089
+ 'subject: ' + (subject ? receiptSubjectLabel(subject) : 'none'),
2090
+ 'scope: ' + receiptScopeHeaderLine(subject, scope),
1905
2091
  'verification:' + ' ' + (verifyStatus === 'passed' ? 'passed' : verifyStatus === 'failed' ? 'FAILED' : 'not recorded') + (verifyResults.length ? ' (' + verifyResults.length + ' result(s))' : ''),
1906
2092
  'anchors: ' + (anchors.length ? anchors.length + ' external anchor(s) recorded' : 'NONE - this pack is not externally anchored (local self-attestation only)'),
1907
2093
  '',
@@ -1944,6 +2130,11 @@ function buildReceiptReadme(input) {
1944
2130
  'pack can recompute them. When the anchors line above says NONE, the pack only',
1945
2131
  'proves internal consistency, not when or by whom it was produced.',
1946
2132
  '',
2133
+ 'Scope',
2134
+ '-----',
2135
+ scopeLines.zh,
2136
+ scopeLines.en,
2137
+ '',
1947
2138
  'Privacy and scope',
1948
2139
  '-----------------',
1949
2140
  '- Built locally; no network calls; verification does not open the ledger.',
@@ -2021,18 +2212,34 @@ function writeReceiptPackDir(targetDir, fileContents, { overwrite = false } = {}
2021
2212
  }
2022
2213
 
2023
2214
  /**
2024
- * Build a delivery receipt pack (v1.1).
2215
+ * Build a delivery receipt pack (manifest v2; v1.1 packs still verify offline).
2025
2216
  *
2026
2217
  * The manifest records the delivered files (relative path / size / SHA-256),
2027
2218
  * the generator environment, the verify results, optional recipient and
2028
- * timestamp anchors, and the evidence entries. receipt.docx is generated and
2029
- * both it and every delivered artifact are covered by SHA256SUMS, so
2219
+ * timestamp anchors, and the evidence entries. Manifest v2 adds the optional
2220
+ * `subject`, the mandatory `scope` ('subject' | 'local-all') and optional
2221
+ * row-level lineage. receipt.docx and README.txt both print the scope warning,
2222
+ * and both it and every delivered artifact are covered by SHA256SUMS, so
2030
2223
  * verifyReceiptPackDir can detect any edit or missing file offline.
2031
2224
  *
2225
+ * Backwards compatibility: callers that pass neither `subject` nor `scope`
2226
+ * (e.g. the 0.3.1 CLI) still get a valid pack, now version 2 with
2227
+ * scope 'local-all' and no subject key — the same manifest rows they got
2228
+ * before, plus the all-customer-data warning.
2229
+ *
2032
2230
  * @param {object} options
2033
2231
  * @param {Array|object} options.deliveries delivery record(s): {id, title, tool,
2034
- * createdAt, validation, files}. Each file is a path string, a
2035
- * {sourcePath} object, or a {content, name} object with embedded bytes.
2232
+ * createdAt, validation, files, clientId?, projectId?, matterId?,
2233
+ * templateName?, templateVersion?, quoteNo?, dataSha256?}. Each file is
2234
+ * a path string, a {sourcePath} object, or a {content, name} object with
2235
+ * embedded bytes. Lineage fields are written only when present; a partial
2236
+ * template identity (name without version) is rejected.
2237
+ * @param {{kind: 'client'|'project'|'matter'|'none', id?: string, name?: string}}
2238
+ * [options.subject] optional manifest.subject (v2). Written only when
2239
+ * passed; kind 'none' declares "no single subject" and forbids id/name.
2240
+ * @param {'subject'|'local-all'} [options.scope] pack scope (v2). Defaults to
2241
+ * 'subject' when a client/project/matter subject is given, otherwise
2242
+ * 'local-all'; contradictory combinations are rejected.
2036
2243
  * @param {object|Array|string} [options.evidence] buildEvidencePack output,
2037
2244
  * evidence entries, or an evidence manifest string.
2038
2245
  * @param {object|Array} [options.verifyResults] results with a boolean ok
@@ -2068,6 +2275,8 @@ export async function buildReceiptPack(options = {}) {
2068
2275
  const generator = normalizeReceiptGenerator(options.env)
2069
2276
  const recipient = normalizeReceiptRecipient(options.recipient)
2070
2277
  const anchors = normalizeReceiptAnchors(options.anchors)
2278
+ const subject = normalizeReceiptSubject(options.subject)
2279
+ const scope = normalizeReceiptScope(options.scope, subject)
2071
2280
  const deliveryFiles = []
2072
2281
  for (const delivery of deliveries) for (const file of delivery.files) deliveryFiles.push(file)
2073
2282
 
@@ -2086,6 +2295,8 @@ export async function buildReceiptPack(options = {}) {
2086
2295
  anchors,
2087
2296
  deliveryFiles,
2088
2297
  receiptSha256: 'see SHA256SUMS',
2298
+ subject,
2299
+ scope,
2089
2300
  })
2090
2301
  const receiptBytes =
2091
2302
  options.receiptDocx !== undefined
@@ -2120,12 +2331,20 @@ export async function buildReceiptPack(options = {}) {
2120
2331
  createdAt,
2121
2332
  generator,
2122
2333
  recipient,
2334
+ // v2: scope is always written, subject only when the caller supplied one.
2335
+ ...(subject ? { subject } : {}),
2336
+ scope,
2123
2337
  deliveries: deliveries.map((delivery) => ({
2124
2338
  id: delivery.id,
2125
2339
  title: delivery.title,
2126
2340
  tool: delivery.tool,
2127
2341
  createdAt: delivery.createdAt,
2128
2342
  validation: delivery.validation,
2343
+ // v2 lineage: absent keys keep the v1 row shape byte-clean.
2344
+ ...(delivery.clientId ? { clientId: delivery.clientId } : {}),
2345
+ ...(delivery.projectId ? { projectId: delivery.projectId } : {}),
2346
+ ...(delivery.matterId ? { matterId: delivery.matterId } : {}),
2347
+ ...(delivery.template ? { template: delivery.template } : {}),
2129
2348
  files: delivery.files.map((file) => ({ path: file.path, name: file.name, size: file.size, sha256: file.sha256 })),
2130
2349
  })),
2131
2350
  receipt: receiptFile,
@@ -2151,6 +2370,8 @@ export async function buildReceiptPack(options = {}) {
2151
2370
  verifyStatus,
2152
2371
  anchors,
2153
2372
  manifestDigest,
2373
+ subject,
2374
+ scope,
2154
2375
  })
2155
2376
  fileContents.set('README.txt', readme)
2156
2377
  // Everything except SHA256SUMS itself is covered by SHA256SUMS.
@@ -2162,6 +2383,9 @@ export async function buildReceiptPack(options = {}) {
2162
2383
  format: RECEIPT_MANIFEST_FORMAT,
2163
2384
  version: RECEIPT_MANIFEST_VERSION,
2164
2385
  createdAt,
2386
+ // v2: null (not undefined) so JSON callers see an explicit "no subject".
2387
+ subject: subject || null,
2388
+ scope,
2165
2389
  deliveryCount: deliveries.length,
2166
2390
  fileCount,
2167
2391
  verifyStatus,
@@ -23,7 +23,11 @@
23
23
  // unseal / sync pull inode replacement and a concurrent writer are safe;
24
24
  // - per-item clearance (default 0, fail closed): rows whose matter.secrecy
25
25
  // is above the clearance are excluded and only counted, never partially
26
- // returned.
26
+ // returned;
27
+ // - customer reads (0.3.2 M3): the client list/status projection is derived by
28
+ // lib/customer-read.js inside one read snapshot; customer entities are
29
+ // SQLite-only, so a JSON backend reports customerEntities:false and an
30
+ // empty list instead of inventing rows.
27
31
  //
28
32
  // The API is a versioned contract (docs/LEDGER-READ-API.md): 0.x versions only
29
33
  // add fields/signatures; existing names, shapes and error codes stay stable.
@@ -32,6 +36,7 @@ import { existsSync, readFileSync } from 'node:fs'
32
36
  import { homedir } from 'node:os'
33
37
  import { isAbsolute, join } from 'node:path'
34
38
 
39
+ import { listClientRows, readClientStatus } from './customer-read.js'
35
40
  import { secrecyLevel } from './egress.js'
36
41
  import { evidenceRecordSecrecy } from './evidence.js'
37
42
 
@@ -285,6 +290,20 @@ function normalizeLimit(value) {
285
290
  return limit
286
291
  }
287
292
 
293
+ /**
294
+ * Validate one customer-page limit (clients or timeline rows). The read-only
295
+ * facade caps a customer page at 200 rows even when a caller asks for more, so
296
+ * a single read can never load an unbounded customer projection.
297
+ */
298
+ function normalizeCustomerLimit(value, fallback, label) {
299
+ if (value === undefined || value === null) return fallback
300
+ const limit = Number(value)
301
+ if (!Number.isInteger(limit) || limit < 1) {
302
+ throw new LedgerReadError('E_USAGE', label + ' must be a positive integer when supplied', 'Omit ' + label + ' to use the default; the read-only facade caps customer pages at 200 rows.')
303
+ }
304
+ return Math.min(limit, 200)
305
+ }
306
+
288
307
  function normalizeParts(parts) {
289
308
  if (parts === undefined || parts === null) return null
290
309
  if (!Array.isArray(parts)) throw new LedgerReadError('E_USAGE', 'parts must be an array of wire table names', `Accepted names: ${WIRE_TABLES.join(', ')}.`)
@@ -324,10 +343,15 @@ async function openLedgerHandle(home) {
324
343
  backend: 'json',
325
344
  schemaVersion: null,
326
345
  warnings: [],
346
+ // Customer entities are SQLite-only (schema v21): the legacy JSON ledger has
347
+ // no client/project/note tables. Report that honestly; never invent rows.
348
+ customerEntities: false,
327
349
  close() {},
328
350
  getEntity: (kind, id, clearance) => jsonEntity(ledger, kind, id, clearance),
329
351
  index: (options) => jsonCommitmentIndex(ledger, options),
330
352
  snapshot: (parts) => jsonSnapshot(ledger, parts),
353
+ clientList: () => ({ rows: [], total: 0, limit: null, clearance: 0, protectedExcluded: 0 }),
354
+ clientStatus: () => null,
331
355
  }
332
356
  }
333
357
  if (!existsSync(backend.dbPath)) throw notFoundInHome(backend)
@@ -345,6 +369,9 @@ async function openLedgerHandle(home) {
345
369
  backend: 'sqlite',
346
370
  schemaVersion: store.schemaVersion(),
347
371
  warnings,
372
+ // A read-only open asserts the current schema (v21), so the customer tables
373
+ // exist whenever this handle is returned.
374
+ customerEntities: true,
348
375
  close() { try { store.close() } catch {} },
349
376
  getEntity(kind, id, clearance) {
350
377
  const spec = ENTITY_KINDS[kind]
@@ -356,6 +383,12 @@ async function openLedgerHandle(home) {
356
383
  snapshot(parts) {
357
384
  return store.read(() => store.loadSnapshot(parts))
358
385
  },
386
+ clientList(options) {
387
+ return listClientRows(store, options)
388
+ },
389
+ clientStatus(id, options) {
390
+ return readClientStatus(store, id, options)
391
+ },
359
392
  }
360
393
  }
361
394
 
@@ -598,6 +631,79 @@ export async function readLedgerSnapshot({ home, parts = null } = {}) {
598
631
  }))
599
632
  }
600
633
 
634
+ /**
635
+ * Read-only customer list (0.3.2 M3). Customer entities are SQLite-only: on the
636
+ * legacy JSON backend the result is an empty list with `customerEntities:false`
637
+ * (never invented rows). The list is clearance-filtered per client (matters and
638
+ * client-level note counts above the clearance are counted in
639
+ * `protectedExcluded`, not shown). Note bodies are never returned.
640
+ *
641
+ * @param {{ home?: string, clearance?: number, limit?: number, all?: boolean }} [options]
642
+ * @returns {Promise<{clients:Array<object>, total:number, truncated:boolean,
643
+ * limit:number, clearance:number, protectedExcluded:number,
644
+ * customerEntities:boolean, schemaVersion:number|null, backend:'sqlite'|'json',
645
+ * readAt:string, warnings:string[]}>}
646
+ */
647
+ export async function readClientList({ home, clearance = 0, limit = 20, all = false } = {}) {
648
+ const root = resolveAdvisersHome({ home })
649
+ const level = normalizeClearance(clearance)
650
+ const pageLimit = normalizeCustomerLimit(limit, 20, 'limit')
651
+ return withLedger(root, (handle) => {
652
+ const result = handle.customerEntities === true
653
+ ? handle.clientList({ clearance: level, limit: pageLimit, includeArchived: all === true })
654
+ : { rows: [], total: 0, protectedExcluded: 0 }
655
+ return {
656
+ clients: result.rows,
657
+ total: result.total,
658
+ truncated: result.total > result.rows.length,
659
+ limit: pageLimit,
660
+ clearance: level,
661
+ protectedExcluded: result.protectedExcluded,
662
+ customerEntities: handle.customerEntities === true,
663
+ schemaVersion: handle.schemaVersion,
664
+ backend: handle.backend,
665
+ readAt: new Date().toISOString(),
666
+ warnings: handle.warnings.slice(),
667
+ }
668
+ })
669
+ }
670
+
671
+ /**
672
+ * Read-only customer status by id (0.3.2 M3): client identity, project
673
+ * summaries, exact counts, open mine/waiting items and a derived
674
+ * delivery/commitment timeline. `found:false` (with `view:null`) distinguishes
675
+ * an unknown/archived-by-id client from a gate failure, without throwing.
676
+ *
677
+ * @param {{ home?: string, id: string, clearance?: number, timelineLimit?: number }} [options]
678
+ * @returns {Promise<{found:boolean, view:object|null, clearance:number,
679
+ * customerEntities:boolean, schemaVersion:number|null, backend:'sqlite'|'json',
680
+ * readAt:string, warnings:string[]}>}
681
+ */
682
+ export async function readClientById({ home, id, clearance = 0, timelineLimit = 20 } = {}) {
683
+ const root = resolveAdvisersHome({ home })
684
+ if (typeof id !== 'string' || id.trim() === '') {
685
+ throw new LedgerReadError('E_USAGE', 'id must be a non-empty string', 'Pass the client id (cl_…); list ids with readClientList.')
686
+ }
687
+ const key = id.trim()
688
+ const level = normalizeClearance(clearance)
689
+ const timelinePage = normalizeCustomerLimit(timelineLimit, 20, 'timelineLimit')
690
+ return withLedger(root, (handle) => {
691
+ const view = handle.customerEntities === true
692
+ ? handle.clientStatus(key, { clearance: level, timelineLimit: timelinePage, openLimit: 20 })
693
+ : null
694
+ return {
695
+ found: view !== null && view !== undefined,
696
+ view: view ?? null,
697
+ clearance: level,
698
+ customerEntities: handle.customerEntities === true,
699
+ schemaVersion: handle.schemaVersion,
700
+ backend: handle.backend,
701
+ readAt: new Date().toISOString(),
702
+ warnings: handle.warnings.slice(),
703
+ }
704
+ })
705
+ }
706
+
601
707
  export default Object.freeze({
602
708
  LedgerReadError,
603
709
  resolveAdvisersHome,
@@ -605,4 +711,6 @@ export default Object.freeze({
605
711
  readOpenCommitmentIndex,
606
712
  readEntityById,
607
713
  readLedgerSnapshot,
714
+ readClientList,
715
+ readClientById,
608
716
  })