advisers 0.1.0-preview.4 → 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.
Files changed (53) hide show
  1. package/LICENSE +131 -21
  2. package/NOTICE +34 -0
  3. package/README-zh.md +40 -9
  4. package/README.md +53 -10
  5. package/THIRD-PARTY-NOTICES.md +277 -0
  6. package/bin/advisers.js +4230 -122
  7. package/index.js +1 -1
  8. package/lib/agent.js +414 -0
  9. package/lib/attachments.js +283 -0
  10. package/lib/capture.js +168 -0
  11. package/lib/context-window.js +123 -0
  12. package/lib/digest.js +27 -0
  13. package/lib/doc-review.js +30 -0
  14. package/lib/egress.js +27 -0
  15. package/lib/evidence.js +1995 -0
  16. package/lib/ical.js +542 -0
  17. package/lib/imap.js +181 -0
  18. package/lib/importers.js +1001 -0
  19. package/lib/learning.js +46 -0
  20. package/lib/mcp-server.js +869 -0
  21. package/lib/model.js +307 -0
  22. package/lib/notify.js +189 -0
  23. package/lib/nudge.js +10 -0
  24. package/lib/ocr.js +47 -0
  25. package/lib/pdf.js +105 -0
  26. package/lib/pet-brief-store.js +51 -0
  27. package/lib/pet-brief.js +644 -0
  28. package/lib/receipt-verify.js +624 -0
  29. package/lib/relative-date.js +393 -0
  30. package/lib/remind.js +690 -0
  31. package/lib/research.js +193 -0
  32. package/lib/review.js +88 -0
  33. package/lib/routine.js +22 -0
  34. package/lib/safety/classifier.js +392 -0
  35. package/lib/safety/explain.js +157 -0
  36. package/lib/safety/index.js +333 -0
  37. package/lib/safety/redact.js +212 -0
  38. package/lib/safety/rules.js +824 -0
  39. package/lib/scheduler.js +399 -0
  40. package/lib/source.js +294 -0
  41. package/lib/sqlite.js +1022 -0
  42. package/lib/sync.js +129 -0
  43. package/lib/timestamp.js +45 -0
  44. package/lib/tos/index.js +332 -0
  45. package/lib/tos/manifest.json +32 -0
  46. package/lib/tos/privacy.zh-CN.md +136 -0
  47. package/lib/tos/safety.zh-CN.md +101 -0
  48. package/lib/tos/summary.zh-CN.md +12 -0
  49. package/lib/tos/terms.zh-CN.md +439 -0
  50. package/lib/ui.js +49 -0
  51. package/lib/undo.js +83 -0
  52. package/lib/vault.js +51 -0
  53. package/package.json +26 -4
