advisers 0.2.0-preview.71 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/evidence.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * E3: evidence chain and evidence pack.
2
+ * E3: evidence chain, evidence pack (v1) and delivery receipt pack (v1.1).
3
3
  *
4
4
  * Every ledger row that claims something about the world must point back to the
5
5
  * conversation turn it came from. This module walks those pointers (a turn is
@@ -11,8 +11,16 @@
11
11
  * README.txt human summary and verification instructions
12
12
  * SHA256SUMS sha256 of manifest.json and README.txt
13
13
  *
14
+ * `buildReceiptPack` is the delivery-receipt upgrade (competitive report
15
+ * 21-w2-delivery-trust.md §2.2 / hardening 13-gap-inventory.md P1-2). It
16
+ * copies the delivered artifacts, a generated receipt.docx, the evidence
17
+ * entries, the generator environment and the verify results into one directory,
18
+ * and SHA256SUMS covers every file — `lib/receipt-verify.js` verifies such a
19
+ * directory offline.
20
+ *
14
21
  * Constraints baked into the design:
15
- * - Offline: this module only imports node:crypto, injects `store` + `ledger`.
22
+ * - Offline: no network calls; imports only node:crypto/node:fs/node:path (plus
23
+ * an optional in-process `advisers-office` build for the receipt DOCX).
16
24
  * - No fabrication: an unknown turn, a session mismatch or an unparseable
17
25
  * `session#turn` ref goes to `missing`; nothing is guessed.
18
26
  * - No leaks: no absolute filesystem paths, no full turn/transcript bodies and
@@ -20,15 +28,58 @@
20
28
  * - SHA256SUMS is tamper-evidence (accidental/deterministic edits), not a
21
29
  * signature: whoever can rewrite the whole pack can recompute the sums.
22
30
  *
23
- * The directory writer/CLI entry point is intentionally out of scope here.
31
+ * The directory writer/CLI entry point for the evidence pack is intentionally
32
+ * out of scope here. `buildReceiptPack` can optionally write the receipt pack
33
+ * directory itself (`outDir`), because the receipt's 0600 mode is part of the
34
+ * format contract.
24
35
  */
25
36
 
26
- import { createHash } from 'node:crypto'
37
+ import { createHash, randomUUID } from 'node:crypto'
38
+ import {
39
+ chmodSync,
40
+ existsSync,
41
+ mkdirSync,
42
+ readFileSync,
43
+ readdirSync,
44
+ renameSync,
45
+ rmdirSync,
46
+ rmSync,
47
+ statSync,
48
+ writeFileSync,
49
+ } from 'node:fs'
50
+ import { dirname, join, resolve } from 'node:path'
27
51
 
28
52
  /** Quotes are verbatim evidence but capped, so a pack never carries a full body. */
29
53
  export const MAX_QUOTE_CHARS = 500
30
54
  export const MANIFEST_FORMAT = 'advisers-evidence-pack'
31
55
  export const MANIFEST_VERSION = 1
56
+ /**
57
+ * Default cap for the "pack everything" path (0.2.0 performance audit P0-3).
58
+ * A pack built from every row in a large ledger is slow and huge; callers must
59
+ * narrow with `ids` or opt into the full pack explicitly (CLI: --ids / --all).
60
+ */
61
+ export const DEFAULT_MAX_EVIDENCE_ENTRIES = 2000
62
+
63
+ /**
64
+ * Raised instead of silently building an enormous pack. The CLI maps this to a
65
+ * non-zero exit code and prints the hint; library callers can inspect
66
+ * `code`/`count`/`limit` and retry with `all: true` after an explicit
67
+ * user confirmation.
68
+ */
69
+ export class EvidencePackLimitError extends Error {
70
+ constructor(count, limit) {
71
+ super(
72
+ `evidence pack would include ${count} entries (limit ${limit}); ` +
73
+ 'pass --ids to select specific records or --all to build the full pack',
74
+ )
75
+ this.name = 'EvidencePackLimitError'
76
+ this.code = 'EVIDENCE_PACK_TOO_LARGE'
77
+ this.count = count
78
+ this.limit = limit
79
+ this.hint = 'Use --ids cm_...,fact_...,pref_... to narrow the pack, or --all to lift the limit.'
80
+ }
81
+ }
82
+
32
83
  /** Header for the optional DOCX table helper, kept next to the rows it describes. */
33
84
  export const DOCX_EVIDENCE_HEADERS = ['类型', '证据ID', '来源(session#turn)', '摘录', '状态']
34
85
 
@@ -150,11 +201,74 @@ function lookupTurn(store, sessionId, turnId) {
150
201
  }
151
202
 
152
203
  // ---------------------------------------------------------------------------
153
- // ledger lookups (Ledger has no getFact/getCommitment by id)
204
+ // ledger lookups
154
205
  // ---------------------------------------------------------------------------
155
206
 
156
- function findCommitment(ledger, id) {
207
+ /**
208
+ * One-shot id index over a ledger snapshot.
209
+ *
210
+ * `buildEvidencePack` used to call `listFacts()`/`listCommitments()` once per
211
+ * requested id, which made the full pack O(N²): 80k entries took 113.75s
212
+ * (performance audit P0-3). Building the index once turns every per-entry
213
+ * lookup into a Map.get, so the full pack is linear. The same index also stops
214
+ * `classifyKind` from re-scanning the ledger for unprefixed ids.
215
+ *
216
+ * The index is a snapshot: do not reuse it after mutating the ledger.
217
+ *
218
+ * @returns {{commitments: Map<string, object>, facts: Map<string, object>,
219
+ * preferences: Map<string, object>, ledger: object}}
220
+ */
221
+ export function createEvidenceIndex(ledger) {
222
+ const commitments = new Map()
223
+ const facts = new Map()
224
+ const preferences = new Map()
225
+ if (!ledger || typeof ledger !== 'object') return { commitments, facts, preferences, ledger }
226
+
227
+ try {
228
+ if (typeof ledger.listCommitments === 'function') {
229
+ for (const row of ledger.listCommitments() ?? []) if (row?.id) commitments.set(row.id, row)
230
+ }
231
+ } catch {
232
+ // A partial/legacy ledger may not expose commitments; lookups fall back below.
233
+ }
234
+ let historyIndexed = false
235
+ try {
236
+ let rows = []
237
+ if (typeof ledger.listFacts === 'function') {
238
+ try {
239
+ rows = ledger.listFacts(undefined, true) ?? []
240
+ historyIndexed = true
241
+ } catch {
242
+ rows = ledger.listFacts() ?? []
243
+ }
244
+ }
245
+ for (const row of rows) if (row?.id) facts.set(row.id, row)
246
+ } catch {
247
+ // ignore; the snapshot fallback below still runs
248
+ }
249
+ // Last resort used by the non-indexed findFact: the portable snapshot also
250
+ // includes tombstones/history that a filtered listFacts may omit. Only pay for
251
+ // the O(N) snapshot when the history-inclusive scan was not available.
252
+ if (!historyIndexed && typeof ledger.toJSON === 'function') {
253
+ try {
254
+ for (const row of ledger.toJSON()?.facts ?? []) if (row?.id && !facts.has(row.id)) facts.set(row.id, row)
255
+ } catch {
256
+ // ignore
257
+ }
258
+ }
259
+ try {
260
+ if (typeof ledger.listPreferences === 'function') {
261
+ for (const row of ledger.listPreferences({ includeCandidates: true }) ?? []) if (row?.id) preferences.set(row.id, row)
262
+ }
263
+ } catch {
264
+ // ignore
265
+ }
266
+ return { commitments, facts, preferences, ledger }
267
+ }
268
+
269
+ function findCommitment(ledger, id, index) {
157
270
  if (!ledger || !id) return undefined
271
+ if (index?.commitments instanceof Map) return index.commitments.get(id)
158
272
  if (typeof ledger.getCommitment === 'function') {
159
273
  const hit = ledger.getCommitment(id)
160
274
  if (hit) return hit
@@ -163,8 +277,9 @@ function findCommitment(ledger, id) {
163
277
  return rows.find((row) => row?.id === id)
164
278
  }
165
279
 
166
- function findFact(ledger, id) {
280
+ function findFact(ledger, id, index) {
167
281
  if (!ledger || !id) return undefined
282
+ if (index?.facts instanceof Map) return index.facts.get(id)
168
283
  if (typeof ledger.getFact === 'function') {
169
284
  const hit = ledger.getFact(id)
170
285
  if (hit) return hit
@@ -191,8 +306,9 @@ function findFact(ledger, id) {
191
306
  }
192
307
  }
193
308
 
194
- function findPreference(ledger, id) {
309
+ function findPreference(ledger, id, index) {
195
310
  if (!ledger || !id) return undefined
311
+ if (index?.preferences instanceof Map) return index.preferences.get(id)
196
312
  if (typeof ledger.findPreference === 'function') {
197
313
  const hit = ledger.findPreference(id)
198
314
  if (hit) return hit
@@ -283,8 +399,8 @@ function resolveSourceRefs(store, items) {
283
399
  * sources: Array<{sessionId: string, turnId: string, quote: string, turn: object}>,
284
400
  * missing: Array<{sessionId?: string, turnId?: string, quote?: string, id?: string, reason: string}> }}
285
401
  */
286
- export function evidenceForCommitment(store, ledger, commitmentId) {
287
- const commitment = findCommitment(ledger, commitmentId)
402
+ export function evidenceForCommitment(store, ledger, commitmentId, index) {
403
+ const commitment = findCommitment(ledger, commitmentId, index)
288
404
  if (!commitment) {
289
405
  return { commitment: undefined, sources: [], missing: [{ id: commitmentId, reason: 'commitment_not_found' }] }
290
406
  }
@@ -319,8 +435,8 @@ export function evidenceForCommitment(store, ledger, commitmentId) {
319
435
  }
320
436
 
321
437
  /** Trace a fact's `SourceRef[]` (plus its primary `source`) back to turns. */
322
- export function evidenceForFact(store, ledger, factId) {
323
- const fact = findFact(ledger, factId)
438
+ export function evidenceForFact(store, ledger, factId, index) {
439
+ const fact = findFact(ledger, factId, index)
324
440
  if (!fact) {
325
441
  return { fact: undefined, sources: [], missing: [{ id: factId, reason: 'fact_not_found' }] }
326
442
  }
@@ -330,8 +446,8 @@ export function evidenceForFact(store, ledger, factId) {
330
446
  }
331
447
 
332
448
  /** Trace a preference's `SourceRef[]` (plus its primary `source`) back to turns. */
333
- export function evidenceForPreference(store, ledger, preferenceId) {
334
- const preference = findPreference(ledger, preferenceId)
449
+ export function evidenceForPreference(store, ledger, preferenceId, index) {
450
+ const preference = findPreference(ledger, preferenceId, index)
335
451
  if (!preference) {
336
452
  return { preference: undefined, sources: [], missing: [{ id: preferenceId, reason: 'preference_not_found' }] }
337
453
  }
@@ -434,24 +550,24 @@ function normalizeKind(kind) {
434
550
  return KIND_ALIASES[kind.trim().toLowerCase()]
435
551
  }
436
552
 
437
- function classifyKind(ledger, id, kind) {
553
+ function classifyKind(ledger, id, kind, index) {
438
554
  const explicit = normalizeKind(kind)
439
555
  if (explicit) return explicit
440
556
  const inferred = inferKindFromId(id)
441
557
  if (inferred) return inferred
442
- if (findCommitment(ledger, id)) return 'commitment'
443
- if (findFact(ledger, id)) return 'fact'
444
- if (findPreference(ledger, id)) return 'preference'
558
+ if (findCommitment(ledger, id, index)) return 'commitment'
559
+ if (findFact(ledger, id, index)) return 'fact'
560
+ if (findPreference(ledger, id, index)) return 'preference'
445
561
  return 'unknown'
446
562
  }
447
563
 
448
- function normalizeRequestedIds(ids, ledger) {
564
+ function normalizeRequestedIds(ids, ledger, index) {
449
565
  const out = { commitments: [], facts: [], preferences: [], unknown: [] }
450
566
  const seen = new Set()
451
567
  const push = (id, kind) => {
452
568
  const value = id === undefined || id === null ? '' : String(id).trim()
453
569
  if (!value) return
454
- const resolved = classifyKind(ledger, value, kind)
570
+ const resolved = classifyKind(ledger, value, kind, index)
455
571
  const key = `${resolved}\u0000${value}`
456
572
  if (seen.has(key)) return
457
573
  seen.add(key)
@@ -562,24 +678,52 @@ function buildReadme({ createdAt, entries, manifestDigest }) {
562
678
  /**
563
679
  * Assemble the three-file evidence pack.
564
680
  *
681
+ * The default path is capped at `DEFAULT_MAX_EVIDENCE_ENTRIES` entries
682
+ * (performance audit P0-3): a pack over every row of a 50k-row ledger is slow
683
+ * and huge. When the cap would be exceeded this throws
684
+ * `EvidencePackLimitError`; pass `all: true` (CLI: `--all`) after an explicit
685
+ * user confirmation, or narrow the selection with `ids` (CLI: `--ids`).
686
+ *
565
687
  * @param {object} options
566
688
  * @param {object} options.store SqliteStore-like (`getTurn`/`listTurns`, `getTurn` optional)
567
689
  * @param {object} options.ledger Ledger instance (listCommitments/listFacts/findPreference)
568
690
  * @param {object|Array|string} [options.ids] `{commitments, facts, preferences}`, an id array,
569
691
  * a single id, or `[{kind, id}]`. `cm_`/`fact_`/`pref_` prefixes are inferred.
570
692
  * @param {Date|string} [options.now]
693
+ * @param {number} [options.limit=DEFAULT_MAX_EVIDENCE_ENTRIES] max entries before
694
+ * `EvidencePackLimitError` (Infinity disables the cap).
695
+ * @param {boolean} [options.all=false] explicit "build the whole pack" opt-in.
571
696
  * @returns {{ files: Record<string, string>, summary: object }}
572
697
  * files: `{ 'manifest.json': string, 'README.txt': string, 'SHA256SUMS': string }`
573
698
  */
574
- export function buildEvidencePack({ store, ledger, ids, now = new Date() } = {}) {
699
+ export function buildEvidencePack({
700
+ store,
701
+ ledger,
702
+ ids,
703
+ now = new Date(),
704
+ limit = DEFAULT_MAX_EVIDENCE_ENTRIES,
705
+ all = false,
706
+ } = {}) {
575
707
  if (!ledger || typeof ledger !== 'object') throw new TypeError('buildEvidencePack requires a ledger')
576
708
  if (!store || typeof store !== 'object') throw new TypeError('buildEvidencePack requires a store')
577
709
  const createdAt = isoDate(now)
578
- const requested = normalizeRequestedIds(ids, ledger)
710
+ const effectiveLimit = all ? Infinity : Number(limit)
711
+ if (!(effectiveLimit === Infinity || (Number.isInteger(effectiveLimit) && effectiveLimit >= 0))) {
712
+ throw new TypeError('buildEvidencePack limit must be a non-negative integer or Infinity')
713
+ }
714
+ const requestedAny = ids !== undefined && ids !== null && !(Array.isArray(ids) && ids.length === 0)
715
+ // Build the lookup index once; every evidenceFor* call below then costs O(1)
716
+ // instead of re-scanning listFacts()/listCommitments() (P0-3: 80k pack went
717
+ // from 113.75s to linear time).
718
+ const index = requestedAny ? createEvidenceIndex(ledger) : undefined
719
+ const requested = normalizeRequestedIds(ids, ledger, index)
720
+ const requestedCount =
721
+ requested.commitments.length + requested.facts.length + requested.preferences.length + requested.unknown.length
722
+ if (requestedCount > effectiveLimit) throw new EvidencePackLimitError(requestedCount, effectiveLimit)
579
723
  const entries = []
580
724
 
581
725
  for (const id of requested.commitments) {
582
- const result = evidenceForCommitment(store, ledger, id)
726
+ const result = evidenceForCommitment(store, ledger, id, index)
583
727
  entries.push({
584
728
  kind: 'commitment',
585
729
  id,
@@ -589,11 +733,11 @@ export function buildEvidencePack({ store, ledger, ids, now = new Date() } = {})
589
733
  })
590
734
  }
591
735
  for (const id of requested.facts) {
592
- const result = evidenceForFact(store, ledger, id)
736
+ const result = evidenceForFact(store, ledger, id, index)
593
737
  entries.push({ kind: 'fact', id, found: Boolean(result.fact), sources: result.sources, missing: result.missing })
594
738
  }
595
739
  for (const id of requested.preferences) {
596
- const result = evidenceForPreference(store, ledger, id)
740
+ const result = evidenceForPreference(store, ledger, id, index)
597
741
  entries.push({
598
742
  kind: 'preference',
599
743
  id,
@@ -653,7 +797,7 @@ export function buildEvidencePack({ store, ledger, ids, now = new Date() } = {})
653
797
  // verification
654
798
  // ---------------------------------------------------------------------------
655
799
 
656
- function isUnsafePackPath(name) {
800
+ export function isUnsafePackPath(name) {
657
801
  if (!name) return true
658
802
  if (name.startsWith('/') || name.startsWith('\\')) return true
659
803
  if (/^[A-Za-z]:[\\/]/.test(name)) return true
@@ -738,6 +882,1016 @@ export function verifyPack(files) {
738
882
  return { ok: errors.length === 0, errors }
739
883
  }
740
884
 
885
+ // ---------------------------------------------------------------------------
886
+ // delivery receipt pack v1.1
887
+ //
888
+ // Competitive report 21-w2-delivery-trust.md §2.2 and hardening
889
+ // 13-gap-inventory.md P1-2: the evidence pack above is an evidence pack; a
890
+ // delivery receipt pack is different. This section copies the delivered
891
+ // artifacts into one directory, generates receipt.docx, records the generator
892
+ // environment and the verify results, and makes SHA256SUMS cover EVERY file
893
+ // (manifest.json, README.txt, receipt.docx and every delivery artifact).
894
+ //
895
+ // lib/receipt-verify.js verifies such a directory offline. This module never
896
+ // calls the network and never needs ~/.advisers to assemble the pack.
897
+ // ---------------------------------------------------------------------------
898
+
899
+ export const RECEIPT_MANIFEST_FORMAT = 'advisers-delivery-receipt-pack'
900
+ export const RECEIPT_MANIFEST_VERSION = 1
901
+ export const RECEIPT_SHA256SUMS_FILE = 'SHA256SUMS'
902
+ /** Files every receipt pack must carry; SHA256SUMS covers all of them. */
903
+ export const RECEIPT_REQUIRED_FILES = Object.freeze(['manifest.json', 'README.txt', 'receipt.docx'])
904
+ /** Delivery artifacts live under this prefix inside the pack. */
905
+ export const RECEIPT_DELIVERIES_PREFIX = 'deliveries/'
906
+ /** Pack files are owner-read/write only (security audit P1-2 / P2-10). */
907
+ export const RECEIPT_FILE_MODE = 0o600
908
+ export const RECEIPT_DIR_MODE = 0o700
909
+ const RECEIPT_MAX_ANCHOR_PROOF_CHARS = 200_000
910
+ const RECEIPT_MAX_TABLE_ROWS = 120
911
+ const RECEIPT_MAX_DELIVERY_ROWS = 40
912
+ const RECEIPT_MAX_MANIFEST_ITEMS = 200
913
+
914
+ let advisersVersionCache
915
+ function evidenceModuleDirVersion() {
916
+ if (advisersVersionCache !== undefined) return advisersVersionCache
917
+ advisersVersionCache = null
918
+ try {
919
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
920
+ if (typeof pkg.version === 'string' && pkg.version) advisersVersionCache = pkg.version
921
+ } catch {
922
+ // Bundled/copied layouts may not ship package.json next to lib/.
923
+ }
924
+ return advisersVersionCache
925
+ }
926
+
927
+ function receiptText(value) {
928
+ return typeof value === 'string' && value ? value : null
929
+ }
930
+
931
+ function receiptDateText(value, fallback = null) {
932
+ if (value === undefined || value === null || value === '') return fallback
933
+ try {
934
+ return isoDate(value)
935
+ } catch {
936
+ throw new TypeError('invalid date in receipt pack input: ' + String(value))
937
+ }
938
+ }
939
+
940
+ function receiptShaText(value) {
941
+ return typeof value === 'string' ? value.toLowerCase() : ''
942
+ }
943
+
944
+ function isSha256Hex(value) {
945
+ return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value)
946
+ }
947
+
948
+ function sanitizeSegment(raw, fallback = 'item') {
949
+ let text = String(raw === undefined || raw === null ? '' : raw)
950
+ .normalize('NFKC')
951
+ .replace(/[\u0000-\u001f\u007f]/g, '')
952
+ .replace(/[\\/:*?"<>|]/g, '_')
953
+ .trim()
954
+ text = text.replace(/^\.+/, '').replace(/\.+$/, '')
955
+ if (!text) text = fallback
956
+ return text.slice(0, 120)
957
+ }
958
+
959
+ function basenameOf(filePath) {
960
+ const text = String(filePath === undefined || filePath === null ? '' : filePath).replace(/\\/g, '/')
961
+ return sanitizeSegment(text.slice(text.lastIndexOf('/') + 1), 'file')
962
+ }
963
+
964
+ function uniqueName(name, used) {
965
+ const base = sanitizeSegment(name, 'file')
966
+ if (!used.has(base)) {
967
+ used.add(base)
968
+ return base
969
+ }
970
+ const dot = base.lastIndexOf('.')
971
+ const stem = dot > 0 ? base.slice(0, dot) : base
972
+ const ext = dot > 0 ? base.slice(dot) : ''
973
+ for (let i = 2; i < 10_000; i += 1) {
974
+ const candidate = stem + '-' + i + ext
975
+ if (!used.has(candidate)) {
976
+ used.add(candidate)
977
+ return candidate
978
+ }
979
+ }
980
+ throw new Error('could not derive a unique pack file name from ' + base)
981
+ }
982
+
983
+ const RECEIPT_ABS_PATH_TOKEN = /(^|[\s"'=(,])((?:[A-Za-z]:[\\/]|\/)[^\s"'<>|,)]*)/g
984
+ /**
985
+ * Redact absolute filesystem path tokens from operator-supplied free text
986
+ * (generator.command, recipient fields). Relative names such as a/b.docx are
987
+ * left alone; evidence quotes are never scrubbed (verbatim quotes must stay
988
+ * byte-identical to their quoteSha256).
989
+ */
990
+ function scrubPathText(value) {
991
+ const text = receiptText(value)
992
+ if (text === null) return null
993
+ let out = text.length > 500 ? text.slice(0, 500) : text
994
+ try {
995
+ out = out.split(process.cwd()).join('<cwd>')
996
+ } catch {
997
+ // process.cwd() can throw if the working directory was deleted; ignore.
998
+ }
999
+ return out.replace(RECEIPT_ABS_PATH_TOKEN, (match, lead) => lead + '<path>')
1000
+ }
1001
+
1002
+ function readDeliveryBytes(source, deliveryId, displayName) {
1003
+ try {
1004
+ const stat = statSync(source)
1005
+ if (!stat.isFile()) throw Object.assign(new Error('not a regular file'), { code: 'ENOTFILE' })
1006
+ return readFileSync(source)
1007
+ } catch (error) {
1008
+ const code = error && error.code ? error.code : error.message
1009
+ throw new Error('delivery ' + deliveryId + ' file is not readable: ' + displayName + ' (' + code + ')')
1010
+ }
1011
+ }
1012
+
1013
+ function normalizeDeliveryFile(file, deliveryId, fileIndex) {
1014
+ if (typeof file === 'string') {
1015
+ const name = basenameOf(file)
1016
+ return { bytes: readDeliveryBytes(file, deliveryId, name), name }
1017
+ }
1018
+ if (file && typeof file === 'object' && !Array.isArray(file)) {
1019
+ const sourcePath = typeof file.sourcePath === 'string' ? file.sourcePath : typeof file.path === 'string' ? file.path : ''
1020
+ const name = basenameOf(file.name || (sourcePath ? basenameOf(sourcePath) : 'file-' + (fileIndex + 1)))
1021
+ const embedded = file.content !== undefined ? file.content : file.bytes
1022
+ if (embedded !== undefined && embedded !== null) {
1023
+ const bytes = toBytes(embedded)
1024
+ if (!bytes) {
1025
+ throw new TypeError('delivery ' + deliveryId + ' file ' + name + ' content must be a string, Buffer, Uint8Array or ArrayBuffer')
1026
+ }
1027
+ return { bytes, name }
1028
+ }
1029
+ if (!sourcePath) {
1030
+ throw new TypeError('delivery ' + deliveryId + ' file #' + (fileIndex + 1) + ' needs content or sourcePath/path')
1031
+ }
1032
+ return { bytes: readDeliveryBytes(sourcePath, deliveryId, name), name }
1033
+ }
1034
+ throw new TypeError('delivery ' + deliveryId + ' file #' + (fileIndex + 1) + ' must be a path string or an object')
1035
+ }
1036
+
1037
+ function normalizeReceiptDeliveries(deliveries) {
1038
+ const input = Array.isArray(deliveries) ? deliveries : deliveries ? [deliveries] : []
1039
+ if (!input.length) {
1040
+ throw new TypeError(
1041
+ 'buildReceiptPack requires at least one delivery ({deliveries: [{id, title, files, ...}]}); ' +
1042
+ 'use buildEvidencePack for an evidence-only pack',
1043
+ )
1044
+ }
1045
+ const usedIds = new Set()
1046
+ return input.map((delivery, index) => {
1047
+ if (!delivery || typeof delivery !== 'object' || Array.isArray(delivery)) {
1048
+ throw new TypeError('delivery #' + (index + 1) + ' must be an object')
1049
+ }
1050
+ const rawId = delivery.id === undefined || delivery.id === null || delivery.id === '' ? 'delivery-' + (index + 1) : String(delivery.id)
1051
+ const id = uniqueName(rawId, usedIds)
1052
+ const rawFiles = delivery.files !== undefined ? delivery.files : delivery.artifacts !== undefined ? delivery.artifacts : delivery.outputs
1053
+ if (!Array.isArray(rawFiles) || rawFiles.length === 0) {
1054
+ throw new TypeError('delivery ' + id + ' has no files to include in the receipt pack')
1055
+ }
1056
+ const usedNames = new Set()
1057
+ const files = rawFiles.map((file, fileIndex) => {
1058
+ const read = normalizeDeliveryFile(file, id, fileIndex)
1059
+ const name = uniqueName(read.name, usedNames)
1060
+ const sha256 = sha256Hex(read.bytes)
1061
+ return {
1062
+ name,
1063
+ path: RECEIPT_DELIVERIES_PREFIX + id + '/' + name,
1064
+ size: read.bytes.length,
1065
+ sha256,
1066
+ content: read.bytes,
1067
+ }
1068
+ })
1069
+ let validation = null
1070
+ if (delivery.validation !== undefined && delivery.validation !== null) {
1071
+ if (typeof delivery.validation === 'string') validation = delivery.validation.slice(0, 500)
1072
+ else {
1073
+ try {
1074
+ validation = JSON.stringify(delivery.validation).slice(0, 500)
1075
+ } catch {
1076
+ validation = null
1077
+ }
1078
+ }
1079
+ }
1080
+ return {
1081
+ id,
1082
+ title: receiptText(delivery.title),
1083
+ tool: receiptText(delivery.tool),
1084
+ createdAt: receiptDateText(delivery.createdAt !== undefined ? delivery.createdAt : delivery.created_at, null),
1085
+ validation,
1086
+ files,
1087
+ }
1088
+ })
1089
+ }
1090
+
1091
+ // --- evidence entries (re-sanitized: the receipt pack keeps references and
1092
+ // --- capped quotes only, never full turn bodies) ---------------------------
1093
+
1094
+ function receiptSource(source) {
1095
+ if (source && typeof source === 'object' && source.turn) return compactSource(source)
1096
+ if (!source || typeof source !== 'object' || Array.isArray(source)) {
1097
+ return { sessionId: '', turnId: '', quote: '', quoteChars: 0, truncated: false, quoteSha256: sha256Hex('') }
1098
+ }
1099
+ const rawQuote = typeof source.quote === 'string' ? source.quote : ''
1100
+ const chars = Array.from(rawQuote)
1101
+ const quote = chars.length > MAX_QUOTE_CHARS ? chars.slice(0, MAX_QUOTE_CHARS).join('') : rawQuote
1102
+ let quoteChars = chars.length
1103
+ if (Number.isInteger(source.quoteChars) && source.quoteChars >= quoteChars) quoteChars = source.quoteChars
1104
+ const entry = {
1105
+ sessionId: typeof source.sessionId === 'string' ? source.sessionId : '',
1106
+ turnId: typeof source.turnId === 'string' ? source.turnId : '',
1107
+ quote,
1108
+ quoteChars,
1109
+ truncated: typeof source.truncated === 'boolean' ? source.truncated : quoteChars > MAX_QUOTE_CHARS,
1110
+ quoteSha256: sha256Hex(quote),
1111
+ }
1112
+ if (Number.isInteger(source.turnSeq)) entry.turnSeq = source.turnSeq
1113
+ if (typeof source.turnRole === 'string') entry.turnRole = source.turnRole
1114
+ return entry
1115
+ }
1116
+
1117
+ function receiptMissing(item) {
1118
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return { reason: 'unknown' }
1119
+ const out = { reason: typeof item.reason === 'string' ? item.reason : 'unknown' }
1120
+ for (const key of ['id', 'ref', 'sessionId', 'turnId']) {
1121
+ if (typeof item[key] === 'string' && item[key]) out[key] = item[key]
1122
+ }
1123
+ if (typeof item.quote === 'string' && item.quote.length) {
1124
+ const clamped = clampQuote(item.quote)
1125
+ if (Number.isInteger(item.quoteChars) && item.quoteChars > clamped.quoteChars) {
1126
+ clamped.quoteChars = item.quoteChars
1127
+ clamped.truncated = true
1128
+ }
1129
+ Object.assign(out, clamped)
1130
+ }
1131
+ return out
1132
+ }
1133
+
1134
+ function receiptEvidenceEntry(entry) {
1135
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return null
1136
+ return {
1137
+ kind: typeof entry.kind === 'string' ? entry.kind : 'unknown',
1138
+ id: String(entry.id === undefined || entry.id === null ? '' : entry.id),
1139
+ found: Boolean(entry.found),
1140
+ sources: (Array.isArray(entry.sources) ? entry.sources : []).map(receiptSource),
1141
+ missing: (Array.isArray(entry.missing) ? entry.missing : []).map(receiptMissing),
1142
+ }
1143
+ }
1144
+
1145
+ function normalizeReceiptEvidence(evidence) {
1146
+ const meta = { format: MANIFEST_FORMAT, version: MANIFEST_VERSION }
1147
+ let list = []
1148
+ if (evidence === undefined || evidence === null) {
1149
+ list = []
1150
+ } else if (typeof evidence === 'string') {
1151
+ try {
1152
+ return normalizeReceiptEvidence(JSON.parse(evidence))
1153
+ } catch {
1154
+ list = []
1155
+ }
1156
+ } else if (Array.isArray(evidence)) {
1157
+ list = evidence
1158
+ } else if (typeof evidence === 'object') {
1159
+ if (evidence.summary && Array.isArray(evidence.summary.entries)) {
1160
+ if (typeof evidence.summary.format === 'string') meta.format = evidence.summary.format
1161
+ if (Number.isInteger(evidence.summary.version)) meta.version = evidence.summary.version
1162
+ list = evidence.summary.entries
1163
+ } else if (Array.isArray(evidence.entries)) {
1164
+ list = evidence.entries
1165
+ } else if (evidence.files && typeof evidence.files === 'object') {
1166
+ const manifestText = textOf(evidence.files['manifest.json'])
1167
+ if (typeof manifestText === 'string') {
1168
+ try {
1169
+ const parsed = JSON.parse(manifestText)
1170
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
1171
+ if (typeof parsed.format === 'string') meta.format = parsed.format
1172
+ if (Number.isInteger(parsed.version)) meta.version = parsed.version
1173
+ list = Array.isArray(parsed.entries) ? parsed.entries : []
1174
+ }
1175
+ } catch {
1176
+ list = []
1177
+ }
1178
+ }
1179
+ }
1180
+ }
1181
+ const entries = list.map(receiptEvidenceEntry).filter(Boolean)
1182
+ entries.sort(compareEntries)
1183
+ const counts = { commitment: 0, fact: 0, preference: 0, unknown: 0 }
1184
+ let sourceCount = 0
1185
+ let missingCount = 0
1186
+ for (const entry of entries) {
1187
+ counts[entry.kind] = (counts[entry.kind] || 0) + 1
1188
+ sourceCount += entry.sources.length
1189
+ missingCount += entry.missing.length
1190
+ }
1191
+ return {
1192
+ format: meta.format,
1193
+ version: meta.version,
1194
+ entryCount: entries.length,
1195
+ counts,
1196
+ sourceCount,
1197
+ missingCount,
1198
+ entries,
1199
+ }
1200
+ }
1201
+
1202
+ // --- verify results ---------------------------------------------------------
1203
+
1204
+ function receiptCheck(check) {
1205
+ if (!check || typeof check !== 'object' || Array.isArray(check)) return null
1206
+ const out = {
1207
+ id: typeof check.id === 'string' ? check.id.slice(0, 120) : 'check',
1208
+ ok: Boolean(check.ok),
1209
+ }
1210
+ if (typeof check.severity === 'string') out.severity = check.severity.slice(0, 20)
1211
+ if (typeof check.detail === 'string') out.detail = check.detail.slice(0, 300)
1212
+ if (check.skipped === true) out.skipped = true
1213
+ return out
1214
+ }
1215
+
1216
+ function receiptStringList(value) {
1217
+ if (!Array.isArray(value)) return []
1218
+ return value
1219
+ .filter((item) => typeof item === 'string')
1220
+ .slice(0, RECEIPT_MAX_MANIFEST_ITEMS)
1221
+ .map((item) => item.slice(0, 300))
1222
+ }
1223
+
1224
+ function receiptVerifyResult(result, index) {
1225
+ if (typeof result === 'boolean') {
1226
+ return { source: null, ok: result, checkedAt: null, errors: [], checks: [], summary: null }
1227
+ }
1228
+ if (!result || typeof result !== 'object' || Array.isArray(result)) {
1229
+ throw new TypeError('verifyResults[' + index + '] must be an object with a boolean ok')
1230
+ }
1231
+ if (typeof result.ok !== 'boolean') throw new TypeError('verifyResults[' + index + '].ok must be a boolean')
1232
+ let checkedAt = null
1233
+ try {
1234
+ checkedAt = receiptDateText(result.checkedAt !== undefined ? result.checkedAt : result.at, null)
1235
+ } catch {
1236
+ checkedAt = null
1237
+ }
1238
+ const checks = Array.isArray(result.checks)
1239
+ ? result.checks.map(receiptCheck).filter(Boolean).slice(0, RECEIPT_MAX_MANIFEST_ITEMS)
1240
+ : []
1241
+ return {
1242
+ source: receiptText(result.source !== undefined ? result.source : result.tool !== undefined ? result.tool : result.command),
1243
+ ok: result.ok,
1244
+ checkedAt,
1245
+ errors: receiptStringList(result.errors),
1246
+ checks,
1247
+ summary: receiptText(result.summary !== undefined ? result.summary : result.detail),
1248
+ }
1249
+ }
1250
+
1251
+ function normalizeReceiptVerifyResults(verifyResults) {
1252
+ if (verifyResults === undefined || verifyResults === null) return []
1253
+ const list = Array.isArray(verifyResults) ? verifyResults : [verifyResults]
1254
+ return list.map((item, index) => receiptVerifyResult(item, index))
1255
+ }
1256
+
1257
+ function receiptVerifyStatus(results) {
1258
+ if (!results.length) return 'not-recorded'
1259
+ return results.every((item) => item.ok) ? 'passed' : 'failed'
1260
+ }
1261
+
1262
+ // --- generator / recipient / optional anchors -------------------------------
1263
+
1264
+ function normalizeReceiptGenerator(env) {
1265
+ const source = env && typeof env === 'object' && !Array.isArray(env) ? env : {}
1266
+ const template = source.template && typeof source.template === 'object' && !Array.isArray(source.template) ? source.template : {}
1267
+ const templateName =
1268
+ source.templateName !== undefined
1269
+ ? source.templateName
1270
+ : typeof source.template === 'string'
1271
+ ? source.template
1272
+ : template.name
1273
+ return {
1274
+ advisersVersion:
1275
+ receiptText(source.advisersVersion !== undefined ? source.advisersVersion : source.version) || evidenceModuleDirVersion(),
1276
+ nodeVersion: receiptText(source.nodeVersion !== undefined ? source.nodeVersion : source.node) || process.version,
1277
+ platform: receiptText(source.platform) || process.platform,
1278
+ templateName: scrubPathText(templateName),
1279
+ templateVersion: scrubPathText(source.templateVersion !== undefined ? source.templateVersion : template.version),
1280
+ command: scrubPathText(source.command),
1281
+ }
1282
+ }
1283
+
1284
+ function normalizeReceiptRecipient(recipient) {
1285
+ if (recipient === undefined || recipient === null || recipient === '') return null
1286
+ if (typeof recipient === 'string') return { name: scrubPathText(recipient), email: null, note: null }
1287
+ if (typeof recipient !== 'object' || Array.isArray(recipient)) {
1288
+ throw new TypeError('recipient must be a string or an object {name, email, note}')
1289
+ }
1290
+ const out = {
1291
+ name: scrubPathText(recipient.name !== undefined ? recipient.name : recipient.to),
1292
+ email: scrubPathText(recipient.email),
1293
+ note: scrubPathText(recipient.note !== undefined ? recipient.note : recipient.description),
1294
+ }
1295
+ if (!out.name && !out.email && !out.note) return null
1296
+ return out
1297
+ }
1298
+
1299
+ function normalizeReceiptAnchors(anchors) {
1300
+ if (anchors === undefined || anchors === null) return []
1301
+ const list = Array.isArray(anchors) ? anchors : [anchors]
1302
+ return list.map((anchor, index) => {
1303
+ if (!anchor || typeof anchor !== 'object' || Array.isArray(anchor)) {
1304
+ throw new TypeError('anchors[' + index + '] must be an object')
1305
+ }
1306
+ const file = typeof anchor.file === 'string' ? anchor.file.replace(/\\/g, '/') : ''
1307
+ if (isUnsafePackPath(file)) throw new TypeError('anchors[' + index + '].file must be a safe relative pack path')
1308
+ const fileSha256 = receiptShaText(anchor.fileSha256)
1309
+ if (!isSha256Hex(fileSha256)) {
1310
+ throw new TypeError('anchors[' + index + '].fileSha256 must be 64 lowercase hex characters')
1311
+ }
1312
+ const adapterId = receiptText(anchor.adapterId)
1313
+ if (!adapterId) throw new TypeError('anchors[' + index + '].adapterId is required')
1314
+ let proof = ''
1315
+ if (typeof anchor.proof === 'string') proof = anchor.proof
1316
+ else if (Buffer.isBuffer(anchor.proof)) proof = anchor.proof.toString('base64')
1317
+ else if (anchor.proof instanceof Uint8Array) proof = Buffer.from(anchor.proof).toString('base64')
1318
+ if (!proof) throw new TypeError('anchors[' + index + '].proof is required')
1319
+ if (proof.length > RECEIPT_MAX_ANCHOR_PROOF_CHARS) {
1320
+ throw new RangeError('anchors[' + index + '].proof is larger than ' + RECEIPT_MAX_ANCHOR_PROOF_CHARS + ' characters')
1321
+ }
1322
+ return {
1323
+ file,
1324
+ fileSha256,
1325
+ adapterId: adapterId.slice(0, 120),
1326
+ issuedAt: receiptDateText(anchor.issuedAt, null),
1327
+ proof,
1328
+ }
1329
+ })
1330
+ }
1331
+
1332
+ // --- minimal deterministic DOCX writer (fallback when advisers-office is not
1333
+ // --- installed; a DOCX is a ZIP with [Content_Types].xml + word/document.xml) ----
1334
+
1335
+ const CRC32_TABLE = (() => {
1336
+ const table = new Uint32Array(256)
1337
+ for (let n = 0; n < 256; n += 1) {
1338
+ let c = n
1339
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
1340
+ table[n] = c >>> 0
1341
+ }
1342
+ return table
1343
+ })()
1344
+
1345
+ function crc32(bytes) {
1346
+ let crc = 0xffffffff
1347
+ for (let i = 0; i < bytes.length; i += 1) crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8)
1348
+ return (crc ^ 0xffffffff) >>> 0
1349
+ }
1350
+
1351
+ const ZIP_DOS_TIME = 0
1352
+ const ZIP_DOS_DATE = 0x0021 // 1980-01-01: fixed so the fallback DOCX is byte-stable
1353
+
1354
+ function zipStoredFiles(entries) {
1355
+ const locals = []
1356
+ const centrals = []
1357
+ let offset = 0
1358
+ for (const entry of entries) {
1359
+ const name = Buffer.from(entry.name, 'utf8')
1360
+ const data = entry.data
1361
+ const crc = crc32(data)
1362
+ const local = Buffer.alloc(30)
1363
+ local.writeUInt32LE(0x04034b50, 0)
1364
+ local.writeUInt16LE(20, 4)
1365
+ local.writeUInt16LE(0x0800, 6)
1366
+ local.writeUInt16LE(0, 8)
1367
+ local.writeUInt16LE(ZIP_DOS_TIME, 10)
1368
+ local.writeUInt16LE(ZIP_DOS_DATE, 12)
1369
+ local.writeUInt32LE(crc, 14)
1370
+ local.writeUInt32LE(data.length, 18)
1371
+ local.writeUInt32LE(data.length, 22)
1372
+ local.writeUInt16LE(name.length, 26)
1373
+ local.writeUInt16LE(0, 28)
1374
+ const localBlock = Buffer.concat([local, name, data])
1375
+ const central = Buffer.alloc(46)
1376
+ central.writeUInt32LE(0x02014b50, 0)
1377
+ central.writeUInt16LE(20, 4)
1378
+ central.writeUInt16LE(20, 6)
1379
+ central.writeUInt16LE(0x0800, 8)
1380
+ central.writeUInt16LE(0, 10)
1381
+ central.writeUInt16LE(ZIP_DOS_TIME, 12)
1382
+ central.writeUInt16LE(ZIP_DOS_DATE, 14)
1383
+ central.writeUInt32LE(crc, 16)
1384
+ central.writeUInt32LE(data.length, 20)
1385
+ central.writeUInt32LE(data.length, 24)
1386
+ central.writeUInt16LE(name.length, 28)
1387
+ central.writeUInt16LE(0, 30)
1388
+ central.writeUInt16LE(0, 32)
1389
+ central.writeUInt16LE(0, 34)
1390
+ central.writeUInt16LE(0, 36)
1391
+ central.writeUInt32LE(0, 38)
1392
+ central.writeUInt32LE(offset, 42)
1393
+ locals.push(localBlock)
1394
+ centrals.push(Buffer.concat([central, name]))
1395
+ offset += localBlock.length
1396
+ }
1397
+ const centralBlock = Buffer.concat(centrals)
1398
+ const eocd = Buffer.alloc(22)
1399
+ eocd.writeUInt32LE(0x06054b50, 0)
1400
+ eocd.writeUInt16LE(0, 4)
1401
+ eocd.writeUInt16LE(0, 6)
1402
+ eocd.writeUInt16LE(entries.length, 8)
1403
+ eocd.writeUInt16LE(entries.length, 10)
1404
+ eocd.writeUInt32LE(centralBlock.length, 12)
1405
+ eocd.writeUInt32LE(offset, 16)
1406
+ eocd.writeUInt16LE(0, 20)
1407
+ return Buffer.concat([...locals, centralBlock, eocd])
1408
+ }
1409
+
1410
+ function escapeXmlText(value) {
1411
+ return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
1412
+ }
1413
+
1414
+ function minimalDocx(spec) {
1415
+ const lines = [{ text: spec.title, bold: true }]
1416
+ if (spec.subtitle) lines.push({ text: spec.subtitle })
1417
+ for (const section of spec.sections || []) {
1418
+ if (section.heading) lines.push({ text: section.heading, bold: true })
1419
+ for (const paragraph of section.paragraphs || []) lines.push({ text: paragraph })
1420
+ for (const bullet of section.bullets || []) lines.push({ text: '- ' + bullet })
1421
+ if (section.table) {
1422
+ lines.push({ text: section.table.headers.join(' | '), bold: true })
1423
+ for (const row of section.table.rows || []) lines.push({ text: row.join(' | ') })
1424
+ }
1425
+ }
1426
+ const paragraphs = lines
1427
+ .map((line) => {
1428
+ const runProps = line.bold ? '<w:rPr><w:b/></w:rPr>' : ''
1429
+ return '<w:p><w:r>' + runProps + '<w:t xml:space="preserve">' + escapeXmlText(line.text) + '</w:t></w:r></w:p>'
1430
+ })
1431
+ .join('')
1432
+ const documentXml =
1433
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1434
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>' +
1435
+ paragraphs +
1436
+ '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr>' +
1437
+ '</w:body></w:document>'
1438
+ const contentTypes =
1439
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1440
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
1441
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
1442
+ '<Default Extension="xml" ContentType="application/xml"/>' +
1443
+ '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>' +
1444
+ '</Types>'
1445
+ const relationships =
1446
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1447
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1448
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
1449
+ '</Relationships>'
1450
+ return zipStoredFiles([
1451
+ { name: '[Content_Types].xml', data: Buffer.from(contentTypes, 'utf8') },
1452
+ { name: '_rels/.rels', data: Buffer.from(relationships, 'utf8') },
1453
+ { name: 'word/document.xml', data: Buffer.from(documentXml, 'utf8') },
1454
+ ])
1455
+ }
1456
+
1457
+ function assertReceiptDocxBuffer(buffer) {
1458
+ const bytes = toBytes(buffer)
1459
+ if (!bytes || bytes.length < 4) throw new TypeError('receipt DOCX builder returned no bytes')
1460
+ if (bytes[0] !== 0x50 || bytes[1] !== 0x4b) throw new TypeError('receipt DOCX builder did not return a ZIP/DOCX buffer')
1461
+ if (!bytes.includes(Buffer.from('word/document.xml', 'utf8'))) {
1462
+ throw new TypeError('receipt DOCX buffer is missing word/document.xml')
1463
+ }
1464
+ return bytes
1465
+ }
1466
+
1467
+ async function buildReceiptDocxBytes(spec, docxBuilder) {
1468
+ if (typeof docxBuilder === 'function') return assertReceiptDocxBuffer(await docxBuilder(spec))
1469
+ if (docxBuilder !== false) {
1470
+ try {
1471
+ const office = await import('advisers-office')
1472
+ if (office && typeof office.buildDocx === 'function') {
1473
+ return assertReceiptDocxBuffer(await office.buildDocx(spec))
1474
+ }
1475
+ } catch {
1476
+ // Offline/portable install without the optional office peer: use the
1477
+ // built-in writer below (still a valid DOCX, just plainer).
1478
+ }
1479
+ }
1480
+ return assertReceiptDocxBuffer(minimalDocx(spec))
1481
+ }
1482
+
1483
+ // --- receipt DOCX content / README / manifest --------------------------------
1484
+
1485
+ function formatBytesLabel(size) {
1486
+ if (!Number.isFinite(size)) return '?'
1487
+ if (size >= 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + ' MiB'
1488
+ if (size >= 1024) return (size / 1024).toFixed(1) + ' KiB'
1489
+ return size + ' B'
1490
+ }
1491
+
1492
+ function receiptRecipientLabel(recipient) {
1493
+ if (!recipient) return 'none'
1494
+ const parts = []
1495
+ if (recipient.name) parts.push(recipient.name)
1496
+ if (recipient.email) parts.push('<' + recipient.email + '>')
1497
+ return parts.length ? parts.join(' ') : 'recorded (see manifest.json)'
1498
+ }
1499
+
1500
+ function receiptDocxSpec(input) {
1501
+ const {
1502
+ createdAt,
1503
+ deliveries,
1504
+ evidence,
1505
+ verifyResults,
1506
+ verifyStatus,
1507
+ recipient,
1508
+ generator,
1509
+ anchors,
1510
+ deliveryFiles,
1511
+ receiptSha256,
1512
+ } = input
1513
+ const summary = [
1514
+ '包格式:' + RECEIPT_MANIFEST_FORMAT + ' v' + RECEIPT_MANIFEST_VERSION,
1515
+ '生成时间:' + createdAt,
1516
+ '收件人:' + (recipient && (recipient.name || recipient.email) ? recipient.name || recipient.email : '未填写'),
1517
+ '生成环境:Advisers ' + (generator.advisersVersion || 'unknown') + ' / Node ' + generator.nodeVersion + ' / ' + generator.platform,
1518
+ '模板:' + (generator.templateName ? generator.templateName + (generator.templateVersion ? '@' + generator.templateVersion : '') : '未记录'),
1519
+ '交付:' + deliveries.length + ' 项 / 文件 ' + deliveryFiles.length + ' 个',
1520
+ '校验结果:' + (verifyStatus === 'passed' ? '通过' : verifyStatus === 'failed' ? '未通过' : '未记录'),
1521
+ '时间锚:' + (anchors.length ? anchors.length + ' 条(外部锚,需按适配器另行验证)' : '未锚定(仅本地自证)'),
1522
+ ]
1523
+ const sections = [{ heading: '摘要', paragraphs: summary }]
1524
+ const deliveryRows = deliveries.slice(0, RECEIPT_MAX_DELIVERY_ROWS).map((delivery) => [
1525
+ delivery.id,
1526
+ delivery.title || '-',
1527
+ delivery.tool || '-',
1528
+ delivery.createdAt || '-',
1529
+ String(delivery.files.length),
1530
+ ])
1531
+ sections.push({
1532
+ heading: '交付清单',
1533
+ ...(deliveryRows.length
1534
+ ? { table: { headers: ['交付ID', '标题', '工具', '生成时间', '文件数'], rows: deliveryRows } }
1535
+ : { paragraphs: ['(没有交付记录)'] }),
1536
+ })
1537
+ if (deliveries.length > deliveryRows.length) {
1538
+ sections.push({ paragraphs: ['另有 ' + (deliveries.length - deliveryRows.length) + ' 项交付未在本回执中展开,见 manifest.json。'] })
1539
+ }
1540
+ const fileRows = deliveryFiles
1541
+ .slice(0, RECEIPT_MAX_TABLE_ROWS)
1542
+ .map((file) => [file.path, formatBytesLabel(file.size), file.sha256])
1543
+ fileRows.push(['receipt.docx', '见摘要', receiptSha256])
1544
+ sections.push({
1545
+ heading: '文件与 SHA-256(交付文件 + 回执)',
1546
+ table: { headers: ['文件(包内相对路径)', '大小', 'SHA-256'], rows: fileRows },
1547
+ ...(deliveryFiles.length > RECEIPT_MAX_TABLE_ROWS
1548
+ ? { paragraphs: ['另有 ' + (deliveryFiles.length - RECEIPT_MAX_TABLE_ROWS) + ' 个交付文件未展开,完整清单见 manifest.json / SHA256SUMS。'] }
1549
+ : {}),
1550
+ })
1551
+ const verifyRows = verifyResults.map((item) => [
1552
+ item.source || '未命名',
1553
+ item.ok ? '通过' : '未通过',
1554
+ item.summary || (item.checks.length ? item.checks.length + ' checks' : item.errors.length ? item.errors.length + ' errors' : '-'),
1555
+ ])
1556
+ sections.push({
1557
+ heading: '校验结果',
1558
+ ...(verifyRows.length
1559
+ ? { table: { headers: ['来源', '结果', '说明'], rows: verifyRows } }
1560
+ : { paragraphs: ['未记录校验结果(verify 未运行或结果未传入)。'] }),
1561
+ })
1562
+ sections.push({
1563
+ heading: '证据摘要',
1564
+ paragraphs: [
1565
+ '证据条目:' + evidence.entryCount + '(commitment ' + evidence.counts.commitment + ' / fact ' + evidence.counts.fact + ' / preference ' + evidence.counts.preference + ' / unknown ' + evidence.counts.unknown + ')',
1566
+ '已解析来源:' + evidence.sourceCount + ';缺失来源:' + evidence.missingCount,
1567
+ '完整证据条目(session#turn 引用与截断引用原话)见 manifest.json 的 evidence 字段。',
1568
+ ],
1569
+ })
1570
+ sections.push({
1571
+ heading: '声明',
1572
+ bullets: [
1573
+ '本回执包由 Advisers 在本地生成,生成与验证过程不访问网络。',
1574
+ 'SHA-256 校验和用于检测生成后的改动;它不是电子签名、第三方时间戳、公证或司法存证。',
1575
+ '收件人字段只是操作者填写的记录,不代表对方签收、同意或已收到。',
1576
+ '未锚定时,包内时间只是本机时钟记录,可被重新打包者改写。',
1577
+ ],
1578
+ })
1579
+ return { title: '交付回执', subtitle: 'Delivery receipt · ' + createdAt, sections }
1580
+ }
1581
+
1582
+ function receiptFilesList(fileContents) {
1583
+ return [...fileContents.entries()]
1584
+ .map(([path, content]) => {
1585
+ const bytes = toBytes(content)
1586
+ return { path, size: bytes.length, sha256: sha256Hex(bytes) }
1587
+ })
1588
+ .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))
1589
+ }
1590
+
1591
+ function buildReceiptSums(fileContents) {
1592
+ const lines = receiptFilesList(fileContents)
1593
+ .filter((file) => file.path !== RECEIPT_SHA256SUMS_FILE)
1594
+ .map((file) => file.sha256 + ' ' + file.path)
1595
+ return lines.join('\n') + '\n'
1596
+ }
1597
+
1598
+ function buildReceiptReadme(input) {
1599
+ const { createdAt, generator, recipient, deliveries, evidence, verifyResults, verifyStatus, anchors, manifestDigest } = input
1600
+ const lines = [
1601
+ 'Advisers delivery receipt pack',
1602
+ '==============================',
1603
+ '',
1604
+ 'format: ' + RECEIPT_MANIFEST_FORMAT + ' v' + RECEIPT_MANIFEST_VERSION,
1605
+ 'created: ' + createdAt,
1606
+ 'recipient: ' + receiptRecipientLabel(recipient),
1607
+ 'generator: advisers ' + (generator.advisersVersion || 'unknown') + ' / node ' + generator.nodeVersion + ' / ' + generator.platform,
1608
+ 'template: ' + (generator.templateName ? generator.templateName + (generator.templateVersion ? ' v' + generator.templateVersion : '') : 'not recorded'),
1609
+ 'command: ' + (generator.command || 'not recorded'),
1610
+ 'deliveries: ' + deliveries.length,
1611
+ 'verification:' + ' ' + (verifyStatus === 'passed' ? 'passed' : verifyStatus === 'failed' ? 'FAILED' : 'not recorded') + (verifyResults.length ? ' (' + verifyResults.length + ' result(s))' : ''),
1612
+ 'anchors: ' + (anchors.length ? anchors.length + ' external anchor(s) recorded' : 'NONE - this pack is not externally anchored (local self-attestation only)'),
1613
+ '',
1614
+ 'These files were delivered (relative paths inside this directory)',
1615
+ '------------------------------------------------------------------',
1616
+ ]
1617
+ for (const delivery of deliveries) {
1618
+ lines.push(
1619
+ '- ' +
1620
+ delivery.id +
1621
+ (delivery.title ? ' ' + delivery.title : '') +
1622
+ (delivery.tool ? ' [' + delivery.tool + ']' : '') +
1623
+ (delivery.createdAt ? ' ' + delivery.createdAt : ''),
1624
+ )
1625
+ for (const file of delivery.files) {
1626
+ lines.push(' ' + file.path + ' (' + formatBytesLabel(file.size) + ') sha256 ' + file.sha256)
1627
+ }
1628
+ }
1629
+ if (!deliveries.length) lines.push('(none)')
1630
+ lines.push(
1631
+ '',
1632
+ 'Files and checksums',
1633
+ '-------------------',
1634
+ 'manifest.json sha256 ' + manifestDigest,
1635
+ 'README.txt this file',
1636
+ 'receipt.docx generated delivery receipt (see manifest.json for its sha256)',
1637
+ 'SHA256SUMS sha256 of every other file in this pack',
1638
+ '',
1639
+ 'Evidence entries: ' + evidence.entryCount + ' (sources ' + evidence.sourceCount + ', missing ' + evidence.missingCount + ')',
1640
+ '(references and capped quotes only; see manifest.json evidence.entries)',
1641
+ '',
1642
+ 'Verify (offline, no ~/.advisers database needed)',
1643
+ '-----------------------------------------------',
1644
+ '1. advisers evidence verify <this-directory>',
1645
+ '2. or with coreutils: cd <this-directory> && sha256sum -c SHA256SUMS',
1646
+ '',
1647
+ 'The checksums detect edits made after generation. They are not a signature,',
1648
+ 'not a trusted timestamp and not notarization: anyone able to rewrite the whole',
1649
+ 'pack can recompute them. When the anchors line above says NONE, the pack only',
1650
+ 'proves internal consistency, not when or by whom it was produced.',
1651
+ '',
1652
+ 'Privacy and scope',
1653
+ '-----------------',
1654
+ '- Built locally; no network calls; verification does not open the ledger.',
1655
+ '- Contains relative paths, copies of the delivered files, SHA-256 digests and',
1656
+ ' evidence quotes capped at ' + MAX_QUOTE_CHARS + ' characters; no full turn bodies.',
1657
+ '- The recipient field is an operator-entered record. It is not an e-signature',
1658
+ ' and does not prove receipt, acceptance or agreement by the recipient.',
1659
+ '- Deleting this pack does not modify the local ledger or database.',
1660
+ )
1661
+ return lines.join('\n') + '\n'
1662
+ }
1663
+
1664
+ function writeReceiptPackDir(targetDir, fileContents, { overwrite = false } = {}) {
1665
+ const target = resolve(String(targetDir))
1666
+ mkdirSync(dirname(target), { recursive: true })
1667
+ let replaced = null
1668
+ if (existsSync(target)) {
1669
+ const stat = statSync(target)
1670
+ if (!stat.isDirectory()) throw new Error('receipt pack outDir exists and is not a directory: ' + target)
1671
+ const entries = readdirSync(target)
1672
+ if (entries.length && !overwrite) {
1673
+ throw new Error('receipt pack outDir is not empty: ' + target + ' (pass overwrite: true or choose a fresh directory)')
1674
+ }
1675
+ if (entries.length) {
1676
+ // Never delete the old directory tree: move it aside instead, so a mistake
1677
+ // with --out cannot destroy unrelated files.
1678
+ replaced = target + '.replaced-' + new Date().toISOString().replace(/[:.]/g, '-')
1679
+ renameSync(target, replaced)
1680
+ } else {
1681
+ rmdirSync(target)
1682
+ }
1683
+ }
1684
+ const staging = target + '.tmp-' + process.pid + '-' + randomUUID().slice(0, 8)
1685
+ mkdirSync(staging, { recursive: true, mode: RECEIPT_DIR_MODE })
1686
+ chmodSync(staging, RECEIPT_DIR_MODE)
1687
+ try {
1688
+ for (const path of [...fileContents.keys()].sort()) {
1689
+ if (isUnsafePackPath(path)) throw new Error('refusing to write unsafe pack path: ' + path)
1690
+ const bytes = toBytes(fileContents.get(path))
1691
+ const full = join(staging, ...path.split('/'))
1692
+ mkdirSync(dirname(full), { recursive: true, mode: RECEIPT_DIR_MODE })
1693
+ writeFileSync(full, bytes, { mode: RECEIPT_FILE_MODE })
1694
+ chmodSync(full, RECEIPT_FILE_MODE)
1695
+ }
1696
+ // Robustness audit P1-7: verify what actually reached the disk, not the
1697
+ // in-memory strings that were meant to be written.
1698
+ for (const [path, content] of fileContents) {
1699
+ const expected = toBytes(content)
1700
+ const full = join(staging, ...path.split('/'))
1701
+ const actual = readFileSync(full)
1702
+ if (actual.length !== expected.length) throw new Error('written pack file has the wrong size: ' + path)
1703
+ if (sha256Hex(actual) !== sha256Hex(expected)) throw new Error('written pack file hash mismatch: ' + path)
1704
+ if (process.platform !== 'win32' && (statSync(full).mode & 0o777) !== RECEIPT_FILE_MODE) {
1705
+ throw new Error('written pack file mode is not 0600: ' + path)
1706
+ }
1707
+ }
1708
+ renameSync(staging, target)
1709
+ } catch (error) {
1710
+ try {
1711
+ rmSync(staging, { recursive: true, force: true })
1712
+ } catch {
1713
+ // best-effort cleanup of our own staging directory only
1714
+ }
1715
+ if (replaced) {
1716
+ try {
1717
+ renameSync(replaced, target)
1718
+ } catch {
1719
+ error.message = error.message + ' (previous outDir contents are preserved at ' + replaced + ')'
1720
+ }
1721
+ }
1722
+ throw error
1723
+ }
1724
+ chmodSync(target, RECEIPT_DIR_MODE)
1725
+ return { outDir: target, replaced }
1726
+ }
1727
+
1728
+ /**
1729
+ * Build a delivery receipt pack (v1.1).
1730
+ *
1731
+ * The manifest records the delivered files (relative path / size / SHA-256),
1732
+ * the generator environment, the verify results, optional recipient and
1733
+ * timestamp anchors, and the evidence entries. receipt.docx is generated and
1734
+ * both it and every delivered artifact are covered by SHA256SUMS, so
1735
+ * verifyReceiptPackDir can detect any edit or missing file offline.
1736
+ *
1737
+ * @param {object} options
1738
+ * @param {Array|object} options.deliveries delivery record(s): {id, title, tool,
1739
+ * createdAt, validation, files}. Each file is a path string, a
1740
+ * {sourcePath} object, or a {content, name} object with embedded bytes.
1741
+ * @param {object|Array|string} [options.evidence] buildEvidencePack output,
1742
+ * evidence entries, or an evidence manifest string.
1743
+ * @param {object|Array} [options.verifyResults] results with a boolean ok
1744
+ * (verifyPack/verifyOffice results work as-is).
1745
+ * @param {object} [options.env] {advisersVersion, nodeVersion, templateName,
1746
+ * templateVersion, command, platform}; missing values are filled from
1747
+ * the current process.
1748
+ * @param {object|string} [options.recipient] optional {name, email, note}.
1749
+ * @param {object|Array} [options.anchors] optional external timestamp anchors:
1750
+ * {file, fileSha256, adapterId, issuedAt, proof}. An empty list means
1751
+ * "not anchored" and the pack discloses that.
1752
+ * @param {Date|string} [options.now]
1753
+ * @param {string} [options.outDir] when set, write the pack directory (0700,
1754
+ * files 0600) and verify the bytes on disk. Without it only the file
1755
+ * map is returned and the caller must keep the 0600 contract.
1756
+ * @param {boolean} [options.overwrite=false] allow replacing a non-empty
1757
+ * outDir; the old directory is moved aside, never deleted.
1758
+ * @param {Function|false} [options.docxBuilder] override receipt.docx builder
1759
+ * ((spec) => Buffer); false forces the built-in portable writer.
1760
+ * @param {Buffer|Uint8Array|string} [options.receiptDocx] pre-built receipt
1761
+ * bytes to include instead of generating one (still hashed + covered).
1762
+ * @returns {Promise<{files: Record<string, string|Buffer>, summary: object}>}
1763
+ */
1764
+ export async function buildReceiptPack(options = {}) {
1765
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
1766
+ throw new TypeError('buildReceiptPack expects an options object')
1767
+ }
1768
+ const createdAt = isoDate(options.now === undefined ? new Date() : options.now)
1769
+ const deliveries = normalizeReceiptDeliveries(options.deliveries)
1770
+ const evidence = normalizeReceiptEvidence(options.evidence)
1771
+ const verifyResults = normalizeReceiptVerifyResults(options.verifyResults)
1772
+ const verifyStatus = receiptVerifyStatus(verifyResults)
1773
+ const generator = normalizeReceiptGenerator(options.env)
1774
+ const recipient = normalizeReceiptRecipient(options.recipient)
1775
+ const anchors = normalizeReceiptAnchors(options.anchors)
1776
+ const deliveryFiles = []
1777
+ for (const delivery of deliveries) for (const file of delivery.files) deliveryFiles.push(file)
1778
+
1779
+ // Generate receipt.docx first: the manifest must carry its SHA-256, and the
1780
+ // receipt must not claim a manifest hash that does not exist yet (a hash cycle).
1781
+ // The receipt's own hash is therefore listed in SHA256SUMS/manifest, not inside
1782
+ // the document (a document cannot contain its own digest).
1783
+ const receiptSpec = receiptDocxSpec({
1784
+ createdAt,
1785
+ deliveries,
1786
+ evidence,
1787
+ verifyResults,
1788
+ verifyStatus,
1789
+ recipient,
1790
+ generator,
1791
+ anchors,
1792
+ deliveryFiles,
1793
+ receiptSha256: 'see SHA256SUMS',
1794
+ })
1795
+ const receiptBytes =
1796
+ options.receiptDocx !== undefined
1797
+ ? assertReceiptDocxBuffer(options.receiptDocx)
1798
+ : await buildReceiptDocxBytes(receiptSpec, options.docxBuilder)
1799
+ const receiptFile = { path: 'receipt.docx', size: receiptBytes.length, sha256: sha256Hex(receiptBytes) }
1800
+
1801
+ // An anchor must commit to a file whose final bytes already exist. manifest /
1802
+ // README / SHA256SUMS are produced after this point, so anchoring them here
1803
+ // would be circular; reject those with a clear message instead of lying.
1804
+ const knownHashes = new Map()
1805
+ for (const file of deliveryFiles) knownHashes.set(file.path, file.sha256)
1806
+ knownHashes.set(receiptFile.path, receiptFile.sha256)
1807
+ for (const anchor of anchors) {
1808
+ if (!knownHashes.has(anchor.file)) {
1809
+ throw new TypeError(
1810
+ 'anchor file must be a delivery file or receipt.docx: ' +
1811
+ anchor.file +
1812
+ ' (manifest/README/SHA256SUMS are generated after the anchors)',
1813
+ )
1814
+ }
1815
+ if (knownHashes.get(anchor.file) !== anchor.fileSha256) {
1816
+ throw new TypeError('anchor fileSha256 does not match the final bytes of ' + anchor.file)
1817
+ }
1818
+ }
1819
+
1820
+ const fileCount = deliveryFiles.length + RECEIPT_REQUIRED_FILES.length
1821
+ const manifestText =
1822
+ stableStringify({
1823
+ format: RECEIPT_MANIFEST_FORMAT,
1824
+ version: RECEIPT_MANIFEST_VERSION,
1825
+ createdAt,
1826
+ generator,
1827
+ recipient,
1828
+ deliveries: deliveries.map((delivery) => ({
1829
+ id: delivery.id,
1830
+ title: delivery.title,
1831
+ tool: delivery.tool,
1832
+ createdAt: delivery.createdAt,
1833
+ validation: delivery.validation,
1834
+ files: delivery.files.map((file) => ({ path: file.path, name: file.name, size: file.size, sha256: file.sha256 })),
1835
+ })),
1836
+ receipt: receiptFile,
1837
+ verify: verifyResults,
1838
+ verifyStatus,
1839
+ anchors,
1840
+ evidence,
1841
+ fileCount,
1842
+ }) + '\n'
1843
+ const manifestDigest = sha256Hex(manifestText)
1844
+
1845
+ const fileContents = new Map()
1846
+ for (const file of deliveryFiles) fileContents.set(file.path, file.content)
1847
+ fileContents.set('receipt.docx', receiptBytes)
1848
+ fileContents.set('manifest.json', manifestText)
1849
+ const readme = buildReceiptReadme({
1850
+ createdAt,
1851
+ generator,
1852
+ recipient,
1853
+ deliveries,
1854
+ evidence,
1855
+ verifyResults,
1856
+ verifyStatus,
1857
+ anchors,
1858
+ manifestDigest,
1859
+ })
1860
+ fileContents.set('README.txt', readme)
1861
+ // Everything except SHA256SUMS itself is covered by SHA256SUMS.
1862
+ fileContents.set(RECEIPT_SHA256SUMS_FILE, buildReceiptSums(fileContents))
1863
+
1864
+ const files = {}
1865
+ for (const path of [...fileContents.keys()].sort()) files[path] = fileContents.get(path)
1866
+ const summary = {
1867
+ format: RECEIPT_MANIFEST_FORMAT,
1868
+ version: RECEIPT_MANIFEST_VERSION,
1869
+ createdAt,
1870
+ deliveryCount: deliveries.length,
1871
+ fileCount,
1872
+ verifyStatus,
1873
+ recipient: recipient || null,
1874
+ generator,
1875
+ evidence: {
1876
+ entryCount: evidence.entryCount,
1877
+ counts: evidence.counts,
1878
+ sourceCount: evidence.sourceCount,
1879
+ missingCount: evidence.missingCount,
1880
+ },
1881
+ anchored: anchors.length > 0,
1882
+ fileMode: RECEIPT_FILE_MODE,
1883
+ manifestDigest,
1884
+ receiptSha256: receiptFile.sha256,
1885
+ files: receiptFilesList(fileContents),
1886
+ }
1887
+ if (options.outDir !== undefined && options.outDir !== null && options.outDir !== '') {
1888
+ const written = writeReceiptPackDir(options.outDir, fileContents, { overwrite: options.overwrite === true })
1889
+ summary.outDir = written.outDir
1890
+ summary.replaced = written.replaced
1891
+ summary.diskVerified = true
1892
+ }
1893
+ return { files, summary }
1894
+ }
741
1895
  // ---------------------------------------------------------------------------
742
1896
  // optional CLI helper: rows for the office DOCX builder (no docx is created here)
743
1897
  // ---------------------------------------------------------------------------