@@ -0,0 +1,1995 @@
1
+ /**
2
+ * E3: evidence chain, evidence pack (v1) and delivery receipt pack (v1.1).
3
+ *
4
+ * Every ledger row that claims something about the world must point back to the
5
+ * conversation turn it came from. This module walks those pointers (a turn is
6
+ * only trusted when both its id and its conversation id agree with the
7
+ * evidence record), and then packages the references — never the full
8
+ * transcript — into a small verifiable directory:
9
+ *
10
+ * manifest.json entries + resolved sources (quote capped at 500 chars) + SHA-256
11
+ * README.txt human summary and verification instructions
12
+ * SHA256SUMS sha256 of manifest.json and README.txt
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
+ *
21
+ * Constraints baked into the design:
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).
24
+ * - No fabrication: an unknown turn, a session mismatch or an unparseable
25
+ * `session#turn` ref goes to `missing`; nothing is guessed.
26
+ * - No leaks: no absolute filesystem paths, no full turn/transcript bodies and
27
+ * no matter summaries/snippets other than the evidence quotes themselves.
28
+ * - SHA256SUMS is tamper-evidence (accidental/deterministic edits), not a
29
+ * signature: whoever can rewrite the whole pack can recompute the sums.
30
+ *
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.
35
+ */
36
+
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'
51
+
52
+ /** Quotes are verbatim evidence but capped, so a pack never carries a full body. */
53
+ export const MAX_QUOTE_CHARS = 500
54
+ export const MANIFEST_FORMAT = 'advisers-evidence-pack'
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
+
83
+ /** Header for the optional DOCX table helper, kept next to the rows it describes. */
84
+ export const DOCX_EVIDENCE_HEADERS = ['类型', '证据ID', '来源(session#turn)', '摘录', '状态']
85
+
86
+ const REQUIRED_PACK_FILES = ['manifest.json', 'README.txt']
87
+ const README_ENTRY_CAP = 100
88
+ const README_REF_CAP = 5
89
+
90
+ const KIND_ALIASES = Object.freeze({
91
+ commitment: 'commitment',
92
+ commitments: 'commitment',
93
+ cm: 'commitment',
94
+ fact: 'fact',
95
+ facts: 'fact',
96
+ preference: 'preference',
97
+ preferences: 'preference',
98
+ pref: 'preference',
99
+ })
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // bytes, hashes and canonical JSON
103
+ // ---------------------------------------------------------------------------
104
+
105
+ function toBytes(data) {
106
+ if (typeof data === 'string') return Buffer.from(data, 'utf8')
107
+ if (Buffer.isBuffer(data)) return data
108
+ if (data instanceof Uint8Array) return Buffer.from(data.buffer, data.byteOffset, data.byteLength)
109
+ if (data instanceof ArrayBuffer) return Buffer.from(data)
110
+ return null
111
+ }
112
+
113
+ function textOf(value) {
114
+ if (typeof value === 'string') return value
115
+ const bytes = toBytes(value)
116
+ return bytes ? bytes.toString('utf8') : null
117
+ }
118
+
119
+ /** SHA-256 hex digest of a UTF-8 string or raw bytes. */
120
+ export function sha256Hex(data) {
121
+ const bytes = toBytes(data)
122
+ if (!bytes) throw new TypeError('sha256Hex expects a string, Buffer, Uint8Array or ArrayBuffer')
123
+ return createHash('sha256').update(bytes).digest('hex')
124
+ }
125
+
126
+ function normalizeJson(value) {
127
+ if (value === undefined) return null
128
+ if (value instanceof Date) return value.toISOString()
129
+ if (Array.isArray(value)) return value.map((item) => normalizeJson(item))
130
+ if (value && typeof value === 'object') {
131
+ const out = {}
132
+ for (const key of Object.keys(value).sort()) {
133
+ if (value[key] === undefined) continue
134
+ out[key] = normalizeJson(value[key])
135
+ }
136
+ return out
137
+ }
138
+ if (typeof value === 'number' && !Number.isFinite(value)) return null
139
+ return value
140
+ }
141
+
142
+ /**
143
+ * Deterministic JSON text: object keys are sorted at every depth and
144
+ * `undefined` fields are dropped, so identical inputs produce identical bytes.
145
+ */
146
+ export function stableStringify(value, { space = 2 } = {}) {
147
+ return JSON.stringify(normalizeJson(value), null, space)
148
+ }
149
+
150
+ function isoDate(value) {
151
+ if (value === undefined || value === null) return new Date().toISOString()
152
+ const date = value instanceof Date ? value : new Date(value)
153
+ if (Number.isNaN(date.getTime())) throw new TypeError(`invalid date: ${value}`)
154
+ return date.toISOString()
155
+ }
156
+
157
+ // ---------------------------------------------------------------------------
158
+ // source refs: `sessionId#turnId`
159
+ // ---------------------------------------------------------------------------
160
+
161
+ /**
162
+ * Parse a `SourceRef.ref` of the form `sessionId#turnId`.
163
+ * Returns `null` when the ref cannot be parsed — callers must put that into
164
+ * `missing` rather than guessing a session.
165
+ */
166
+ export function parseSourceRef(ref) {
167
+ if (typeof ref !== 'string') return null
168
+ const text = ref.trim()
169
+ const split = text.indexOf('#')
170
+ if (split <= 0) return null
171
+ const sessionId = text.slice(0, split)
172
+ const turnId = text.slice(split + 1)
173
+ if (!sessionId || !turnId || turnId.includes('#')) return null
174
+ return { sessionId, turnId }
175
+ }
176
+
177
+ function lookupTurn(store, sessionId, turnId) {
178
+ if (!store || typeof store !== 'object') return { turn: undefined, failed: false }
179
+ let failed = false
180
+ if (typeof store.getTurn === 'function') {
181
+ try {
182
+ const turn = store.getTurn(turnId)
183
+ if (turn) return { turn }
184
+ } catch {
185
+ failed = true
186
+ }
187
+ }
188
+ // Older stores (and this module at HEAD before getTurn landed) only expose
189
+ // listTurns; scan the evidence's own session, never another one.
190
+ if (sessionId && typeof store.listTurns === 'function') {
191
+ try {
192
+ const turns = store.listTurns(sessionId, 10_000)
193
+ const found = Array.isArray(turns) ? turns.find((turn) => turn?.id === turnId) : undefined
194
+ if (found) return { turn: found }
195
+ failed = false
196
+ } catch {
197
+ failed = true
198
+ }
199
+ }
200
+ return { turn: undefined, failed }
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // ledger lookups
205
+ // ---------------------------------------------------------------------------
206
+
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) {
270
+ if (!ledger || !id) return undefined
271
+ if (index?.commitments instanceof Map) return index.commitments.get(id)
272
+ if (typeof ledger.getCommitment === 'function') {
273
+ const hit = ledger.getCommitment(id)
274
+ if (hit) return hit
275
+ }
276
+ const rows = typeof ledger.listCommitments === 'function' ? ledger.listCommitments() : []
277
+ return rows.find((row) => row?.id === id)
278
+ }
279
+
280
+ function findFact(ledger, id, index) {
281
+ if (!ledger || !id) return undefined
282
+ if (index?.facts instanceof Map) return index.facts.get(id)
283
+ if (typeof ledger.getFact === 'function') {
284
+ const hit = ledger.getFact(id)
285
+ if (hit) return hit
286
+ }
287
+ let rows = []
288
+ if (typeof ledger.listFacts === 'function') {
289
+ try {
290
+ rows = ledger.listFacts(undefined, true)
291
+ } catch {
292
+ try {
293
+ rows = ledger.listFacts()
294
+ } catch {
295
+ rows = []
296
+ }
297
+ }
298
+ }
299
+ let hit = rows.find((row) => row?.id === id)
300
+ if (hit) return hit
301
+ // Last resort: the portable snapshot, which includes tombstones/history.
302
+ try {
303
+ return (ledger.toJSON?.().facts ?? []).find((row) => row?.id === id)
304
+ } catch {
305
+ return undefined
306
+ }
307
+ }
308
+
309
+ function findPreference(ledger, id, index) {
310
+ if (!ledger || !id) return undefined
311
+ if (index?.preferences instanceof Map) return index.preferences.get(id)
312
+ if (typeof ledger.findPreference === 'function') {
313
+ const hit = ledger.findPreference(id)
314
+ if (hit) return hit
315
+ }
316
+ let rows = []
317
+ try {
318
+ rows = ledger.listPreferences({ includeCandidates: true })
319
+ } catch {
320
+ rows = []
321
+ }
322
+ return rows.find((row) => row?.id === id)
323
+ }
324
+
325
+ // ---------------------------------------------------------------------------
326
+ // evidence traceback
327
+ // ---------------------------------------------------------------------------
328
+
329
+ function sourceRefKey(item) {
330
+ if (!item || typeof item !== 'object') return `\u0000${String(item)}`
331
+ return `${typeof item.ref === 'string' ? item.ref : ''}\u0000${typeof item.quote === 'string' ? item.quote : ''}`
332
+ }
333
+
334
+ function primarySourceCandidates(source) {
335
+ if (!source || typeof source !== 'object') return []
336
+ const hasRef = typeof source.ref === 'string' && source.ref.length > 0
337
+ const hasQuote = typeof source.quote === 'string' && source.quote.length > 0
338
+ return hasRef || hasQuote ? [source] : []
339
+ }
340
+
341
+ function collectSourceRefs(...lists) {
342
+ const seen = new Set()
343
+ const out = []
344
+ for (const list of lists) {
345
+ if (!Array.isArray(list)) continue
346
+ for (const item of list) {
347
+ const key = sourceRefKey(item)
348
+ if (seen.has(key)) continue
349
+ seen.add(key)
350
+ out.push(item)
351
+ }
352
+ }
353
+ return out
354
+ }
355
+
356
+ function resolveSourceRefs(store, items) {
357
+ const sources = []
358
+ const missing = []
359
+ for (const item of items) {
360
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
361
+ missing.push({ reason: 'invalid_source' })
362
+ continue
363
+ }
364
+ const quote = typeof item.quote === 'string' ? item.quote : ''
365
+ const ref = typeof item.ref === 'string' ? item.ref : ''
366
+ if (!ref) {
367
+ missing.push({ quote, reason: 'no_ref' })
368
+ continue
369
+ }
370
+ const parsed = parseSourceRef(ref)
371
+ if (!parsed) {
372
+ missing.push({ ref, quote, reason: 'unparseable_ref' })
373
+ continue
374
+ }
375
+ const lookup = lookupTurn(store, parsed.sessionId, parsed.turnId)
376
+ if (!lookup.turn) {
377
+ missing.push({
378
+ ref,
379
+ quote,
380
+ sessionId: parsed.sessionId,
381
+ turnId: parsed.turnId,
382
+ reason: lookup.failed ? 'lookup_failed' : 'turn_not_found',
383
+ })
384
+ continue
385
+ }
386
+ if (lookup.turn.conversationId !== parsed.sessionId) {
387
+ missing.push({ ref, quote, sessionId: parsed.sessionId, turnId: parsed.turnId, reason: 'session_mismatch' })
388
+ continue
389
+ }
390
+ sources.push({ sessionId: parsed.sessionId, turnId: parsed.turnId, quote, turn: lookup.turn })
391
+ }
392
+ return { sources, missing }
393
+ }
394
+
395
+ /**
396
+ * Trace a commitment's evidence back to real turns.
397
+ *
398
+ * @returns {{ commitment: object|undefined,
399
+ * sources: Array<{sessionId: string, turnId: string, quote: string, turn: object}>,
400
+ * missing: Array<{sessionId?: string, turnId?: string, quote?: string, id?: string, reason: string}> }}
401
+ */
402
+ export function evidenceForCommitment(store, ledger, commitmentId, index) {
403
+ const commitment = findCommitment(ledger, commitmentId, index)
404
+ if (!commitment) {
405
+ return { commitment: undefined, sources: [], missing: [{ id: commitmentId, reason: 'commitment_not_found' }] }
406
+ }
407
+ const sources = []
408
+ const missing = []
409
+ const evidence = Array.isArray(commitment.evidence) ? commitment.evidence : []
410
+ for (const item of evidence) {
411
+ const sessionId = typeof item?.sessionId === 'string' ? item.sessionId : ''
412
+ const turnId = typeof item?.turnId === 'string' ? item.turnId : ''
413
+ const quote = typeof item?.quote === 'string' ? item.quote : ''
414
+ if (!sessionId || !turnId) {
415
+ missing.push({
416
+ sessionId: sessionId || undefined,
417
+ turnId: turnId || undefined,
418
+ quote,
419
+ reason: 'invalid_evidence',
420
+ })
421
+ continue
422
+ }
423
+ const lookup = lookupTurn(store, sessionId, turnId)
424
+ if (!lookup.turn) {
425
+ missing.push({ sessionId, turnId, quote, reason: lookup.failed ? 'lookup_failed' : 'turn_not_found' })
426
+ continue
427
+ }
428
+ if (lookup.turn.conversationId !== sessionId) {
429
+ missing.push({ sessionId, turnId, quote, reason: 'session_mismatch' })
430
+ continue
431
+ }
432
+ sources.push({ sessionId, turnId, quote, turn: lookup.turn })
433
+ }
434
+ return { commitment, sources, missing }
435
+ }
436
+
437
+ /** Trace a fact's `SourceRef[]` (plus its primary `source`) back to turns. */
438
+ export function evidenceForFact(store, ledger, factId, index) {
439
+ const fact = findFact(ledger, factId, index)
440
+ if (!fact) {
441
+ return { fact: undefined, sources: [], missing: [{ id: factId, reason: 'fact_not_found' }] }
442
+ }
443
+ const refs = collectSourceRefs(fact.evidence, primarySourceCandidates(fact.source))
444
+ const resolved = resolveSourceRefs(store, refs)
445
+ return { fact, sources: resolved.sources, missing: resolved.missing }
446
+ }
447
+
448
+ /** Trace a preference's `SourceRef[]` (plus its primary `source`) back to turns. */
449
+ export function evidenceForPreference(store, ledger, preferenceId, index) {
450
+ const preference = findPreference(ledger, preferenceId, index)
451
+ if (!preference) {
452
+ return { preference: undefined, sources: [], missing: [{ id: preferenceId, reason: 'preference_not_found' }] }
453
+ }
454
+ const refs = collectSourceRefs(preference.evidence, primarySourceCandidates(preference.source))
455
+ const resolved = resolveSourceRefs(store, refs)
456
+ return { preference, sources: resolved.sources, missing: resolved.missing }
457
+ }
458
+
459
+ // ---------------------------------------------------------------------------
460
+ // manifest
461
+ // ---------------------------------------------------------------------------
462
+
463
+ function compareEntries(a, b) {
464
+ const left = `${a?.kind ?? ''}\u0000${a?.id ?? ''}`
465
+ const right = `${b?.kind ?? ''}\u0000${b?.id ?? ''}`
466
+ return left < right ? -1 : left > right ? 1 : 0
467
+ }
468
+
469
+ /**
470
+ * Build the manifest bytes. `entries` are the compact evidence entries produced
471
+ * by `buildEvidencePack` (an entry may also be any JSON-serializable object).
472
+ * Passing a fixed `createdAt` makes the output reproducible byte-for-byte.
473
+ *
474
+ * @returns {string} canonical JSON text with a trailing newline
475
+ */
476
+ export function manifestFor(entries, { createdAt } = {}) {
477
+ const list = (Array.isArray(entries) ? entries : [])
478
+ .filter((entry) => entry && typeof entry === 'object' && !Array.isArray(entry))
479
+ .map((entry) => ({ ...entry }))
480
+ list.sort(compareEntries)
481
+ return `${stableStringify({
482
+ format: MANIFEST_FORMAT,
483
+ version: MANIFEST_VERSION,
484
+ createdAt: isoDate(createdAt),
485
+ entryCount: list.length,
486
+ entries: list,
487
+ })}\n`
488
+ }
489
+
490
+ // ---------------------------------------------------------------------------
491
+ // pack assembly
492
+ // ---------------------------------------------------------------------------
493
+
494
+ function clampQuote(value) {
495
+ const text = typeof value === 'string' ? value : ''
496
+ const chars = Array.from(text)
497
+ const truncated = chars.length > MAX_QUOTE_CHARS
498
+ const quote = truncated ? chars.slice(0, MAX_QUOTE_CHARS).join('') : text
499
+ return { quote, quoteChars: chars.length, truncated, quoteSha256: sha256Hex(quote) }
500
+ }
501
+
502
+ function formatRef(sessionId, turnId) {
503
+ const parts = []
504
+ if (typeof sessionId === 'string' && sessionId) parts.push(sessionId)
505
+ if (typeof turnId === 'string' && turnId) parts.push(turnId)
506
+ return parts.join('#')
507
+ }
508
+
509
+ function compactSource(source) {
510
+ const clamped = clampQuote(source?.quote)
511
+ const entry = {
512
+ sessionId: typeof source?.sessionId === 'string' ? source.sessionId : '',
513
+ turnId: typeof source?.turnId === 'string' ? source.turnId : '',
514
+ ...clamped,
515
+ }
516
+ // Turn sequence/role are provenance metadata, not body text.
517
+ if (Number.isInteger(source?.turn?.seq)) entry.turnSeq = source.turn.seq
518
+ if (typeof source?.turn?.role === 'string') entry.turnRole = source.turn.role
519
+ return entry
520
+ }
521
+
522
+ function compactMissing(item) {
523
+ const out = { reason: typeof item?.reason === 'string' ? item.reason : 'unknown' }
524
+ for (const key of ['id', 'ref', 'sessionId', 'turnId']) {
525
+ if (typeof item?.[key] === 'string' && item[key]) out[key] = item[key]
526
+ }
527
+ if (typeof item?.quote === 'string' && item.quote.length) Object.assign(out, clampQuote(item.quote))
528
+ return out
529
+ }
530
+
531
+ function compactEntry(entry) {
532
+ return {
533
+ kind: typeof entry.kind === 'string' ? entry.kind : 'unknown',
534
+ id: String(entry.id ?? ''),
535
+ found: Boolean(entry.found),
536
+ sources: (Array.isArray(entry.sources) ? entry.sources : []).map(compactSource),
537
+ missing: (Array.isArray(entry.missing) ? entry.missing : []).map(compactMissing),
538
+ }
539
+ }
540
+
541
+ function inferKindFromId(id) {
542
+ if (/^cm[_:]/.test(id)) return 'commitment'
543
+ if (/^fact[_:]/.test(id)) return 'fact'
544
+ if (/^pref[_:]/.test(id)) return 'preference'
545
+ return undefined
546
+ }
547
+
548
+ function normalizeKind(kind) {
549
+ if (typeof kind !== 'string') return undefined
550
+ return KIND_ALIASES[kind.trim().toLowerCase()]
551
+ }
552
+
553
+ function classifyKind(ledger, id, kind, index) {
554
+ const explicit = normalizeKind(kind)
555
+ if (explicit) return explicit
556
+ const inferred = inferKindFromId(id)
557
+ if (inferred) return inferred
558
+ if (findCommitment(ledger, id, index)) return 'commitment'
559
+ if (findFact(ledger, id, index)) return 'fact'
560
+ if (findPreference(ledger, id, index)) return 'preference'
561
+ return 'unknown'
562
+ }
563
+
564
+ function normalizeRequestedIds(ids, ledger, index) {
565
+ const out = { commitments: [], facts: [], preferences: [], unknown: [] }
566
+ const seen = new Set()
567
+ const push = (id, kind) => {
568
+ const value = id === undefined || id === null ? '' : String(id).trim()
569
+ if (!value) return
570
+ const resolved = classifyKind(ledger, value, kind, index)
571
+ const key = `${resolved}\u0000${value}`
572
+ if (seen.has(key)) return
573
+ seen.add(key)
574
+ if (resolved === 'commitment') out.commitments.push(value)
575
+ else if (resolved === 'fact') out.facts.push(value)
576
+ else if (resolved === 'preference') out.preferences.push(value)
577
+ else out.unknown.push(value)
578
+ }
579
+ const pushItem = (item, fallbackKind) => {
580
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
581
+ const kind = normalizeKind(item.kind ?? item.type) ?? fallbackKind
582
+ push(item.id ?? item.value, kind)
583
+ return
584
+ }
585
+ push(item, fallbackKind)
586
+ }
587
+ const pushMany = (value, fallbackKind) => {
588
+ if (value === undefined || value === null) return
589
+ if (Array.isArray(value)) {
590
+ for (const item of value) pushItem(item, fallbackKind)
591
+ return
592
+ }
593
+ pushItem(value, fallbackKind)
594
+ }
595
+ if (Array.isArray(ids) || typeof ids === 'string') {
596
+ pushMany(ids, undefined)
597
+ } else if (ids && typeof ids === 'object') {
598
+ pushMany(ids.commitments ?? ids.commitmentIds ?? ids.commitment, 'commitment')
599
+ pushMany(ids.facts ?? ids.factIds ?? ids.fact, 'fact')
600
+ pushMany(ids.preferences ?? ids.preferenceIds ?? ids.preference, 'preference')
601
+ if (ids.ids !== undefined) pushMany(ids.ids, undefined)
602
+ }
603
+ return out
604
+ }
605
+
606
+ function buildReadme({ createdAt, entries, manifestDigest }) {
607
+ const counts = { commitment: 0, fact: 0, preference: 0, unknown: 0 }
608
+ let sourceCount = 0
609
+ let missingCount = 0
610
+ let truncatedCount = 0
611
+ for (const entry of entries) {
612
+ counts[entry.kind] = (counts[entry.kind] ?? 0) + 1
613
+ sourceCount += entry.sources.length
614
+ missingCount += entry.missing.length
615
+ truncatedCount += entry.sources.filter((source) => source.truncated).length
616
+ }
617
+ const lines = [
618
+ 'Advisers evidence pack',
619
+ '======================',
620
+ '',
621
+ `format: ${MANIFEST_FORMAT} v${MANIFEST_VERSION}`,
622
+ `created: ${createdAt}`,
623
+ `entries: ${entries.length} (commitment ${counts.commitment}, fact ${counts.fact}, preference ${counts.preference}, unknown ${counts.unknown})`,
624
+ `sources: ${sourceCount} resolved, ${missingCount} missing`,
625
+ `quotes: verbatim, at most ${MAX_QUOTE_CHARS} characters each; ${truncatedCount} truncated`,
626
+ '',
627
+ 'Files',
628
+ '-----',
629
+ `manifest.json sha256 ${manifestDigest}`,
630
+ 'README.txt this file',
631
+ 'SHA256SUMS sha256 of manifest.json and README.txt',
632
+ '',
633
+ 'Verify',
634
+ '------',
635
+ 'Run `sha256sum -c SHA256SUMS` in a directory containing manifest.json and README.txt.',
636
+ 'The checksums detect later edits to the pack. They are not a signature: anyone able to',
637
+ 'rewrite the whole pack can recompute them.',
638
+ '',
639
+ 'Entries (quotes and full traceback live in manifest.json)',
640
+ '--------------------------------------------------------',
641
+ ]
642
+ if (!entries.length) lines.push('(no evidence requested)')
643
+ const shown = entries.slice(0, README_ENTRY_CAP)
644
+ for (const entry of shown) {
645
+ lines.push(
646
+ `- ${entry.kind} ${entry.id} sources=${entry.sources.length} missing=${entry.missing.length}${entry.found ? '' : ' (record not found)'}`,
647
+ )
648
+ const refs = entry.sources.slice(0, README_REF_CAP)
649
+ for (const source of refs) {
650
+ lines.push(` source ${formatRef(source.sessionId, source.turnId)}${source.truncated ? ' (quote truncated)' : ''}`)
651
+ }
652
+ if (entry.sources.length > refs.length) lines.push(` ... ${entry.sources.length - refs.length} more source(s)`)
653
+ const missingShown = entry.missing.slice(0, README_REF_CAP)
654
+ for (const item of missingShown) {
655
+ const ref = item.ref || formatRef(item.sessionId, item.turnId) || item.id || ''
656
+ lines.push(` missing ${item.reason}${ref ? ` (${ref})` : ''}`)
657
+ }
658
+ if (entry.missing.length > missingShown.length) {
659
+ lines.push(` ... ${entry.missing.length - missingShown.length} more missing`)
660
+ }
661
+ }
662
+ if (entries.length > shown.length) {
663
+ lines.push(`... ${entries.length - shown.length} more entr${entries.length - shown.length === 1 ? 'y' : 'ies'} — see manifest.json`)
664
+ }
665
+ lines.push(
666
+ '',
667
+ 'Privacy and scope',
668
+ '-----------------',
669
+ '- Built locally from the ledger and the turn store; this module performs no network calls.',
670
+ `- Contains references (session#turn), verbatim quotes capped at ${MAX_QUOTE_CHARS} characters, and SHA-256 digests only.`,
671
+ '- Contains no absolute filesystem paths, no full turn/transcript bodies, and no matter summaries.',
672
+ '- Deleting the pack does not modify the local ledger or database.',
673
+ '- Hashes prove the pack was not altered after generation; they do not prove the quotes are true.',
674
+ )
675
+ return `${lines.join('\n')}\n`
676
+ }
677
+
678
+ /**
679
+ * Assemble the three-file evidence pack.
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
+ *
687
+ * @param {object} options
688
+ * @param {object} options.store SqliteStore-like (`getTurn`/`listTurns`, `getTurn` optional)
689
+ * @param {object} options.ledger Ledger instance (listCommitments/listFacts/findPreference)
690
+ * @param {object|Array|string} [options.ids] `{commitments, facts, preferences}`, an id array,
691
+ * a single id, or `[{kind, id}]`. `cm_`/`fact_`/`pref_` prefixes are inferred.
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.
696
+ * @returns {{ files: Record<string, string>, summary: object }}
697
+ * files: `{ 'manifest.json': string, 'README.txt': string, 'SHA256SUMS': string }`
698
+ */
699
+ export function buildEvidencePack({
700
+ store,
701
+ ledger,
702
+ ids,
703
+ now = new Date(),
704
+ limit = DEFAULT_MAX_EVIDENCE_ENTRIES,
705
+ all = false,
706
+ } = {}) {
707
+ if (!ledger || typeof ledger !== 'object') throw new TypeError('buildEvidencePack requires a ledger')
708
+ if (!store || typeof store !== 'object') throw new TypeError('buildEvidencePack requires a store')
709
+ const createdAt = isoDate(now)
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)
723
+ const entries = []
724
+
725
+ for (const id of requested.commitments) {
726
+ const result = evidenceForCommitment(store, ledger, id, index)
727
+ entries.push({
728
+ kind: 'commitment',
729
+ id,
730
+ found: Boolean(result.commitment),
731
+ sources: result.sources,
732
+ missing: result.missing,
733
+ })
734
+ }
735
+ for (const id of requested.facts) {
736
+ const result = evidenceForFact(store, ledger, id, index)
737
+ entries.push({ kind: 'fact', id, found: Boolean(result.fact), sources: result.sources, missing: result.missing })
738
+ }
739
+ for (const id of requested.preferences) {
740
+ const result = evidenceForPreference(store, ledger, id, index)
741
+ entries.push({
742
+ kind: 'preference',
743
+ id,
744
+ found: Boolean(result.preference),
745
+ sources: result.sources,
746
+ missing: result.missing,
747
+ })
748
+ }
749
+ for (const id of requested.unknown) {
750
+ entries.push({ kind: 'unknown', id, found: false, sources: [], missing: [{ id, reason: 'record_not_found' }] })
751
+ }
752
+
753
+ const compacted = entries
754
+ .map(compactEntry)
755
+ .sort(compareEntries)
756
+
757
+ const manifestJson = manifestFor(compacted, { createdAt })
758
+ const manifestDigest = sha256Hex(manifestJson)
759
+ const readme = buildReadme({ createdAt, entries: compacted, manifestDigest })
760
+ const readmeDigest = sha256Hex(readme)
761
+ const sums = [`${readmeDigest} README.txt`, `${manifestDigest} manifest.json`].join('\n') + '\n'
762
+
763
+ const counts = { commitment: 0, fact: 0, preference: 0, unknown: 0 }
764
+ let sourceCount = 0
765
+ let missingCount = 0
766
+ let truncatedCount = 0
767
+ for (const entry of compacted) {
768
+ counts[entry.kind] = (counts[entry.kind] ?? 0) + 1
769
+ sourceCount += entry.sources.length
770
+ missingCount += entry.missing.length
771
+ truncatedCount += entry.sources.filter((source) => source.truncated).length
772
+ }
773
+
774
+ return {
775
+ files: {
776
+ 'manifest.json': manifestJson,
777
+ 'README.txt': readme,
778
+ 'SHA256SUMS': sums,
779
+ },
780
+ summary: {
781
+ format: MANIFEST_FORMAT,
782
+ version: MANIFEST_VERSION,
783
+ createdAt,
784
+ entryCount: compacted.length,
785
+ counts,
786
+ sourceCount,
787
+ missingCount,
788
+ truncatedCount,
789
+ notFound: compacted.filter((entry) => !entry.found).map((entry) => entry.id),
790
+ fileHashes: { 'manifest.json': manifestDigest, 'README.txt': readmeDigest },
791
+ entries: compacted,
792
+ },
793
+ }
794
+ }
795
+
796
+ // ---------------------------------------------------------------------------
797
+ // verification
798
+ // ---------------------------------------------------------------------------
799
+
800
+ export function isUnsafePackPath(name) {
801
+ if (!name) return true
802
+ if (name.startsWith('/') || name.startsWith('\\')) return true
803
+ if (/^[A-Za-z]:[\\/]/.test(name)) return true
804
+ return name.split(/[\\/]/).some((part) => part === '..')
805
+ }
806
+
807
+ /**
808
+ * Recompute SHA256SUMS. A pack is `ok` only when every checksum matches, both
809
+ * core files are covered, the manifest parses, and no extra file is smuggled in
810
+ * unhashed. Tampering with any pack file must flip `ok` to false.
811
+ *
812
+ * @returns {{ok: boolean, errors: string[]}}
813
+ */
814
+ export function verifyPack(files) {
815
+ const errors = []
816
+ if (!files || typeof files !== 'object' || Array.isArray(files)) {
817
+ return { ok: false, errors: ['pack must be an object mapping file names to contents'] }
818
+ }
819
+ const sumsText = textOf(files.SHA256SUMS)
820
+ if (sumsText === null) return { ok: false, errors: ['SHA256SUMS is missing or unreadable'] }
821
+
822
+ const listed = new Map()
823
+ for (const raw of sumsText.split(/\r?\n/)) {
824
+ const line = raw.trim()
825
+ if (!line) continue
826
+ const match = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line)
827
+ if (!match) {
828
+ errors.push(`malformed SHA256SUMS line: ${line.slice(0, 80)}`)
829
+ continue
830
+ }
831
+ const name = match[2].trim()
832
+ if (!name) {
833
+ errors.push('malformed SHA256SUMS line: empty file name')
834
+ continue
835
+ }
836
+ if (isUnsafePackPath(name)) {
837
+ errors.push(`unsafe path in SHA256SUMS: ${name}`)
838
+ continue
839
+ }
840
+ if (name === 'SHA256SUMS') {
841
+ errors.push('SHA256SUMS must not list itself')
842
+ continue
843
+ }
844
+ if (listed.has(name)) {
845
+ errors.push(`duplicate entry in SHA256SUMS: ${name}`)
846
+ continue
847
+ }
848
+ listed.set(name, match[1].toLowerCase())
849
+ }
850
+
851
+ for (const name of REQUIRED_PACK_FILES) {
852
+ if (!listed.has(name)) errors.push(`SHA256SUMS does not cover ${name}`)
853
+ }
854
+
855
+ for (const [name, expected] of listed) {
856
+ const bytes = toBytes(files[name])
857
+ if (!bytes) {
858
+ errors.push(`missing file: ${name}`)
859
+ continue
860
+ }
861
+ if (sha256Hex(bytes) !== expected) errors.push(`hash mismatch: ${name}`)
862
+ }
863
+
864
+ for (const name of Object.keys(files)) {
865
+ if (name === 'SHA256SUMS') continue
866
+ if (!listed.has(name)) errors.push(`file not covered by SHA256SUMS: ${name}`)
867
+ if (files[name] === undefined || files[name] === null) errors.push(`missing file: ${name}`)
868
+ }
869
+
870
+ const manifestText = textOf(files['manifest.json'])
871
+ if (manifestText !== null) {
872
+ try {
873
+ const manifest = JSON.parse(manifestText)
874
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
875
+ errors.push('manifest.json is not a JSON object')
876
+ }
877
+ } catch {
878
+ errors.push('manifest.json is not valid JSON')
879
+ }
880
+ }
881
+
882
+ return { ok: errors.length === 0, errors }
883
+ }
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
+ }
1895
+ // ---------------------------------------------------------------------------
1896
+ // optional CLI helper: rows for the office DOCX builder (no docx is created here)
1897
+ // ---------------------------------------------------------------------------
1898
+
1899
+ function entryFromResult(result) {
1900
+ const record = result?.commitment ?? result?.fact ?? result?.preference
1901
+ if (!record) return undefined
1902
+ const kind = result.commitment ? 'commitment' : result.fact ? 'fact' : 'preference'
1903
+ return {
1904
+ kind,
1905
+ id: record.id,
1906
+ found: true,
1907
+ sources: Array.isArray(result.sources) ? result.sources : [],
1908
+ missing: Array.isArray(result.missing) ? result.missing : [],
1909
+ }
1910
+ }
1911
+
1912
+ function extractEntries(input) {
1913
+ if (!input) return []
1914
+ if (typeof input === 'string') {
1915
+ try {
1916
+ return extractEntries(JSON.parse(input))
1917
+ } catch {
1918
+ return []
1919
+ }
1920
+ }
1921
+ if (Array.isArray(input)) {
1922
+ const out = []
1923
+ for (const item of input) {
1924
+ if (!item || typeof item !== 'object') continue
1925
+ if (item.commitment || item.fact || item.preference) {
1926
+ const entry = entryFromResult(item)
1927
+ if (entry) out.push(entry)
1928
+ continue
1929
+ }
1930
+ out.push(item)
1931
+ }
1932
+ return out
1933
+ }
1934
+ if (input.summary && Array.isArray(input.summary.entries)) return input.summary.entries
1935
+ if (Array.isArray(input.entries)) return input.entries
1936
+ if (input.files && input.files['manifest.json'] !== undefined) {
1937
+ try {
1938
+ return extractEntries(JSON.parse(textOf(input.files['manifest.json']) ?? ''))
1939
+ } catch {
1940
+ return []
1941
+ }
1942
+ }
1943
+ if (input.commitment || input.fact || input.preference) {
1944
+ const entry = entryFromResult(input)
1945
+ return entry ? [entry] : []
1946
+ }
1947
+ return []
1948
+ }
1949
+
1950
+ /**
1951
+ * Flatten a pack (or evidence results, or `manifest.json` entries) into rows for
1952
+ * `office`'s DOCX table builder. Columns follow DOCX_EVIDENCE_HEADERS:
1953
+ * `[kind, id, session#turn, quote (<= 500 chars), 'ok' | 'missing: <reason>']`.
1954
+ * This helper never writes a DOCX — the CLI owns that.
1955
+ *
1956
+ * @returns {string[][]}
1957
+ */
1958
+ export function toDocxRows(input, { maxRows = 200 } = {}) {
1959
+ const entries = extractEntries(input)
1960
+ const rows = []
1961
+ for (const entry of entries) {
1962
+ const kind = String(entry.kind ?? 'unknown')
1963
+ const id = String(entry.id ?? '')
1964
+ const sources = Array.isArray(entry.sources) ? entry.sources : []
1965
+ const missing = Array.isArray(entry.missing) ? entry.missing : []
1966
+ if (!sources.length && !missing.length) {
1967
+ rows.push([kind, id, '', '', entry.found === false ? '记录不存在' : '无证据'])
1968
+ continue
1969
+ }
1970
+ for (const source of sources) {
1971
+ rows.push([
1972
+ kind,
1973
+ id,
1974
+ formatRef(source.sessionId, source.turnId),
1975
+ clampQuote(source.quote).quote,
1976
+ entry.found === false ? '记录不存在' : 'ok',
1977
+ ])
1978
+ }
1979
+ for (const item of missing) {
1980
+ rows.push([
1981
+ kind,
1982
+ id,
1983
+ item.ref || formatRef(item.sessionId, item.turnId) || String(item.id ?? ''),
1984
+ clampQuote(item.quote).quote,
1985
+ `missing: ${item.reason ?? 'unknown'}`,
1986
+ ])
1987
+ }
1988
+ }
1989
+ if (rows.length > maxRows) {
1990
+ const hidden = rows.length - maxRows
1991
+ const kept = rows.slice(0, Math.max(0, maxRows - 1))
1992
+ return [...kept, ['…', '', '', '', `${hidden} 行未显示`]]
1993
+ }
1994
+ return rows
1995
+ }