advisers 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/advisers.js CHANGED
@@ -1,14 +1,26 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawnSync } from 'node:child_process'
3
- import { chmodSync, closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'
3
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
4
4
  import { homedir, hostname } from 'node:os'
5
5
  import { createHash, randomBytes, randomUUID } from 'node:crypto'
6
- import { basename, dirname, extname, isAbsolute, join } from 'node:path'
6
+ import { delimiter as PATH_DELIMITER, basename, dirname, extname, isAbsolute, join } from 'node:path'
7
7
  let SqliteStore
8
8
  let acquireInstanceLock
9
9
  let instanceLockPath
10
+ let inspectWalStatus
11
+ let readInstanceLock
12
+ let instanceLockIsStale
13
+ let openReadStoreLib
10
14
  try {
11
- ({ SqliteStore, acquireInstanceLock, instanceLockPath } = await import('../lib/sqlite.js'))
15
+ ({
16
+ SqliteStore,
17
+ acquireInstanceLock,
18
+ instanceLockPath,
19
+ inspectWalStatus,
20
+ readInstanceLock,
21
+ instanceLockIsStale,
22
+ openReadStore: openReadStoreLib,
23
+ } = await import('../lib/sqlite.js'))
12
24
  } catch (error) {
13
25
  if (String(error?.message || error).includes('node:sqlite')) {
14
26
  console.error(`Advisers needs Node >= 22.16 (node:sqlite). You have ${process.version}. Install Node 24 or use nvm-windows.`)
@@ -17,6 +29,19 @@ try {
17
29
  throw error
18
30
  }
19
31
  import { egressDeniedReason } from '../lib/egress.js'
32
+ // 0.2.3 Wave 1: every durable bin/ output goes through the crash-safe helpers
33
+ // (short-write loop, fsync, atomic rename, bounded Windows retry) instead of a
34
+ // one-shot writeFileSync that ENOSPC can truncate.
35
+ import {
36
+ atomicWriteFileSync,
37
+ commitTempFileSync,
38
+ copyFileWithRetrySync,
39
+ describeFsError,
40
+ fsyncDirSync,
41
+ fsyncFileSync,
42
+ rmWithRetrySync,
43
+ writeAllToTempSync,
44
+ } from '../lib/fs-safe.js'
20
45
 
21
46
  /**
22
47
  * P1-1: lazy-load the heavy / rarely used libraries.
@@ -54,6 +79,7 @@ const loadSafety = lazyModule(() => import('../lib/safety/index.js'))
54
79
  // IMAP client and review helpers (~63-75ms of compiled JS). They are only
55
80
  // needed by a subset of commands, so each one is a memoized dynamic import.
56
81
  const loadAgent = lazyModule(() => import('../lib/agent.js'))
82
+ const loadUntrusted = lazyModule(() => import('../lib/untrusted.js'))
57
83
  const loadModel = lazyModule(() => import('../lib/model.js'))
58
84
  const loadLearning = lazyModule(() => import('../lib/learning.js'))
59
85
  const loadRoutine = lazyModule(() => import('../lib/routine.js'))
@@ -185,28 +211,47 @@ function readAuditKey() {
185
211
  }
186
212
  function ensureAuditKey() {
187
213
  if (process.env.ADVISERS_AUDIT_KEY) return
188
- try {
189
- if (existsSync(AUDIT_KEY_FILE)) {
190
- process.env.ADVISERS_AUDIT_KEY = readAuditKey()
191
- return
192
- }
193
- const key = randomBytes(32).toString('hex')
214
+ // P0-4: O_EXCL so two first-run processes agree on exactly one key. The loser
215
+ // must read the winner's key, not overwrite it (that would leave rows signed
216
+ // with a key that no longer exists on disk). A loser can observe the winner's
217
+ // file between open() and write(), so a short/empty read is retried briefly
218
+ // instead of failing the whole command (0.2.3 read path makes first opens
219
+ // faster and the window is easier to hit under concurrent first runs).
220
+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4))
221
+ const pause = (ms) => { try { Atomics.wait(waitBuffer, 0, 0, ms) } catch {} }
222
+ let lastError = null
223
+ for (let attempt = 0; attempt < 25; attempt++) {
194
224
  try {
195
- // P0-4: O_EXCL so two first-run processes agree on exactly one key. The
196
- // loser must read the winner's key, not overwrite it (that would leave
197
- // rows signed with a key that no longer exists on disk).
198
- writeFileSync(AUDIT_KEY_FILE, key, { mode: 0o600, flag: 'wx' })
225
+ if (existsSync(AUDIT_KEY_FILE)) {
226
+ const key = readFileSync(AUDIT_KEY_FILE, 'utf8').trim()
227
+ if (key.length >= 16) { process.env.ADVISERS_AUDIT_KEY = key; return }
228
+ lastError = new Error(`audit key file is too short (${key.length} chars, expected >= 16): ${AUDIT_KEY_FILE}`)
229
+ pause(5)
230
+ continue
231
+ }
232
+ const key = randomBytes(32).toString('hex')
233
+ try { writeFileSync(AUDIT_KEY_FILE, key, { mode: 0o600, flag: 'wx' }) } catch (error) {
234
+ if (error?.code !== 'EEXIST') throw error
235
+ pause(5)
236
+ continue
237
+ }
199
238
  process.env.ADVISERS_AUDIT_KEY = key
239
+ return
200
240
  } catch (error) {
201
- if (error?.code !== 'EEXIST') throw error
202
- process.env.ADVISERS_AUDIT_KEY = readAuditKey()
241
+ lastError = error
242
+ pause(5)
203
243
  }
244
+ }
245
+ try {
246
+ process.env.ADVISERS_AUDIT_KEY = readAuditKey()
204
247
  } catch (error) {
205
- console.error(`advisers: audit key unavailable (${error.message})`)
206
- console.error(` expected a readable ${AUDIT_KEY_FILE} with at least 16 characters.`)
207
- console.error(' refusing to write an unkeyed audit chain. Restore the key file; if it is lost, move it aside and rerun (the existing chain will then verify as BROKEN).')
208
- process.exit(1)
248
+ lastError = error
209
249
  }
250
+ if (process.env.ADVISERS_AUDIT_KEY) return
251
+ console.error(`advisers: audit key unavailable (${lastError?.message ?? 'unknown error'})`)
252
+ console.error(` expected a readable ${AUDIT_KEY_FILE} with at least 16 characters.`)
253
+ console.error(' refusing to write an unkeyed audit chain. Restore the key file; if it is lost, move it aside and rerun (the existing chain will then verify as BROKEN).')
254
+ process.exit(1)
210
255
  }
211
256
  function ensureHome() {
212
257
  mkdirSync(HOME, { recursive: true, mode: 0o700 })
@@ -214,6 +259,88 @@ function ensureHome() {
214
259
  ensureAuditKey()
215
260
  }
216
261
 
262
+ // ---------------------------------------------------------------------------
263
+ // 0.2.3 Wave 1: agent workspace boundary (security audit SEC3-02 / P1-B)
264
+ //
265
+ // Agent file tools used to default to process.cwd(), i.e. whatever directory
266
+ // the user happened to start the CLI in (often $HOME or a client project). They
267
+ // now default to a dedicated 0700 workspace under ADVISERS_HOME. Widening the
268
+ // boundary is explicit only: --allow-path <dir> (repeatable, chat/repl) or
269
+ // ADVISERS_ALLOW_PATHS (path-list). Sensitive/persistence paths stay denied by
270
+ // lib/agent.js regardless of the allow list.
271
+ // ---------------------------------------------------------------------------
272
+ const AGENT_WORKSPACE = join(HOME, 'workspace')
273
+
274
+ /** Create (0700) and return the default agent workspace root. */
275
+ function ensureAgentWorkspace() {
276
+ mkdirSync(AGENT_WORKSPACE, { recursive: true, mode: 0o700 })
277
+ try { chmodSync(AGENT_WORKSPACE, 0o700) } catch {}
278
+ return AGENT_WORKSPACE
279
+ }
280
+
281
+ /** Merge explicit --allow-path values with ADVISERS_ALLOW_PATHS (explicit only). */
282
+ function resolveAllowPaths(cliAllowPaths = []) {
283
+ const list = Array.isArray(cliAllowPaths) ? cliAllowPaths.slice() : []
284
+ const envValue = process.env.ADVISERS_ALLOW_PATHS
285
+ if (envValue) list.push(...String(envValue).split(PATH_DELIMITER))
286
+ const seen = new Set()
287
+ const result = []
288
+ for (const entry of list) {
289
+ const value = String(entry == null ? '' : entry).trim()
290
+ if (!value || seen.has(value)) continue
291
+ seen.add(value)
292
+ result.push(value)
293
+ }
294
+ return result
295
+ }
296
+
297
+ /** Short audit-safe hash used when a value must not be stored verbatim. */
298
+ function auditHash(value) {
299
+ try { return createHash('sha256').update(String(value)).digest('hex').slice(0, 16) } catch { return 'unhashable' }
300
+ }
301
+
302
+ /**
303
+ * Reason text for the tool audit chain: control characters removed and any
304
+ * absolute path (POSIX or Windows) replaced with a short hash, so an audit row
305
+ * never stores a home/workspace path or a model-supplied absolute path.
306
+ */
307
+ function auditSafeReason(value) {
308
+ let text = String(value == null ? '' : value).replace(/[\u0000-\u001f\u007f]/g, ' ')
309
+ text = text.replace(/(?:[A-Za-z]:[\\/]|\/)[^\s;,'")]+/g, (match) => 'sha256:' + auditHash(match))
310
+ return text.replace(/\s+/g, ' ').trim().slice(0, 160)
311
+ }
312
+
313
+ /**
314
+ * onToolAction sink for runAgent: one audit row per allowed/denied tool call.
315
+ * action is tool.read / tool.write / tool.call; the row keeps the tool name,
316
+ * decision, code and a workspace-relative path (or a hash of the raw input).
317
+ * File contents and absolute paths are never written.
318
+ */
319
+ function auditToolAction(entry) {
320
+ try {
321
+ const store = dbStore()
322
+ if (!store) return
323
+ const spec = entry && typeof entry === 'object' ? entry : {}
324
+ const allowed = spec.allowed !== false
325
+ const action = spec.action === 'write' ? 'tool.write' : spec.action === 'read' ? 'tool.read' : 'tool.call'
326
+ const parts = ['tool=' + safeAuditToken(spec.tool, 'unknown'), 'allowed=' + (allowed ? 1 : 0), 'code=' + safeAuditToken(spec.code, allowed ? 'OK' : 'DENIED')]
327
+ if (typeof spec.relativePath === 'string' && spec.relativePath) parts.push('path=' + safeAuditToken(spec.relativePath, '?'))
328
+ else if (spec.input != null) parts.push('pathHash=' + auditHash(spec.input))
329
+ if (spec.turnId != null) parts.push('turn=' + safeAuditToken(spec.turnId, '-'))
330
+ if (!allowed) {
331
+ const reason = auditSafeReason(spec.reason)
332
+ if (reason) parts.push('reason=' + reason)
333
+ }
334
+ store.appendAudit({ actor: 'agent', action, allowed, reason: parts.join(';') })
335
+ } catch {}
336
+ }
337
+
338
+ /** Sanitize one audit token (no separators/control characters); bounded length. */
339
+ function safeAuditToken(value, fallback) {
340
+ const text = String(value == null ? '' : value).replace(/[\u0000-\u001f\u007f;=\s]+/g, '_').trim()
341
+ return text ? text.slice(0, 80) : fallback
342
+ }
343
+
217
344
  /**
218
345
  * P1-1: core ids are `${prefix}_${Date.now().toString(36)}_${seq}` with a
219
346
  * per-process counter, so two CLIs started in the same millisecond can mint the
@@ -266,6 +393,147 @@ function secureDbSidecars() {
266
393
  }
267
394
  }
268
395
 
396
+ // ---------------------------------------------------------------------------
397
+ // 0.2.3 persistence v2 read path (03-design-persistence-v2.md §4).
398
+ //
399
+ // Pure-read commands open state.db with DatabaseSync({ readOnly: true }) and take
400
+ // NO HOME instance lock: the lock now protects only writers and whole-file
401
+ // maintenance (migrate/vault/sync/import/backup). A reader sees the last
402
+ // committed WAL snapshot, so it keeps working while a long-lived writer (mcp,
403
+ // bridge, older ui) holds the lock. Writes still go through openStore() and its
404
+ // E_DB_LOCKED behaviour.
405
+ //
406
+ // `ADVISERS_READ_LOCKFREE=0` is the kill switch: read commands fall back to the
407
+ // exact 0.2.2 path (writable store + HOME lock). A read-only volume / read-only
408
+ // directory can make SQLite fail to create the -shm sidecar; that case also
409
+ // degrades to the writable path (which reports the historical error messages).
410
+ // ---------------------------------------------------------------------------
411
+
412
+ function readLockfreeEnabled() {
413
+ return process.env.ADVISERS_READ_LOCKFREE !== '0'
414
+ }
415
+
416
+ /** Sleep without busy-waiting; only used for the bounded schema-migration retry. */
417
+ const READ_SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4))
418
+ function sleepSync(ms) {
419
+ try { Atomics.wait(READ_SLEEP_BUFFER, 0, 0, Math.max(0, Math.floor(Number(ms) || 0))) } catch {}
420
+ }
421
+
422
+ /** True for a read-only volume / sidecar-creation failure (documented fallback). */
423
+ function isReadOnlyFallbackError(error) {
424
+ const code = String(error?.code ?? '')
425
+ if (code === 'E_SCHEMA_STALE' || code === 'E_SCHEMA_NEWER' || code === 'E_DB_CORRUPT' || code === 'E_DB_LOCKED' || code === 'E_VAULT_SEALED' || code === 'E_READ_ONLY') return false
426
+ if (code === 'EACCES' || code === 'EPERM' || code === 'EROFS') return true
427
+ const message = String(error?.message ?? '')
428
+ return /readonly database|read-only database|unable to open database file|cannot open database/i.test(message)
429
+ }
430
+
431
+ /**
432
+ * Briefly take the writer lock, open the database writable (which runs the
433
+ * backup + per-version migration) and release it again, so a reader that found
434
+ * a stale schema can retry the read-only open. A lock held by another process is
435
+ * a bounded, retried failure; a failed migration backup/corrupt DB is re-thrown
436
+ * fail-closed (the original database is untouched).
437
+ */
438
+ function migrateUnderLock() {
439
+ ensureHome()
440
+ const previousLock = instanceLock?.held ? instanceLock : null
441
+ const lock = ensureInstanceLock()
442
+ try {
443
+ const store = new SqliteStore(DB)
444
+ store.close()
445
+ } finally {
446
+ if (lock?.held && lock !== previousLock) releaseInstanceLock()
447
+ }
448
+ }
449
+
450
+ let activeReadStore = null
451
+
452
+ /**
453
+ * Open (once per process) the lock-free read-only store.
454
+ *
455
+ * - JSON store legacy mode → null (loadJson()).
456
+ * - missing database → initialize through the writable path once, then drop the
457
+ * writer lock so a long-lived reader (ui/tui) does not block writers forever.
458
+ * - stale schema → bounded retry after a short write-lock migration (§4.4).
459
+ * - newer schema / corrupt database / sealed vault → fail closed, never migrate.
460
+ */
461
+ function openReadStore() {
462
+ if (mode === 'json') return null
463
+ ensureHome()
464
+ const sealed = vaultSealedPath()
465
+ if (sealed) throw vaultSealedError(sealed)
466
+ if (activeReadStore) return activeReadStore
467
+ if (!readLockfreeEnabled()) return openStore()
468
+ if (!existsSync(DB)) {
469
+ // First run keeps the historical behaviour: a command may create the store.
470
+ // A pure reader must not keep the writer lock for its whole lifetime.
471
+ const store = openStore()
472
+ activeStore = undefined
473
+ try { store.close() } catch {}
474
+ releaseInstanceLock()
475
+ }
476
+ let lastError = null
477
+ for (let attempt = 0; attempt < 3; attempt++) {
478
+ let store
479
+ try {
480
+ store = openReadStoreLib(DB)
481
+ } catch (error) {
482
+ if (error?.code === 'E_SCHEMA_NEWER') throw error
483
+ if (error?.code !== 'E_SCHEMA_STALE') {
484
+ if (isReadOnlyFallbackError(error)) return openStore()
485
+ throw error
486
+ }
487
+ lastError = error
488
+ try {
489
+ migrateUnderLock()
490
+ } catch (migrationError) {
491
+ // A failed migration is not a transient read-path problem: retrying it
492
+ // would only create more backups (and can hide the real failure). Only
493
+ // lock contention is retried; everything else is re-thrown fail-closed.
494
+ const retryableLock = migrationError?.code === 'E_DB_LOCKED' || migrationError?.code === 'E_MIGRATE_BUSY'
495
+ if (!retryableLock) throw migrationError
496
+ lastError = migrationError
497
+ }
498
+ sleepSync(50 * (attempt + 1))
499
+ continue
500
+ }
501
+ activeReadStore = store
502
+ return store
503
+ }
504
+ const error = new Error(
505
+ `E_SCHEMA_STALE: could not bring ${DB} to the current schema for a read-only open after 3 attempts` +
506
+ (lastError?.message ? ` (${lastError.message})` : '') +
507
+ '; if another advisers process is upgrading it, retry in a moment; otherwise run a writable command (for example `advisers doctor`) and retry.',
508
+ )
509
+ error.code = 'E_SCHEMA_STALE'
510
+ throw error
511
+ }
512
+
513
+ /** The lock-free read store (null for the legacy JSON store). */
514
+ function readStore() {
515
+ return mode === 'json' ? null : openReadStore()
516
+ }
517
+
518
+ /** Print the documented store error for a read command and exit 1. */
519
+ function exitReadStoreFailure(error) {
520
+ if (error?.code === 'E_SCHEMA_STALE' || error?.code === 'E_SCHEMA_NEWER') { console.error(error.message); process.exit(1) }
521
+ if (error?.code === 'E_VAULT_SEALED') { console.error(error.message); process.exit(1) }
522
+ const hint = storeFailureHint(error)
523
+ if (hint) { console.error(hint); process.exit(1) }
524
+ console.error(`sqlite unavailable: ${error.message}`)
525
+ console.error('Run `advisers doctor`; refusing to silently switch to JSON (would split the ledger).')
526
+ process.exit(1)
527
+ }
528
+
529
+ /** Read store for commands that query the store directly (null in JSON mode). */
530
+ function readStoreOrExit() {
531
+ ensureHome()
532
+ if (mode !== 'sqlite') return null
533
+ try { return openReadStore() } catch (error) { exitReadStoreFailure(error) }
534
+ }
535
+
536
+
269
537
  function openStore({ checkIntegrity = false } = {}) {
270
538
  if (!activeStore) {
271
539
  const sealed = vaultSealedPath()
@@ -365,6 +633,59 @@ function loadLedger(parts = null) {
365
633
  }
366
634
  }
367
635
 
636
+ /**
637
+ * Load the ledger for a PURE-READ command through the lock-free read-only store
638
+ * (0.2.3 persistence v2 §4.6). Same partial-loading contract as loadLedger(),
639
+ * but it never takes the HOME writer lock and never runs DDL/migration.
640
+ * Write commands must keep using loadLedger()/dbStore().
641
+ */
642
+ function loadReadLedger(parts = null) {
643
+ ensureHome()
644
+ if (mode === 'json') return loadJson()
645
+ try {
646
+ const store = openReadStore()
647
+ if (!parts) return Ledger.fromJSON(store.read(() => store.load()), LOCAL_PORTS)
648
+ const snapshot = store.read(() => {
649
+ const partial = { version: 1 }
650
+ for (const [table, options] of Object.entries(parts)) {
651
+ const loader = LEDGER_PART_LOADERS[table]
652
+ if (!loader) throw new Error(`unknown ledger table for partial load: ${table}`)
653
+ partial[table] = loader(store, options ?? {})
654
+ }
655
+ return partial
656
+ })
657
+ return Ledger.fromParts(snapshot, LOCAL_PORTS)
658
+ } catch (error) {
659
+ exitReadStoreFailure(error)
660
+ }
661
+ }
662
+
663
+ /**
664
+ * Read a partial ledger for a pure-read command. Thin alias of loadReadLedger()
665
+ * so the dispatch reads as "this command only reads", while write commands keep
666
+ * calling loadLedger()/dbStore() (writer lock + WAL).
667
+ */
668
+ function readLedgerForCommand(parts = null) {
669
+ return loadReadLedger(parts)
670
+ }
671
+
672
+ /**
673
+ * Minimal open-commitment rows for the HUMAN `today` view (0.2.3 hot path).
674
+ *
675
+ * `today` classifies every open commitment but only displays id/debtor/creditor/
676
+ * action/dueAt. Loading them through loadCommitments() maps the full entity
677
+ * (JSON.parse of evidence/reminder_offsets, defaults, sortable objects) which at
678
+ * 200k rows is ~365ms in-process vs ~139ms for the six columns actually needed.
679
+ * The JSON/sources forms keep the full entities (their contract needs them).
680
+ * The query runs on the lock-free read connection and is read-only.
681
+ */
682
+ function loadOpenCommitmentRowsForToday() {
683
+ const store = readStoreOrExit()
684
+ if (!store) return []
685
+ const rows = store.db.prepare("SELECT id, debtor, creditor, action, due_at FROM commitments WHERE status = 'open' ORDER BY rowid").all()
686
+ return rows.map((row) => ({ id: row.id, debtor: row.debtor, creditor: row.creditor, action: row.action, dueAt: row.due_at ?? undefined }))
687
+ }
688
+
368
689
  function exitStoreWriteFailure(error) {
369
690
  // P0-2: never fall back to state.json. The SQLite database is the only ledger
370
691
  // once it exists, so a JSON fallback would silently split the book (and the
@@ -400,28 +721,88 @@ function saveLedgerWithAudit(ledger, audit, inside) {
400
721
  }
401
722
  }
402
723
 
403
- function updateStoreWithAudit(fn, audit) {
724
+ /**
725
+ * 0.2.3 persistence v2 write helper: one BEGIN IMMEDIATE containing the directed
726
+ * business writes and exactly one audit row (03-design-persistence-v2.md §3.2).
727
+ * In JSON-store mode the caller keeps the legacy load/save path and this returns
728
+ * { legacyJson: true } so the command can fall back without a second code path.
729
+ */
730
+ function mutateWithAudit(fn, audit) {
404
731
  ensureHome()
405
732
  const store = dbStore()
406
- if (!store) return
733
+ if (!store) return { legacyJson: true }
407
734
  try {
408
- return store.transaction(() => {
409
- fn(store)
410
- return store.appendAudit(audit)
411
- })
735
+ return store.mutate(fn, audit)
412
736
  } catch (error) {
413
- exitStoreWriteFailure(error)
737
+ // Only store-level failures get the "nothing was written" explanation; a
738
+ // business error (unknown matter/commitment, validation) is rethrown so the
739
+ // command can print its own stable message/code (E_MATTER_NOT_FOUND, ...).
740
+ if (isStoreWriteFailure(error)) exitStoreWriteFailure(error)
741
+ throw error
414
742
  }
415
743
  }
416
744
 
417
- function recordDeliveryWithAudit({ files, tool, title, validation, audit }) {
745
+ /** Alias kept for the existing call sites (memory reject, ...): same channel. */
746
+ function updateStoreWithAudit(fn, audit) {
747
+ return mutateWithAudit(fn, audit)
748
+ }
749
+
750
+ /**
751
+ * Record a delivery row + its audit row in one transaction.
752
+ *
753
+ * P0-3 (performance audit): the old path called loadLedger() just to resolve the
754
+ * active matter id, i.e. a hidden FULL load on every deliver/template/pack
755
+ * command (two full loads per deliver at 200k rows). Resolve it from the latest
756
+ * session or the first active matter instead: both are single indexed lookups.
757
+ */
758
+ function activeMatterIdForWrite(store) {
759
+ const routed = activeMatterIdFromStore(store)
760
+ if (routed) return routed
761
+ const sessionMatter = sessionMatterIdIfActive(store)
762
+ if (sessionMatter) return sessionMatter
763
+ try { return store?.firstActiveMatter?.()?.id ?? 'matter' } catch { return 'matter' }
764
+ }
765
+
766
+ /**
767
+ * Delivery matter id resolved INSIDE the write transaction: latest session's
768
+ * matter > first active matter > a newly inserted default matter (defaults
769
+ * identical to Ledger.addMatter({title:'默认事项'})). This keeps the historical
770
+ * "a delivery always points at a real matter" behaviour without the old hidden
771
+ * full loadLedger() (P0-3); the default matter and the delivery row commit
772
+ * together with the audit row.
773
+ */
774
+ function resolveDeliveryMatterId(store) {
775
+ const routed = activeMatterIdFromStore(store)
776
+ if (routed) return routed
777
+ const sessionMatter = sessionMatterIdIfActive(store)
778
+ if (sessionMatter) return sessionMatter
779
+ const active = store.firstActiveMatter?.()
780
+ if (active) return active.id
781
+ const timestamp = now()
782
+ const matter = {
783
+ id: LOCAL_PORTS.ids.next('matter'),
784
+ title: '默认事项',
785
+ status: 'active',
786
+ domain: 'general',
787
+ secrecy: 0,
788
+ participants: [],
789
+ deadlines: [],
790
+ openQuestions: [],
791
+ createdAt: timestamp,
792
+ updatedAt: timestamp,
793
+ }
794
+ store.insertMatter(matter)
795
+ return matter.id
796
+ }
797
+
798
+ function recordDeliveryWithAudit({ files, tool, title, validation, audit, matterId }) {
418
799
  const store = dbStore()
419
800
  if (!store) return
420
- let matterId = 'matter'
421
- try { matterId = activeMatterId(loadLedger()) } catch {}
801
+ const conversationId = latestConversationId()
422
802
  updateStoreWithAudit((s) => s.addDelivery({
423
- matterId,
424
- conversationId: latestConversationId(),
803
+ // An explicit --matter is validated inside the transaction (no dangling id).
804
+ matterId: matterId ? assertMatterForWrite(s, matterId) : resolveDeliveryMatterId(s),
805
+ conversationId,
425
806
  files,
426
807
  tool,
427
808
  title,
@@ -448,42 +829,6 @@ function saveSoul(doc) {
448
829
  writeFileSync(SOUL_META, JSON.stringify({ version: doc.version, updatedAt: doc.updatedAt }, null, 2) + '\n', { mode: 0o600 })
449
830
  }
450
831
 
451
- /** Write bytes to an already-created same-directory temp file and fsync it. */
452
- function writeDurableTemp(target, bytes, { mode = 0o600 } = {}) {
453
- const fd = openSync(target, 'wx', mode)
454
- try {
455
- writeSync(fd, bytes)
456
- fsyncSync(fd)
457
- } finally {
458
- closeSync(fd)
459
- }
460
- return target
461
- }
462
-
463
- /** fsync a directory entry so a rename survives a crash. */
464
- function fsyncDir(path) {
465
- try {
466
- const fd = openSync(path, 'r')
467
- try { fsyncSync(fd) } finally { closeSync(fd) }
468
- } catch {}
469
- }
470
-
471
- /** Atomic write: same-directory temp + fsync + rename + directory fsync. */
472
- function atomicWriteFileSync(path, bytes, { mode = 0o600 } = {}) {
473
- mkdirSync(dirname(path), { recursive: true })
474
- const tmp = join(dirname(path), `.${basename(path)}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`)
475
- try {
476
- writeDurableTemp(tmp, bytes, { mode })
477
- renameSync(tmp, path)
478
- } catch (error) {
479
- try { if (existsSync(tmp)) rmSync(tmp) } catch {}
480
- throw error
481
- }
482
- try { chmodSync(path, mode) } catch {}
483
- fsyncDir(dirname(path))
484
- return path
485
- }
486
-
487
832
  const soulStore = { load: loadSoul, save: saveSoul }
488
833
 
489
834
  function runtimeFor(ledger) {
@@ -499,6 +844,35 @@ function now() {
499
844
  return new Date().toISOString()
500
845
  }
501
846
 
847
+ /**
848
+ * 0.2.3 B3: honest manual evidence for operator-entered quotes.
849
+ *
850
+ * Before this the CLI wrote `{sessionId:'local', turnId:'cli'}`, a fake
851
+ * conversation pointer that every reader resolved as MISSING (turn_not_found)
852
+ * and every receipt counted as a missing source. A manual source is
853
+ * unverifiable by construction, not missing: evidence.js maps this shape to
854
+ * resolution=unverifiable/operator_entered and receipts count operatorEntered
855
+ * separately from missingCount. No DB migration: evidence is a JSON column.
856
+ */
857
+ function sha256HexText(text) {
858
+ return createHash('sha256').update(String(text), 'utf8').digest('hex')
859
+ }
860
+
861
+ function manualEvidence(quote, command) {
862
+ const text = String(quote ?? '')
863
+ return {
864
+ kind: 'manual',
865
+ type: 'manual',
866
+ source: 'operator',
867
+ quote: text,
868
+ quoteSha256: sha256HexText(text),
869
+ capturedAt: now(),
870
+ capturedBy: 'local',
871
+ command,
872
+ cliVersion: VERSION,
873
+ }
874
+ }
875
+
502
876
  function dbStore() {
503
877
  return mode === 'sqlite' ? openStore() : undefined
504
878
  }
@@ -513,7 +887,7 @@ function latestConversationId() {
513
887
  }
514
888
 
515
889
  function printHistory() {
516
- const store = dbStore()
890
+ const store = readStoreOrExit()
517
891
  const rows = store?.listSessions(12) ?? []
518
892
  if (!rows.length) {
519
893
  console.log('no saved sessions yet')
@@ -525,12 +899,17 @@ function printHistory() {
525
899
  }
526
900
 
527
901
  function printReceipt() {
528
- const store = dbStore()
902
+ const store = readStoreOrExit()
529
903
  if (!store) { console.log('receipt requires SQLite store'); return }
530
- const delivery = store.listDeliveries(1)[0]
904
+ // 0.2.3: one read snapshot for the delivery row, model usage and research row.
905
+ const { delivery, usage, research } = store.read(() => ({
906
+ delivery: store.listDeliveries(1)[0],
907
+ usage: store.sumModelUsage(),
908
+ research: store.listResearch?.(1)?.[0],
909
+ }))
531
910
  if (!delivery) { console.log('还没有交付记录;先运行 `advisers office` / `advisers template`。'); return }
532
911
  // P1-2 (0.2.2): only this delivery's matter and its open commitments are read.
533
- const ledger = loadLedger({ commitments: { status: 'open', matterId: delivery.matterId } })
912
+ const ledger = loadReadLedger({ commitments: { status: 'open', matterId: delivery.matterId } })
534
913
  const open = ledger.openCommitments(delivery.matterId)
535
914
  console.log(`回执 ${delivery.id}`)
536
915
  console.log(`时间:${delivery.createdAt}`)
@@ -540,9 +919,7 @@ function printReceipt() {
540
919
  console.log(`校验:${delivery.validation || '未记录'}`)
541
920
  console.log(`未完成承诺:${open.length}`)
542
921
  for (const c of open.slice(0, 3)) console.log(` ${c.id} ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
543
- const usage = store.sumModelUsage()
544
922
  if (usage.calls) console.log(`模型:${usage.calls} calls · ${usage.total_tokens} tokens`)
545
- const research = store.listResearch?.(1)?.[0]
546
923
  if (research) {
547
924
  console.log(`研究:${research.query}`)
548
925
  for (const source of research.sources.slice(0, 3)) console.log(` web: ${source.title || '(untitled)'} ${source.url}`)
@@ -551,7 +928,7 @@ function printReceipt() {
551
928
  }
552
929
 
553
930
  function printDeliveries() {
554
- const store = dbStore()
931
+ const store = readStoreOrExit()
555
932
  const rows = store?.listDeliveries(12) ?? []
556
933
  if (!rows.length) {
557
934
  console.log('no deliveries yet')
@@ -559,7 +936,7 @@ function printDeliveries() {
559
936
  }
560
937
  // P1-2 (0.2.2): only matter titles are needed for the fallback label.
561
938
  let matters = []
562
- try { matters = loadLedger({ matters: {} }).listMatters() } catch {}
939
+ try { matters = loadReadLedger({ matters: {} }).listMatters() } catch {}
563
940
  const title = new Map(matters.map((m) => [m.id, m.title]))
564
941
  for (const row of rows) {
565
942
  console.log(`${row.createdAt.slice(0, 19)} ${row.title ?? title.get(row.matterId) ?? row.matterId} [${row.tool ?? 'tool'}] ${row.validation ?? ''}`)
@@ -633,10 +1010,12 @@ function help() {
633
1010
 
634
1011
  Usage:
635
1012
  advisers start the local conversation (TTY)
636
- advisers chat [--file <path>] [text]
1013
+ advisers chat [--file <path>] [--allow-path <dir>]... [text]
637
1014
  one-shot task, or start the local conversation
638
1015
  advisers init initialize home + soul
639
- advisers doctor check Node/SQLite/Office/policy/model
1016
+ advisers doctor [--check-db]
1017
+ check Node/SQLite/Office/policy/model; --check-db adds
1018
+ quick_check + FTS integrity + WAL + backup + plaintext/temp checks
640
1019
  advisers status home/store/model/counts
641
1020
  advisers history recent conversations
642
1021
  advisers search <text> full-text search old turns
@@ -653,7 +1032,11 @@ Usage:
653
1032
  read-only redacted Pet Brief (contract v0.2); --print-schema prints the JSON Schema
654
1033
  advisers tick due commitments in the next 7 days
655
1034
  advisers week last 7 days
656
- advisers digest day|week short digest
1035
+ advisers agenda [--days 7] [--json]
1036
+ 7-day agenda: commitments + calendar_events, Asia/Shanghai days
1037
+ advisers morning [--json] [--out f]
1038
+ deterministic local morning brief (no model, no network)
1039
+ advisers digest day|week|morning short digest (morning = the deterministic brief)
657
1040
  advisers diff show the last changed file
658
1041
  advisers undo [--list] restore the last file write
659
1042
  advisers learn ls recent task trajectories
@@ -673,7 +1056,11 @@ Usage:
673
1056
  per-commitment reminder offsets (Asia/Shanghai wall clock)
674
1057
  advisers deliveries recent generated files
675
1058
  advisers receipt one-screen delivery receipt
676
- advisers ls list matters
1059
+ advisers ls list matters (alias of matter ls)
1060
+ advisers matter add <title> [--secrecy 0-3] [--domain d] [--summary s] [--json]
1061
+ advisers matter ls [--all] [--json]
1062
+ advisers matter show|rename|archive|use <id> ...
1063
+ create/inspect/rename/archive a matter; 'use' sets the write default
677
1064
  advisers privacy [--json] [--prove] show/verify local data & egress facts
678
1065
  advisers why <pref-id> explain a preference
679
1066
  advisers forget <pref-id> forget a preference (tombstone)
@@ -725,6 +1112,9 @@ Usage:
725
1112
  advisers routine check <id> run file/manual verification
726
1113
  advisers routine curate [--apply] mark stale/deprecated routines
727
1114
  advisers routine restore <id> restore an archived routine to draft
1115
+ advisers template quote <data.json> <out.docx|out.xlsx> [--json] [--record-delivery] [--matter id]
1116
+ advisers template proposal <data.json> <out.docx> [--json] [--record-delivery]
1117
+ deterministic quote / proposal (DOCX; quote also XLSX); amount strings
728
1118
  advisers template <weekly|budget|presentation|flow|mindmap|minutes|notice> <data.json> <out>
729
1119
  build a template into docx/xlsx/pptx/mmd/drawio/xmind
730
1120
  advisers link ls list matter links
@@ -752,18 +1142,30 @@ Environment:
752
1142
  enable the model call in chat
753
1143
  ADVISERS_YES=1 skip the plan confirmation
754
1144
  ADVISERS_FORCE=1 overwrite existing files without asking
1145
+ ADVISERS_ALLOW_PATHS explicit path-list (OS path separator) widening the
1146
+ agent file-tool boundary, same as repeated --allow-path
755
1147
  ADVISERS_PROGRESS=0 hide [tool] progress lines
756
1148
  ADVISERS_ACCEPT_TOS=1 record TOS consent without a TTY (same as --accept-tos)
757
1149
  ADVISERS_NOTIFY_WEBHOOK optional outbound webhook for remind --deliver --notify
758
1150
  ADVISERS_LOCK_TIMEOUT_MS wait for another advisers process to release the
759
1151
  instance lock (milliseconds; default 10000, 0 = fail immediately)
760
1152
 
1153
+ Agent workspace:
1154
+ chat/repl file tools (file_read/file_write/office_*) are confined to
1155
+ ADVISERS_HOME/workspace (created 0700). They do not default to the current
1156
+ directory. Pass --allow-path <dir> (repeatable) or set ADVISERS_ALLOW_PATHS to
1157
+ widen the boundary explicitly; credential stores, persistence targets and
1158
+ other sensitive paths stay denied even then.
1159
+
761
1160
  Concurrency:
762
- One advisers process per ADVISERS_HOME uses the SQLite ledger at a time. The
763
- CLI takes ~/.advisers/instance.lock before opening state.db; a second process
764
- waits up to ADVISERS_LOCK_TIMEOUT_MS and then exits with E_DB_LOCKED instead
765
- of writing from a stale ledger snapshot. ui / mcp / bridge keep the lock while
766
- they run, so stop them before running other commands (or raise the timeout).
1161
+ One advisers WRITER per ADVISERS_HOME uses the SQLite ledger at a time. The
1162
+ CLI takes ~/.advisers/instance.lock before opening state.db for a write; a
1163
+ second writer waits up to ADVISERS_LOCK_TIMEOUT_MS and then exits with
1164
+ E_DB_LOCKED instead of writing from a stale ledger snapshot. mcp / bridge keep
1165
+ the lock while they run (they write audit rows), so stop them before running
1166
+ other writes (or raise the timeout). Read-only commands (status/today/who/...,
1167
+ ui, tui, pet-brief) do NOT take the lock: they read a consistent WAL snapshot,
1168
+ so they keep working and never block a writer.
767
1169
  A stale lock (dead pid, or not refreshed for 1h) is reclaimed; SIGINT/SIGTERM
768
1170
  and normal exit release the lock. Concurrent commands therefore either run one
769
1171
  after another or fail explicitly — they never silently overwrite each other.
@@ -811,31 +1213,112 @@ function learnPreference(ledger, statement, quote, { explicit = false } = {}) {
811
1213
  return { preference: pref, promoted: false }
812
1214
  }
813
1215
 
1216
+ /**
1217
+ * `advisers purge <matter> [--yes]` — privacy delete one matter.
1218
+ *
1219
+ * 0.2.3 §3.3.12: the dry-run is a pure read (lock-free, partial tables). With
1220
+ * --yes the ledger tombstones, the non-ledger row deletion and the audit row all
1221
+ * commit in ONE transaction; the business rules are the same as
1222
+ * core Ledger.purgeMatter (test/incremental-write.test.js pins the SQL half).
1223
+ * The historical raw UPDATEs for links/updates/routes are the documented P1
1224
+ * exception: SqliteStore has no targeted primitives for those tables yet.
1225
+ * VACUUM cannot run inside a transaction, so it runs after COMMIT.
1226
+ */
814
1227
  function purgeMatter(id, confirmed) {
815
1228
  if (!id) { console.error('usage: advisers purge <matter-id> [--yes]'); process.exitCode = 1; return }
816
- const ledger = loadLedger()
817
- const matter = ledger.getMatter(id)
818
- if (!matter) { console.error(`unknown matter: ${id}`); process.exitCode = 1; return }
819
- const facts = ledger.listFacts(id).length
820
- const links = ledger.listLinks(id).length
821
- const updates = ledger.listUpdates().filter((u) => u.sourceMatter === id || u.targetMatter === id).length
822
- const commitments = ledger.openCommitments(id).length
823
- console.log(`matter ${id}: ${matter.title}`)
824
- console.log(`facts=${facts} links=${links} updates=${updates} open_commitments=${commitments}`)
1229
+ if (mode === 'json') {
1230
+ const ledger = loadJson()
1231
+ const matter = ledger.getMatter(id)
1232
+ if (!matter) { console.error(`unknown matter: ${id}`); process.exitCode = 1; return }
1233
+ const facts = ledger.listFacts(id).length
1234
+ const links = ledger.listLinks(id).length
1235
+ const updates = ledger.listUpdates().filter((u) => u.sourceMatter === id || u.targetMatter === id).length
1236
+ const commitments = ledger.openCommitments(id).length
1237
+ console.log(`matter ${id}: ${matter.title}`)
1238
+ console.log(`facts=${facts} links=${links} updates=${updates} open_commitments=${commitments}`)
1239
+ if (!confirmed) { console.log('dry-run only; re-run with --yes to purge'); return }
1240
+ const counts = ledger.purgeMatter(id)
1241
+ saveJson(ledger)
1242
+ console.log(`purged: ${JSON.stringify(counts)} sqlite={}`)
1243
+ return
1244
+ }
825
1245
  if (!confirmed) {
826
- console.log('dry-run only; re-run with --yes to purge')
1246
+ try {
1247
+ const store = readStoreOrExit()
1248
+ const { matter, facts, links, updates, commitments } = store.read(() => {
1249
+ const target = store.getMatter(id)
1250
+ if (!target) return { matter: undefined }
1251
+ return {
1252
+ matter: target,
1253
+ facts: store.loadFacts({ matterId: id }).filter((f) => f.status !== 'deleted').length,
1254
+ links: store.loadLinks({}).filter((l) => (l.fromMatter === id || l.toMatter === id) && l.status !== 'rejected').length,
1255
+ updates: store.loadUpdates().filter((u) => (u.sourceMatter === id || u.targetMatter === id) && u.status === 'pending').length,
1256
+ commitments: store.loadCommitments({ matterId: id, status: 'open' }).length,
1257
+ }
1258
+ })
1259
+ if (!matter) { console.error(`unknown matter: ${id}`); process.exitCode = 1; return }
1260
+ console.log(`matter ${id}: ${matter.title}`)
1261
+ console.log(`facts=${facts} links=${links} updates=${updates} open_commitments=${commitments}`)
1262
+ console.log('dry-run only; re-run with --yes to purge')
1263
+ } catch (error) { reportCommandFailure(error) }
827
1264
  return
828
1265
  }
829
- const counts = ledger.purgeMatter(id)
830
- const sqlite = dbStore()?.purgeMatterData(id)
831
- saveLedgerWithAudit(ledger, { actor: 'local', action: 'matter.purge', allowed: true, reason: `${id} ${JSON.stringify(counts)}` })
832
- console.log(`purged: ${JSON.stringify(counts)} sqlite=${JSON.stringify(sqlite ?? {})}`)
1266
+ const audit = { actor: 'local', action: 'matter.purge', allowed: true, reason: '' }
1267
+ try {
1268
+ const { result } = mutateWithAudit((store) => {
1269
+ const timestamp = now()
1270
+ const counts = { facts: 0, links: 0, updates: 0, commitments: 0, preferences: 0, routes: 0 }
1271
+ for (const fact of store.loadFacts({ matterId: id })) {
1272
+ if (fact.status === 'deleted') continue
1273
+ store.updateFact(fact.id, { status: 'deleted', object: '[purged]', source: null, evidence: null, deletedAt: timestamp, deletedReason: 'matter_purged' })
1274
+ counts.facts++
1275
+ }
1276
+ for (const link of store.loadLinks({})) {
1277
+ if ((link.fromMatter === id || link.toMatter === id) && link.status !== 'rejected') {
1278
+ store.db.prepare('UPDATE links SET status = ?, evidence = ? WHERE id = ?').run('rejected', '[]', link.id)
1279
+ counts.links++
1280
+ }
1281
+ }
1282
+ for (const update of store.loadUpdates()) {
1283
+ if ((update.sourceMatter === id || update.targetMatter === id) && update.status === 'pending') {
1284
+ store.db.prepare('UPDATE updates SET status = ?, change = ?, rollback = NULL WHERE id = ?').run('rejected', '[purged]', update.id)
1285
+ counts.updates++
1286
+ }
1287
+ }
1288
+ for (const commitment of store.loadCommitments({ matterId: id })) {
1289
+ if (commitment.status !== 'open') continue
1290
+ store.updateCommitment(commitment.id, { status: 'dropped', action: '[purged]', creditor: '[purged]', evidence: [] })
1291
+ counts.commitments++
1292
+ }
1293
+ for (const preference of store.loadPreferences()) {
1294
+ if (preference.scope?.level === 'matter' && preference.scope?.value === id && preference.status !== 'deprecated') {
1295
+ store.updatePreference(preference.id, { status: 'deprecated', statement: '[purged]', evidence: [] })
1296
+ counts.preferences++
1297
+ }
1298
+ }
1299
+ for (const [key, matterId] of Object.entries(store.loadRoutes())) {
1300
+ if (matterId !== id) continue
1301
+ store.db.prepare('DELETE FROM routes WHERE key = ?').run(key)
1302
+ counts.routes++
1303
+ }
1304
+ store.updateMatter(id, { status: 'archived', title: '[purged]', summary: null, updatedAt: timestamp })
1305
+ const sqlite = store.purgeMatterData(id, { vacuum: false })
1306
+ audit.reason = `${id} ${JSON.stringify(counts)}`
1307
+ return { counts, sqlite }
1308
+ }, audit)
1309
+ try {
1310
+ const store = dbStore()
1311
+ store.checkpoint({ mode: 'TRUNCATE' })
1312
+ store.db.exec('VACUUM')
1313
+ } catch {}
1314
+ console.log(`purged: ${JSON.stringify(result.counts)} sqlite=${JSON.stringify(result.sqlite ?? {})}`)
1315
+ } catch (error) { reportCommandFailure(error) }
833
1316
  }
834
1317
 
835
1318
  function parseFlags(args) {
836
1319
  const flags = {}
837
1320
  const positional = []
838
- const booleanFlags = new Set(['web', 'deep', 'all', 'yes', 'json', 'list', 'force', 'apply', 'quiet', 'help', 'content', 'ics', 'deliver', 'install', 'uninstall', 'status', 'calendar', 'sources', 'pack', 'receipt', 'from-imap', 'remove', 'force', 'notify', 'no-remind'])
1321
+ const booleanFlags = new Set(['web', 'deep', 'all', 'yes', 'json', 'list', 'force', 'apply', 'quiet', 'help', 'content', 'ics', 'deliver', 'install', 'uninstall', 'status', 'calendar', 'sources', 'pack', 'receipt', 'from-imap', 'remove', 'force', 'notify', 'no-remind', 'dry-run', 'unclassified', 'no-calendar', 'include-done', 'record-delivery'])
839
1322
  for (let i = 0; i < args.length; i++) {
840
1323
  if (args[i].startsWith('--')) {
841
1324
  const key = args[i].slice(2)
@@ -864,9 +1347,8 @@ function recordManualDelivery(files, tool, title, validation) {
864
1347
  try {
865
1348
  const store = dbStore()
866
1349
  if (!store) return
867
- const ledger = loadLedger()
868
1350
  store.addDelivery({
869
- matterId: activeMatterId(ledger),
1351
+ matterId: activeMatterIdForWrite(store),
870
1352
  conversationId: latestConversationId(),
871
1353
  files,
872
1354
  tool,
@@ -876,15 +1358,158 @@ function recordManualDelivery(files, tool, title, validation) {
876
1358
  } catch {}
877
1359
  }
878
1360
 
1361
+ /** `advisers matter use <id>` marker: meta row in SQLite, route in the JSON store. */
1362
+ function activeMatterIdFromStore(store) {
1363
+ try {
1364
+ const id = store?.getMeta?.('active_matter_id')
1365
+ if (!id) return undefined
1366
+ const matter = store.getMatter(id)
1367
+ return matter && matter.status === 'active' ? id : undefined
1368
+ } catch { return undefined }
1369
+ }
1370
+
1371
+ function activeMatterIdFromLedgerRoute(ledger) {
1372
+ try {
1373
+ const id = ledger?.getRoute?.('active-matter')
1374
+ if (!id) return undefined
1375
+ const matter = ledger.getMatter(id)
1376
+ return matter && matter.status === 'active' ? id : undefined
1377
+ } catch { return undefined }
1378
+ }
1379
+
1380
+ /**
1381
+ * Latest session's matter, but only when it still exists and is active.
1382
+ * Without this check a legacy/archived session reference could silently write
1383
+ * a dangling or archived matter_id (the exact class of bug --matter had).
1384
+ */
1385
+ function sessionMatterIdIfActive(store) {
1386
+ try {
1387
+ const latest = store?.listSessions?.(1)?.[0]
1388
+ if (!latest?.matterId) return undefined
1389
+ const matter = store.getMatter?.(latest.matterId)
1390
+ return matter && matter.status === 'active' ? matter.id : undefined
1391
+ } catch { return undefined }
1392
+ }
1393
+
879
1394
  function activeMatterId(ledger, explicit) {
880
1395
  if (explicit) return explicit
1396
+ // `matter use` wins over the latest session, so a CLI-only user can pick the
1397
+ // default matter for subsequent `commit add` without opening a chat session.
1398
+ const routed = (mode === 'json' ? undefined : activeMatterIdFromStore(dbStore())) ?? activeMatterIdFromLedgerRoute(ledger)
1399
+ if (routed) return routed
881
1400
  try {
882
- const latest = dbStore()?.listSessions(1)[0]
883
- if (latest) return latest.matterId
1401
+ const sessionMatter = sessionMatterIdIfActive(dbStore())
1402
+ if (sessionMatter) return sessionMatter
884
1403
  } catch {}
885
1404
  return ledger.listMatters()[0]?.id ?? ledger.addMatter({ title: '默认事项' }).id
886
1405
  }
887
1406
 
1407
+ // ---------------------------------------------------------------------------
1408
+ // 0.2.3 incremental-write command helpers (03-design-persistence-v2.md §3.3).
1409
+ //
1410
+ // Every directed write resolves its matter/session/ids BEFORE entering the
1411
+ // transaction and only calls targeted store.get*/insert*/update*/setMeta inside
1412
+ // it: no loadLedger()/saveLedger() may run inside mutateWithAudit (a full load
1413
+ // inside the transaction would both block writers and re-introduce the
1414
+ // 107MB-WAL write amplification this path exists to remove).
1415
+ // ---------------------------------------------------------------------------
1416
+
1417
+ /**
1418
+ * Matter id for a directed write: explicit --matter (trusted, matching the
1419
+ * historical semantics), else the latest session's matter, else the first active
1420
+ * matter, else a newly inserted default matter (defaults identical to
1421
+ * Ledger.addMatter({title:'默认事项'})).
1422
+ */
1423
+ /** Business error with a stable code (message keeps the code for plain stderr). */
1424
+ function matterCommandError(code, message, hint) {
1425
+ const error = new Error(code + ': ' + message + (hint ? ' (hint: ' + hint + ')' : ''))
1426
+ error.code = code
1427
+ if (hint) error.hint = hint
1428
+ return error
1429
+ }
1430
+
1431
+ /** Validate an explicit matter id for a write: exists and active, else throw. */
1432
+ function assertMatterForWrite(store, explicit) {
1433
+ const id = String(explicit)
1434
+ const matter = store.getMatter?.(id)
1435
+ if (!matter) throw matterCommandError('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter add "…"')
1436
+ if (matter.status !== 'active') throw matterCommandError('E_MATTER_ARCHIVED', 'matter is archived: ' + id, 'advisers matter ls')
1437
+ return matter.id
1438
+ }
1439
+
1440
+ /** Resolve an explicit --matter on a ledger loaded in memory (JSON store / readers). */
1441
+ function resolveMatterForCommand(ledger, explicit, command = 'write') {
1442
+ if (explicit === undefined || explicit === null) return activeMatterId(ledger)
1443
+ if (explicit === true) throw matterCommandError('E_USAGE', '--matter requires a matter id', 'advisers matter ls')
1444
+ const id = String(explicit)
1445
+ const matter = ledger?.getMatter?.(id)
1446
+ if (!matter) throw matterCommandError('E_MATTER_NOT_FOUND', 'unknown matter: ' + id + ' (' + command + ')', 'advisers matter add "…"')
1447
+ if (matter.status !== 'active') throw matterCommandError('E_MATTER_ARCHIVED', 'matter is archived: ' + id + ' (' + command + ')', 'advisers matter ls')
1448
+ return matter.id
1449
+ }
1450
+
1451
+ function resolveWriteMatterId(store, explicit) {
1452
+ if (explicit) return assertMatterForWrite(store, explicit)
1453
+ const routed = activeMatterIdFromStore(store)
1454
+ if (routed) return routed
1455
+ const sessionMatter = sessionMatterIdIfActive(store)
1456
+ if (sessionMatter) return sessionMatter
1457
+ const active = store.firstActiveMatter?.()
1458
+ if (active) return active.id
1459
+ const timestamp = now()
1460
+ const matter = {
1461
+ id: LOCAL_PORTS.ids.next('matter'),
1462
+ title: '默认事项',
1463
+ status: 'active',
1464
+ domain: 'general',
1465
+ secrecy: 0,
1466
+ participants: [],
1467
+ deadlines: [],
1468
+ openQuestions: [],
1469
+ createdAt: timestamp,
1470
+ updatedAt: timestamp,
1471
+ }
1472
+ store.insertMatter(matter)
1473
+ return matter.id
1474
+ }
1475
+
1476
+ /** Session id stamped on CLI-made evidence; falls back to 'local' like before. */
1477
+ function latestConversationIdFor(store) {
1478
+ try { return store.listSessions(1)?.[0]?.conversationId ?? 'local' } catch { return 'local' }
1479
+ }
1480
+
1481
+ /**
1482
+ * Report a command failure either as a store write failure (E_DB_LOCKED etc.,
1483
+ * with the documented hint) or as a plain business error (usage/unknown id) with
1484
+ * exit code 1. Keeps the 0.2.2 stderr text for business errors unchanged.
1485
+ */
1486
+ function isStoreWriteFailure(error) {
1487
+ const code = error?.code
1488
+ return code === 'E_DB_LOCKED' || code === 'E_DB_CORRUPT' || code === 'E_MIGRATE_BUSY' ||
1489
+ code === 'E_MIGRATION_BACKUP' || code === 'E_READ_ONLY' || code === 'E_TX_REQUIRED' ||
1490
+ code === 'E_SCHEMA_STALE' || code === 'E_SCHEMA_NEWER' || code === 'E_VAULT_SEALED' ||
1491
+ error?.errcode !== undefined || /SQLITE_|database is locked|disk I\/O error|database or disk is full/i.test(String(error?.message ?? ''))
1492
+ }
1493
+
1494
+ function reportCommandFailure(error) {
1495
+ if (isStoreWriteFailure(error)) { exitStoreWriteFailure(error); return }
1496
+ console.error(error?.message ?? String(error))
1497
+ process.exitCode = 1
1498
+ }
1499
+
1500
+ /** Shared output lines of `commit add` (kept byte-identical to 0.2.2). */
1501
+ function printCommitAdded(c, reminderOffsets) {
1502
+ console.log(`${c.id} open ${c.action}${c.dueAt ? ` due ${c.dueAt}` : ''}`)
1503
+ if (reminderOffsets !== undefined) console.log('reminder-offsets: ' + JSON.stringify(reminderOffsets))
1504
+ }
1505
+
1506
+ /** Shared output lines of `commit edit` (kept byte-identical to 0.2.2). */
1507
+ function printCommitUpdated(c, patch) {
1508
+ console.log(`updated: ${c.id}`)
1509
+ if ('reminderOffsets' in patch) console.log('reminder-offsets: ' + JSON.stringify(c.reminderOffsets ?? []))
1510
+ if (patch.dueAt !== undefined) console.log('due: ' + (c.dueAt ?? '未定'))
1511
+ }
1512
+
888
1513
  function printCommitments(ledger, asJson = false) {
889
1514
  const rows = ledger.listCommitments()
890
1515
  if (asJson) { console.log(JSON.stringify(rows, null, 2)); return }
@@ -915,7 +1540,7 @@ function printWeek(ledger) {
915
1540
  const open = commitments.filter((c) => c.status === 'open')
916
1541
  const overdue = open.filter((c) => c.dueAt && Date.parse(c.dueAt) < now)
917
1542
  let deliveries = []
918
- try { deliveries = dbStore()?.listDeliveries(100) ?? [] } catch {}
1543
+ try { deliveries = readStoreOrExit()?.listDeliveries(100) ?? [] } catch {}
919
1544
  const weekDeliveries = deliveries.filter((d) => Date.parse(d.createdAt) >= weekAgo)
920
1545
  console.log(`本周(${new Date(weekAgo).toISOString().slice(0, 10)} – ${new Date(now).toISOString().slice(0, 10)})`)
921
1546
  console.log(`承诺:到期 ${due.length} 件,完成 ${done.length} 件,未完成 ${open.length} 件,逾期 ${overdue.length} 件。`)
@@ -925,6 +1550,756 @@ function printWeek(ledger) {
925
1550
  console.log('下周一件:' + (next?.action ?? open[0]?.action ?? '先定一个承诺或交付。'))
926
1551
  }
927
1552
 
1553
+ // ---------------------------------------------------------------------------
1554
+ // 0.2.3 P1a: matter (客户/项目) minimal closed loop.
1555
+ //
1556
+ // Before this the CLI had exactly two creation paths (the automatic default
1557
+ // matter and link ingest), and --matter was trusted blindly, so users could
1558
+ // write matter_id='client-wang' while matters was empty. pet-brief then
1559
+ // dropped that commitment silently. These commands create/list/show/rename/
1560
+ // archive a matter and 'matter use' records the default for later writes.
1561
+ // No schema change: the matters table already exists (schema v20).
1562
+ // ---------------------------------------------------------------------------
1563
+ function matterFail(code, message, hint) {
1564
+ console.error(JSON.stringify({ error: { code: code, message: message, ...(hint ? { hint: hint } : {}) } }))
1565
+ process.exitCode = 1
1566
+ }
1567
+
1568
+ function matterNextDueAt(open) {
1569
+ const next = open
1570
+ .map((commitment) => dueInstantOfValue(commitment.dueAt))
1571
+ .filter((ms) => ms !== null)
1572
+ .sort((a, b) => a - b)[0]
1573
+ return next === undefined ? null : toShanghaiIso(next)
1574
+ }
1575
+
1576
+ function matterJsonRow(matter, openByMatter) {
1577
+ const open = openByMatter.get(matter.id) ?? []
1578
+ return {
1579
+ id: matter.id,
1580
+ title: matter.title,
1581
+ status: matter.status,
1582
+ domain: matter.domain ?? 'general',
1583
+ secrecy: Number(matter.secrecy ?? 0),
1584
+ clientId: null,
1585
+ projectId: null,
1586
+ openCommitments: open.length,
1587
+ nextDueAt: matterNextDueAt(open),
1588
+ }
1589
+ }
1590
+
1591
+ async function matterCommand(args) {
1592
+ const sub = args[0]
1593
+ const parsed = parseFlags(args.slice(1))
1594
+ const flags = parsed.flags
1595
+ const positional = parsed.positional
1596
+ const asJson = flags.json === true
1597
+ const fail = (code, message, hint) => { matterFail(code, message, hint) }
1598
+ if (sub === 'add') {
1599
+ const title = positional.join(' ').trim()
1600
+ if (!title) { fail('E_USAGE', 'matter add requires a title', 'advisers matter add "王工 · 官网改版"'); return }
1601
+ let secrecy = 0
1602
+ if (flags.secrecy !== undefined) {
1603
+ if (flags.secrecy === true || !/^[0-3]$/.test(String(flags.secrecy))) { fail('E_USAGE', '--secrecy must be an integer 0..3'); return }
1604
+ secrecy = Number(flags.secrecy)
1605
+ }
1606
+ const domain = typeof flags.domain === 'string' ? flags.domain : 'general'
1607
+ const summary = typeof flags.summary === 'string' ? flags.summary : undefined
1608
+ if (mode === 'json') {
1609
+ const ledger = loadJson()
1610
+ const matter = ledger.addMatter({ title: title, domain: domain, secrecy: secrecy, summary: summary })
1611
+ saveJson(ledger)
1612
+ if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter add', matter: matter }, null, 2)); return }
1613
+ console.log('created ' + matter.id + ' ' + matter.title)
1614
+ return
1615
+ }
1616
+ try {
1617
+ const audit = { actor: 'local', action: 'matter.add', allowed: true, reason: '' }
1618
+ const made = mutateWithAudit((store) => {
1619
+ const timestamp = now()
1620
+ const row = {
1621
+ id: LOCAL_PORTS.ids.next('matter'), title: title, status: 'active', domain: domain, secrecy: secrecy,
1622
+ ...(summary === undefined ? {} : { summary: summary }),
1623
+ participants: [], deadlines: [], openQuestions: [], createdAt: timestamp, updatedAt: timestamp,
1624
+ }
1625
+ store.insertMatter(row)
1626
+ audit.reason = row.id
1627
+ return row
1628
+ }, audit)
1629
+ const matter = made.result
1630
+ if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter add', matter: matter }, null, 2)); return }
1631
+ console.log('created ' + matter.id + ' ' + matter.title)
1632
+ } catch (error) { reportCommandFailure(error) }
1633
+ return
1634
+ }
1635
+ if (sub === 'ls') {
1636
+ try {
1637
+ const ledger = mode === 'json' ? loadJson() : readLedgerForCommand({ matters: {}, commitments: { status: 'open' } })
1638
+ const statuses = flags.all === true ? ['active', 'paused', 'archived'] : ['active']
1639
+ const matters = statuses.flatMap((status) => ledger.listMatters(status))
1640
+ const openByMatter = new Map()
1641
+ for (const commitment of ledger.listCommitments()) {
1642
+ if (commitment.status !== 'open') continue
1643
+ const list = openByMatter.get(commitment.matterId) ?? []
1644
+ list.push(commitment)
1645
+ openByMatter.set(commitment.matterId, list)
1646
+ }
1647
+ const rows = matters.map((matter) => matterJsonRow(matter, openByMatter))
1648
+ rows.sort((a, b) => (a.status === b.status ? (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) : (a.status < b.status ? -1 : 1)))
1649
+ if (asJson) { console.log(JSON.stringify(rows, null, 2)); return }
1650
+ if (!rows.length) { console.log('(没有事项)'); return }
1651
+ for (const row of rows) console.log(row.id + '\t' + row.status + '\tsecrecy=' + row.secrecy + '\topen=' + row.openCommitments + '\t' + (row.nextDueAt ?? '无截止') + '\t' + row.title)
1652
+ } catch (error) { reportCommandFailure(error) }
1653
+ return
1654
+ }
1655
+ if (sub === 'show') {
1656
+ const id = positional[0]
1657
+ if (!id) { fail('E_USAGE', 'matter show requires a matter id', 'advisers matter ls'); return }
1658
+ try {
1659
+ const ledger = mode === 'json' ? loadJson() : readLedgerForCommand({ matters: {}, commitments: { matterId: id } })
1660
+ const matter = ledger.getMatter(id)
1661
+ if (!matter) { fail('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls'); return }
1662
+ const commitments = ledger.listCommitments().filter((commitment) => commitment.matterId === id)
1663
+ const open = commitments.filter((commitment) => commitment.status === 'open')
1664
+ const payload = {
1665
+ ok: true,
1666
+ command: 'matter show',
1667
+ matter: matter,
1668
+ counts: { commitments: commitments.length, open: open.length, done: commitments.filter((c) => c.status === 'done').length },
1669
+ open: open.map((c) => ({ id: c.id, action: c.action, dueAt: c.dueAt ?? null, debtor: c.debtor, creditor: c.creditor })),
1670
+ nextDueAt: matterNextDueAt(open),
1671
+ }
1672
+ if (asJson) { console.log(JSON.stringify(payload, null, 2)); return }
1673
+ console.log(matter.id + ' ' + matter.title)
1674
+ console.log('状态 ' + matter.status + ' · 保密 ' + Number(matter.secrecy ?? 0) + ' · 领域 ' + (matter.domain ?? 'general'))
1675
+ if (matter.summary) console.log('摘要:' + matter.summary)
1676
+ console.log('未完成承诺 ' + open.length + ' · 总承诺 ' + commitments.length + ' · 下一截止 ' + (payload.nextDueAt ?? '无'))
1677
+ for (const c of open.slice(0, 20)) console.log(' ' + c.id + ' ' + c.action + (c.dueAt ? ' · ' + c.dueAt : ''))
1678
+ } catch (error) { reportCommandFailure(error) }
1679
+ return
1680
+ }
1681
+ if (sub === 'rename') {
1682
+ const id = positional[0]
1683
+ const title = positional.slice(1).join(' ').trim()
1684
+ if (!id || !title) { fail('E_USAGE', 'matter rename requires <id> <title>', 'advisers matter rename matter_x "新标题"'); return }
1685
+ if (mode === 'json') {
1686
+ const ledger = loadJson()
1687
+ const matter = ledger.getMatter(id)
1688
+ if (!matter) { fail('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls'); return }
1689
+ matter.title = title
1690
+ matter.updatedAt = now()
1691
+ saveJson(ledger)
1692
+ if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter rename', matter: matter }, null, 2)); return }
1693
+ console.log('renamed ' + id + ' ' + title)
1694
+ return
1695
+ }
1696
+ try {
1697
+ const audit = { actor: 'local', action: 'matter.rename', allowed: true, reason: id }
1698
+ const made = mutateWithAudit((store) => {
1699
+ const current = store.getMatter(id)
1700
+ if (!current) throw matterCommandError('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls')
1701
+ store.updateMatter(id, { title: title, updatedAt: now() })
1702
+ return store.getMatter(id)
1703
+ }, audit)
1704
+ if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter rename', matter: made.result }, null, 2)); return }
1705
+ console.log('renamed ' + id + ' ' + made.result.title)
1706
+ } catch (error) { reportCommandFailure(error) }
1707
+ return
1708
+ }
1709
+ if (sub === 'archive') {
1710
+ const id = positional[0]
1711
+ if (!id) { fail('E_USAGE', 'matter archive requires a matter id', 'advisers matter ls'); return }
1712
+ const dryRun = flags['dry-run'] === true
1713
+ try {
1714
+ if (mode === 'json') {
1715
+ const ledger = loadJson()
1716
+ const matter = ledger.getMatter(id)
1717
+ if (!matter) { fail('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls'); return }
1718
+ if (dryRun) {
1719
+ if (asJson) console.log(JSON.stringify({ ok: true, command: 'matter archive', dryRun: true, matter: matter }, null, 2))
1720
+ else console.log('would archive ' + id + ' ' + matter.title + '(dry-run,未写入)')
1721
+ return
1722
+ }
1723
+ matter.status = 'archived'
1724
+ matter.updatedAt = now()
1725
+ saveJson(ledger)
1726
+ if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter archive', matter: matter }, null, 2)); return }
1727
+ console.log('archived ' + id + ' ' + matter.title)
1728
+ return
1729
+ }
1730
+ if (dryRun) {
1731
+ const ledger = readLedgerForCommand({ matters: {} })
1732
+ const matter = ledger.getMatter(id)
1733
+ if (!matter) { fail('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls'); return }
1734
+ if (asJson) console.log(JSON.stringify({ ok: true, command: 'matter archive', dryRun: true, matter: matter }, null, 2))
1735
+ else console.log('would archive ' + id + ' ' + matter.title + '(dry-run,未写入)')
1736
+ return
1737
+ }
1738
+ const audit = { actor: 'local', action: 'matter.archive', allowed: true, reason: id }
1739
+ const made = mutateWithAudit((store) => {
1740
+ const current = store.getMatter(id)
1741
+ if (!current) throw matterCommandError('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls')
1742
+ store.updateMatter(id, { status: 'archived', updatedAt: now() })
1743
+ return store.getMatter(id)
1744
+ }, audit)
1745
+ if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter archive', matter: made.result }, null, 2)); return }
1746
+ console.log('archived ' + id + ' ' + made.result.title)
1747
+ } catch (error) { reportCommandFailure(error) }
1748
+ return
1749
+ }
1750
+ if (sub === 'use') {
1751
+ const id = positional[0]
1752
+ if (!id) { fail('E_USAGE', 'matter use requires a matter id', 'advisers matter ls'); return }
1753
+ try {
1754
+ if (mode === 'json') {
1755
+ const ledger = loadJson()
1756
+ const matter = ledger.getMatter(id)
1757
+ if (!matter) { fail('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls'); return }
1758
+ if (matter.status !== 'active') { fail('E_MATTER_ARCHIVED', 'matter is archived: ' + id, 'advisers matter ls'); return }
1759
+ ledger.setRoute('active-matter', id)
1760
+ saveJson(ledger)
1761
+ if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter use', matterId: id }, null, 2)); return }
1762
+ console.log('active matter: ' + id + ' ' + matter.title)
1763
+ return
1764
+ }
1765
+ const audit = { actor: 'local', action: 'matter.use', allowed: true, reason: id }
1766
+ const made = mutateWithAudit((store) => {
1767
+ const current = store.getMatter(id)
1768
+ if (!current) throw matterCommandError('E_MATTER_NOT_FOUND', 'unknown matter: ' + id, 'advisers matter ls')
1769
+ if (current.status !== 'active') throw matterCommandError('E_MATTER_ARCHIVED', 'matter is archived: ' + id, 'advisers matter ls')
1770
+ store.setMeta('active_matter_id', id)
1771
+ return current
1772
+ }, audit)
1773
+ if (asJson) { console.log(JSON.stringify({ ok: true, command: 'matter use', matterId: id }, null, 2)); return }
1774
+ console.log('active matter: ' + id + ' ' + made.result.title)
1775
+ } catch (error) { reportCommandFailure(error) }
1776
+ return
1777
+ }
1778
+ if (!sub || sub === 'help' || sub === '--help') {
1779
+ console.log('usage: advisers matter <add|ls|show|rename|archive|use> ...')
1780
+ console.log(' advisers matter add <title> [--secrecy 0-3] [--domain name] [--summary text] [--json]')
1781
+ console.log(' advisers matter ls [--all] [--json]')
1782
+ console.log(' advisers matter show <id> [--json]')
1783
+ console.log(' advisers matter rename <id> <title> [--json]')
1784
+ console.log(' advisers matter archive <id> [--dry-run] [--json]')
1785
+ console.log(' advisers matter use <id> [--json] set the default matter for later writes')
1786
+ return
1787
+ }
1788
+ fail('E_USAGE', 'unknown matter subcommand: ' + sub, 'advisers matter help')
1789
+ }
1790
+
1791
+ // ---------------------------------------------------------------------------
1792
+ // 0.2.3 P3: 7-day agenda + deterministic morning brief.
1793
+ //
1794
+ // Time semantics (design §1.4/§5.4): the display/storage split is fixed to
1795
+ // Asia/Shanghai. Storage keeps UTC instants; every window boundary, grouping
1796
+ // decision and label below is computed on the Shanghai calendar day, never on
1797
+ // new Date().toISOString().slice(0,10) (the 0.2.2 'week' bug). A date-only
1798
+ // dueAt means "done before 23:59:59.999 local time". RRULE expansion reuses
1799
+ // lib/ical.js expandRrule; unsupported rules/timezones are degraded, skipped
1800
+ // and reported, never guessed. No model call, no network call, no writes.
1801
+ // ---------------------------------------------------------------------------
1802
+ const AGENDA_TIMEZONE = 'Asia/Shanghai'
1803
+ const AGENDA_DAY_MS = 86400_000
1804
+ const AGENDA_OFFSET_MS = 8 * 3600_000
1805
+ const AGENDA_WEEKDAYS = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
1806
+ const AGENDA_DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/
1807
+ const AGENDA_LOCAL_TIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/
1808
+
1809
+ function agendaDayNumber(day) {
1810
+ const text = String(day ?? '')
1811
+ if (!AGENDA_DATE_ONLY.test(text)) return null
1812
+ const parts = text.split('-').map(Number)
1813
+ if (parts.some((part) => !Number.isFinite(part))) return null
1814
+ return Math.round(Date.UTC(parts[0], parts[1] - 1, parts[2]) / AGENDA_DAY_MS)
1815
+ }
1816
+
1817
+ function agendaDayFromNumber(number) {
1818
+ return new Date(number * AGENDA_DAY_MS).toISOString().slice(0, 10)
1819
+ }
1820
+
1821
+ function agendaAddDays(day, delta) {
1822
+ const number = agendaDayNumber(day)
1823
+ return number === null ? null : agendaDayFromNumber(number + delta)
1824
+ }
1825
+
1826
+ function agendaWeekday(day) {
1827
+ const number = agendaDayNumber(day)
1828
+ return number === null ? '' : AGENDA_WEEKDAYS[new Date(number * AGENDA_DAY_MS).getUTCDay()]
1829
+ }
1830
+
1831
+ function agendaDayStartInstant(day) {
1832
+ return agendaDayNumber(day) * AGENDA_DAY_MS - AGENDA_OFFSET_MS
1833
+ }
1834
+
1835
+ function agendaDayEndInstant(day) {
1836
+ return agendaDayNumber(day) * AGENDA_DAY_MS - AGENDA_OFFSET_MS + AGENDA_DAY_MS - 1
1837
+ }
1838
+
1839
+ function agendaLocalDayOfInstant(ms) {
1840
+ return agendaDayFromNumber(Math.floor((ms + AGENDA_OFFSET_MS) / AGENDA_DAY_MS))
1841
+ }
1842
+
1843
+ function agendaLocalTimeOfInstant(ms) {
1844
+ const wall = new Date(ms + AGENDA_OFFSET_MS)
1845
+ return String(wall.getUTCHours()).padStart(2, '0') + ':' + String(wall.getUTCMinutes()).padStart(2, '0')
1846
+ }
1847
+
1848
+ /** UTC instant -> Shanghai wall-clock ISO string with an explicit +08:00 offset. */
1849
+ function toShanghaiIso(ms) {
1850
+ return new Date(ms + AGENDA_OFFSET_MS).toISOString().replace('Z', '+08:00')
1851
+ }
1852
+
1853
+ /**
1854
+ * Resolve a stored dueAt to an absolute instant.
1855
+ * - YYYY-MM-DD -> end of that Shanghai day
1856
+ * - local ISO without zone -> Shanghai wall clock (+08:00)
1857
+ * - anything with Z/offset -> its absolute instant
1858
+ * Returns null for invalid/dirty data (callers degrade instead of guessing).
1859
+ */
1860
+ function dueInstantOfValue(dueAt) {
1861
+ if (dueAt === undefined || dueAt === null) return null
1862
+ const text = String(dueAt).trim()
1863
+ if (!text) return null
1864
+ if (AGENDA_DATE_ONLY.test(text)) return agendaDayEndInstant(text)
1865
+ if (AGENDA_LOCAL_TIME.test(text)) {
1866
+ const ms = Date.parse(text.replace(' ', 'T') + '+08:00')
1867
+ return Number.isFinite(ms) ? ms : null
1868
+ }
1869
+ const ms = Date.parse(text)
1870
+ return Number.isFinite(ms) ? ms : null
1871
+ }
1872
+
1873
+ function agendaClip(value, max) {
1874
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
1875
+ const chars = Array.from(text)
1876
+ return chars.length <= max ? text : chars.slice(0, max).join('')
1877
+ }
1878
+
1879
+ function agendaIsDateOnlyDue(dueAt) {
1880
+ const text = String(dueAt ?? '')
1881
+ return AGENDA_DATE_ONLY.test(text) || !/[T ]\d{2}:\d{2}/.test(text)
1882
+ }
1883
+
1884
+ function agendaCommitmentItem(commitment, dueMs) {
1885
+ const allDay = agendaIsDateOnlyDue(commitment.dueAt)
1886
+ return {
1887
+ id: commitment.id,
1888
+ kind: 'commitment',
1889
+ title: agendaClip(commitment.action, 120),
1890
+ allDay: allDay,
1891
+ at: new Date(dueMs).toISOString(),
1892
+ localDate: agendaLocalDayOfInstant(dueMs),
1893
+ localTime: allDay ? null : agendaLocalTimeOfInstant(dueMs),
1894
+ matterId: commitment.matterId ?? null,
1895
+ ref: { kind: 'commitment', id: commitment.id },
1896
+ meta: { creditor: commitment.creditor },
1897
+ }
1898
+ }
1899
+
1900
+ function agendaCompareItems(a, b) {
1901
+ if (Boolean(a.allDay) !== Boolean(b.allDay)) return a.allDay ? 1 : -1
1902
+ const left = Date.parse(a.at)
1903
+ const right = Date.parse(b.at)
1904
+ if (Number.isFinite(left) && Number.isFinite(right) && left !== right) return left - right
1905
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
1906
+ }
1907
+
1908
+ function agendaCalendarMeta(instance) {
1909
+ const meta = {}
1910
+ if (instance.rrule) meta.rrule = String(instance.rrule)
1911
+ if (instance.location) meta.location = String(instance.location)
1912
+ return meta
1913
+ }
1914
+
1915
+ /**
1916
+ * Build the deterministic agenda view shared by 'agenda' and 'digest morning'.
1917
+ * Pure projection: no writes, no model/network calls, no clock reads besides
1918
+ * the injected nowMs. All arrays are deterministically sorted.
1919
+ */
1920
+ async function buildAgendaData(input) {
1921
+ const { expandRrule } = await loadIcal()
1922
+ const nowMs = input.nowMs
1923
+ const days = input.days
1924
+ const includeCalendar = input.includeCalendar !== false
1925
+ const includeDone = input.includeDone === true
1926
+ const matterId = input.matterId
1927
+ const startDay = input.fromDay ?? agendaLocalDayOfInstant(nowMs)
1928
+ const lastDay = agendaAddDays(startDay, days - 1)
1929
+ const degraded = []
1930
+ const overdue = []
1931
+ const waiting = []
1932
+ const unscheduled = []
1933
+ const dayItems = new Map()
1934
+ const pushDay = (day, item) => {
1935
+ const list = dayItems.get(day) ?? []
1936
+ list.push(item)
1937
+ dayItems.set(day, list)
1938
+ }
1939
+ for (const commitment of input.ledger.listCommitments()) {
1940
+ if (matterId && commitment.matterId !== matterId) continue
1941
+ const status = commitment.status
1942
+ if (status === 'done') {
1943
+ if (!includeDone) continue
1944
+ } else if (status !== 'open' && status !== 'snoozed') continue
1945
+ const isWaiting = typeof commitment.debtor === 'string' && (commitment.debtor === 'third' || commitment.debtor.startsWith('third:'))
1946
+ const dueMs = commitment.dueAt ? dueInstantOfValue(commitment.dueAt) : null
1947
+ if (commitment.dueAt && dueMs === null) {
1948
+ unscheduled.push({ id: commitment.id, kind: 'commitment', title: agendaClip(commitment.action, 120), allDay: true, at: null, localDate: null, ref: { kind: 'commitment', id: commitment.id }, meta: { debtor: commitment.debtor } })
1949
+ degraded.push({ source: 'commitments', code: 'E_TIME_INVALID', id: commitment.id, reason: 'invalid dueAt' })
1950
+ continue
1951
+ }
1952
+ if (isWaiting && status !== 'done') {
1953
+ waiting.push({ id: commitment.id, kind: 'commitment', title: agendaClip(commitment.action, 120), allDay: true, at: dueMs === null ? null : new Date(dueMs).toISOString(), localDate: null, debtor: commitment.debtor, ref: { kind: 'commitment', id: commitment.id } })
1954
+ continue
1955
+ }
1956
+ if (dueMs === null) {
1957
+ unscheduled.push({ id: commitment.id, kind: 'commitment', title: agendaClip(commitment.action, 120), allDay: true, at: null, localDate: null, ref: { kind: 'commitment', id: commitment.id } })
1958
+ continue
1959
+ }
1960
+ if (status !== 'done' && dueMs < nowMs) {
1961
+ overdue.push(agendaCommitmentItem(commitment, dueMs))
1962
+ continue
1963
+ }
1964
+ if (status === 'done') {
1965
+ const doneDay = agendaLocalDayOfInstant(dueMs)
1966
+ if (doneDay >= startDay && doneDay <= lastDay) pushDay(doneDay, Object.assign(agendaCommitmentItem(commitment, dueMs), { kind: 'done' }))
1967
+ continue
1968
+ }
1969
+ const dueDay = agendaLocalDayOfInstant(dueMs)
1970
+ if (dueDay >= startDay && dueDay <= lastDay) pushDay(dueDay, agendaCommitmentItem(commitment, dueMs))
1971
+ }
1972
+ if (includeCalendar) {
1973
+ for (const row of input.events ?? []) {
1974
+ const tzid = row.tzid === undefined || row.tzid === null ? '' : String(row.tzid)
1975
+ if (tzid && !['Asia/Shanghai', 'UTC', 'Etc/UTC', 'GMT', 'Z'].includes(tzid)) {
1976
+ degraded.push({ source: 'calendar', code: 'E_CALENDAR_SKIP', id: row.uid ?? null, reason: 'unsupported tzid: ' + tzid })
1977
+ continue
1978
+ }
1979
+ let instances
1980
+ try {
1981
+ instances = expandRrule(row, { from: startDay, to: lastDay })
1982
+ } catch (error) {
1983
+ degraded.push({ source: 'calendar', code: 'E_CALENDAR_SKIP', id: row.uid ?? null, reason: String(error && error.message ? error.message : error) })
1984
+ continue
1985
+ }
1986
+ for (const instance of instances) {
1987
+ if (instance.allDay) {
1988
+ const day = String(instance.startsAt ?? '').slice(0, 10)
1989
+ if (agendaDayNumber(day) === null || day < startDay || day > lastDay) continue
1990
+ pushDay(day, {
1991
+ id: instance.uid ?? day, kind: 'calendar', title: agendaClip(instance.summary, 120), allDay: true,
1992
+ at: new Date(agendaDayStartInstant(day)).toISOString(), localDate: day, localTime: null,
1993
+ matterId: null, ref: { kind: 'calendar', id: instance.uid ?? day }, meta: agendaCalendarMeta(instance),
1994
+ })
1995
+ continue
1996
+ }
1997
+ const startMs = Date.parse(instance.startsAt)
1998
+ if (!Number.isFinite(startMs)) {
1999
+ degraded.push({ source: 'calendar', code: 'E_CALENDAR_SKIP', id: instance.uid ?? null, reason: 'invalid startsAt' })
2000
+ continue
2001
+ }
2002
+ const day = agendaLocalDayOfInstant(startMs)
2003
+ if (day < startDay || day > lastDay) continue
2004
+ const endMs = instance.endsAt ? Date.parse(instance.endsAt) : null
2005
+ const item = {
2006
+ id: instance.uid ?? String(instance.startsAt), kind: 'calendar', title: agendaClip(instance.summary, 120), allDay: false,
2007
+ at: new Date(startMs).toISOString(), localDate: day, localTime: agendaLocalTimeOfInstant(startMs),
2008
+ matterId: null, ref: { kind: 'calendar', id: instance.uid ?? String(instance.startsAt) }, meta: agendaCalendarMeta(instance),
2009
+ }
2010
+ if (Number.isFinite(endMs)) item.endAt = new Date(endMs).toISOString()
2011
+ pushDay(day, item)
2012
+ }
2013
+ }
2014
+ }
2015
+ overdue.sort(agendaCompareItems)
2016
+ const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
2017
+ waiting.sort(byId)
2018
+ unscheduled.sort(byId)
2019
+ const daysOut = []
2020
+ for (let offset = 0; offset < days; offset++) {
2021
+ const date = agendaAddDays(startDay, offset)
2022
+ const items = (dayItems.get(date) ?? []).slice().sort(agendaCompareItems)
2023
+ daysOut.push({ date: date, weekday: agendaWeekday(date), load: items.length, items: items.slice(0, 20) })
2024
+ }
2025
+ const conflicts = []
2026
+ const seenConflicts = new Set()
2027
+ const addConflict = (date, leftId, rightId) => {
2028
+ const pair = [leftId, rightId].sort()
2029
+ const key = date + '|' + pair.join('|')
2030
+ if (seenConflicts.has(key)) return
2031
+ seenConflicts.add(key)
2032
+ conflicts.push({ date: date, items: pair })
2033
+ }
2034
+ for (const day of daysOut) {
2035
+ const calendars = day.items.filter((item) => item.kind === 'calendar' && !item.allDay && item.endAt)
2036
+ const timedCommitments = day.items.filter((item) => item.kind === 'commitment' && !item.allDay)
2037
+ for (let i = 0; i < calendars.length; i++) {
2038
+ const left = calendars[i]
2039
+ const leftStart = Date.parse(left.at)
2040
+ const leftEnd = Date.parse(left.endAt)
2041
+ for (let j = i + 1; j < calendars.length; j++) {
2042
+ const right = calendars[j]
2043
+ const rightStart = Date.parse(right.at)
2044
+ const rightEnd = Date.parse(right.endAt)
2045
+ if (Number.isFinite(leftStart) && Number.isFinite(leftEnd) && Number.isFinite(rightStart) && Number.isFinite(rightEnd) && leftStart < rightEnd && rightStart < leftEnd) addConflict(day.date, left.id, right.id)
2046
+ }
2047
+ for (const commitment of timedCommitments) {
2048
+ const at = Date.parse(commitment.at)
2049
+ if (Number.isFinite(at) && Number.isFinite(leftStart) && Number.isFinite(leftEnd) && at >= leftStart && at <= leftEnd) addConflict(day.date, commitment.id, left.id)
2050
+ }
2051
+ }
2052
+ }
2053
+ conflicts.sort((a, b) => (a.date === b.date ? (a.items.join(',') < b.items.join(',') ? -1 : 1) : (a.date < b.date ? -1 : 1)))
2054
+ const perDayLoad = {}
2055
+ for (const day of daysOut) if (day.load) perDayLoad[day.date] = day.load
2056
+ return {
2057
+ ok: true,
2058
+ command: 'agenda',
2059
+ now: new Date(nowMs).toISOString(),
2060
+ window: { from: startDay, to: lastDay, days: days, timezone: AGENDA_TIMEZONE },
2061
+ overdue: overdue.slice(0, 50),
2062
+ days: daysOut,
2063
+ waiting: waiting.slice(0, 20),
2064
+ unscheduled: unscheduled.slice(0, 20),
2065
+ conflicts: conflicts,
2066
+ counts: { overdue: overdue.length, today: daysOut[0] ? daysOut[0].load : 0, days: days, waiting: waiting.length, unscheduled: unscheduled.length, conflicts: conflicts.length, perDayLoad: perDayLoad },
2067
+ degraded: degraded,
2068
+ }
2069
+ }
2070
+
2071
+ function agendaUsageFail(message) {
2072
+ console.error(JSON.stringify({ error: { code: 'E_USAGE', message: message, hint: 'advisers agenda --help' } }))
2073
+ process.exitCode = 1
2074
+ }
2075
+
2076
+ /** Shared --days/--from/--now parsing for agenda + morning. */
2077
+ function parseAgendaWindowFlags(flags, timelineCommand) {
2078
+ let days = 7
2079
+ if (flags.days !== undefined) {
2080
+ if (flags.days === true || !/^\d+$/.test(String(flags.days))) { agendaUsageFail('--days must be an integer 1..31'); return null }
2081
+ days = Number(flags.days)
2082
+ if (!Number.isInteger(days) || days < 1 || days > 31) { agendaUsageFail('--days must be an integer 1..31'); return null }
2083
+ }
2084
+ let nowMs = Date.now()
2085
+ if (flags.now !== undefined) {
2086
+ const parsed = typeof flags.now === 'string' ? Date.parse(flags.now) : NaN
2087
+ if (!Number.isFinite(parsed)) { agendaUsageFail('--now must be an ISO-8601 timestamp'); return null }
2088
+ nowMs = parsed
2089
+ }
2090
+ let fromDay
2091
+ if (flags.from !== undefined) {
2092
+ if (typeof flags.from !== 'string' || !AGENDA_DATE_ONLY.test(flags.from)) { agendaUsageFail('--from must be YYYY-MM-DD'); return null }
2093
+ fromDay = flags.from
2094
+ }
2095
+ const matterId = typeof flags.matter === 'string' ? flags.matter : undefined
2096
+ return { days: days, nowMs: nowMs, fromDay: fromDay, matterId: matterId }
2097
+ }
2098
+
2099
+ function loadAgendaInputs() {
2100
+ if (mode === 'json') return { ledger: loadJson(), events: [] }
2101
+ const store = readStoreOrExit()
2102
+ if (!store) return { ledger: loadJson(), events: [] }
2103
+ const snapshot = store.read(() => ({ version: 1, matters: store.loadMatters(), commitments: store.loadCommitments() }))
2104
+ const events = store.read(() => store.listCalendarEvents())
2105
+ return { ledger: Ledger.fromJSON(snapshot, LOCAL_PORTS), events: events }
2106
+ }
2107
+
2108
+ function agendaMatterErrorLine(error) {
2109
+ console.error(JSON.stringify({ error: { code: typeof error.code === 'string' ? error.code : 'E_USAGE', message: error.message } }))
2110
+ process.exitCode = 1
2111
+ }
2112
+
2113
+ function printAgenda(data) {
2114
+ console.log('议程 ' + data.window.from + '(' + agendaWeekday(data.window.from) + ') → ' + data.window.to + '(' + agendaWeekday(data.window.to) + ')')
2115
+ console.log('逾期(' + data.counts.overdue + ')')
2116
+ if (!data.overdue.length) console.log(' (无)')
2117
+ for (const item of data.overdue) console.log(' ' + item.id + ' ' + item.title + ' · ' + (item.localDate ?? '无日期'))
2118
+ for (const day of data.days) {
2119
+ console.log(day.date + ' ' + day.weekday + '(' + day.load + ')')
2120
+ if (!day.items.length) { console.log(' (无)'); continue }
2121
+ for (const item of day.items) {
2122
+ const when = item.kind === 'calendar' && item.localTime ? item.localTime + (item.endAt ? '–' + agendaLocalTimeOfInstant(Date.parse(item.endAt)) : '') + ' ' : ''
2123
+ const marker = item.kind === 'commitment' ? ' [承诺]' : item.kind === 'done' ? ' [已完成]' : ''
2124
+ console.log(' ' + when + item.title + marker)
2125
+ }
2126
+ }
2127
+ console.log('等待他人(' + data.counts.waiting + ')')
2128
+ if (!data.waiting.length) console.log(' (无)')
2129
+ for (const item of data.waiting) console.log(' ' + item.title + ' · ' + item.debtor)
2130
+ console.log('未排期(' + data.counts.unscheduled + ')')
2131
+ if (!data.unscheduled.length) console.log(' (无)')
2132
+ for (const item of data.unscheduled) console.log(' ' + item.title)
2133
+ if (data.conflicts.length) {
2134
+ console.log('冲突(' + data.counts.conflicts + ')')
2135
+ for (const conflict of data.conflicts) console.log(' ' + conflict.date + ' ' + conflict.items.join(' / '))
2136
+ }
2137
+ if (data.degraded.length) console.log('数据降级:' + data.degraded.length + ' 条(详见 --json)')
2138
+ }
2139
+
2140
+ async function agendaCommand(args) {
2141
+ const parsed = parseFlags(args)
2142
+ const flags = parsed.flags
2143
+ if (flags.help === true) {
2144
+ console.log('usage: advisers agenda [--days 1..31] [--from YYYY-MM-DD] [--matter id] [--no-calendar] [--include-done] [--json] [--now ISO]')
2145
+ return
2146
+ }
2147
+ const window = parseAgendaWindowFlags(flags, 'agenda')
2148
+ if (!window) return
2149
+ try {
2150
+ const inputs = loadAgendaInputs()
2151
+ if (window.matterId) {
2152
+ try { resolveMatterForCommand(inputs.ledger, window.matterId, 'agenda') } catch (error) { agendaMatterErrorLine(error); return }
2153
+ }
2154
+ const data = await buildAgendaData({
2155
+ ledger: inputs.ledger,
2156
+ events: flags['no-calendar'] === true ? [] : inputs.events,
2157
+ nowMs: window.nowMs,
2158
+ days: window.days,
2159
+ fromDay: window.fromDay,
2160
+ includeCalendar: flags['no-calendar'] !== true,
2161
+ includeDone: flags['include-done'] === true,
2162
+ matterId: window.matterId,
2163
+ })
2164
+ if (flags.json === true) { console.log(JSON.stringify(data, null, 2)); return }
2165
+ printAgenda(data)
2166
+ } catch (error) { reportCommandFailure(error) }
2167
+ }
2168
+
2169
+ function morningUpcoming(agenda) {
2170
+ const rows = []
2171
+ for (const day of agenda.days.slice(1)) {
2172
+ for (const item of day.items) {
2173
+ rows.push({ date: day.date, weekday: day.weekday, kind: item.kind, id: item.id, title: item.title, localTime: item.localTime ?? null, ref: item.ref })
2174
+ }
2175
+ }
2176
+ return rows
2177
+ }
2178
+
2179
+ async function buildMorningReport(input) {
2180
+ const agenda = await buildAgendaData({
2181
+ ledger: input.ledger,
2182
+ events: input.events,
2183
+ nowMs: input.nowMs,
2184
+ days: input.days,
2185
+ fromDay: input.fromDay,
2186
+ includeCalendar: true,
2187
+ includeDone: false,
2188
+ matterId: input.matterId,
2189
+ })
2190
+ const today = agenda.days[0] ?? { date: agenda.window.from, weekday: agendaWeekday(agenda.window.from), load: 0, items: [] }
2191
+ const mustDo = today.items.filter((item) => item.kind === 'commitment')
2192
+ const meetings = today.items.filter((item) => item.kind === 'calendar')
2193
+ const upcoming = morningUpcoming(agenda)
2194
+ const risks = []
2195
+ if (agenda.overdue.length) risks.push('逾期 ' + agenda.overdue.length + ' 条:' + agenda.overdue.slice(0, 3).map((item) => item.title).join(';'))
2196
+ if (agenda.conflicts.length) risks.push('时间冲突 ' + agenda.conflicts.length + ' 处')
2197
+ if (today.load >= 3) risks.push('今日负载较高(' + today.load + ' 项)')
2198
+ if (agenda.unscheduled.length) risks.push('未排期 ' + agenda.unscheduled.length + ' 条')
2199
+ const hashInput = {
2200
+ localDay: agenda.window.from,
2201
+ window: agenda.window,
2202
+ mustDo: mustDo,
2203
+ overdue: agenda.overdue,
2204
+ meetings: meetings,
2205
+ waiting: agenda.waiting,
2206
+ upcoming: upcoming,
2207
+ unscheduled: agenda.unscheduled,
2208
+ conflicts: agenda.conflicts,
2209
+ counts: {
2210
+ mustDo: mustDo.length,
2211
+ overdue: agenda.overdue.length,
2212
+ meetings: meetings.length,
2213
+ waiting: agenda.waiting.length,
2214
+ upcoming: upcoming.length,
2215
+ unscheduled: agenda.unscheduled.length,
2216
+ conflicts: agenda.conflicts.length,
2217
+ },
2218
+ }
2219
+ const evidence = await loadEvidence()
2220
+ const dataSha256 = evidence.sha256Hex(evidence.stableStringify(hashInput, { space: 0 }))
2221
+ return { agenda: agenda, today: today, risks: risks, hashInput: hashInput, dataSha256: dataSha256 }
2222
+ }
2223
+
2224
+ function morningMarkdown(report) {
2225
+ const agenda = report.agenda
2226
+ const day = agenda.window.from
2227
+ const lines = []
2228
+ lines.push('# 晨报 ' + day + '(' + agendaWeekday(day) + ')')
2229
+ lines.push('> 本地确定性生成 · 不含模型推理 · 数据哈希 sha256:' + report.dataSha256.slice(0, 16))
2230
+ lines.push('')
2231
+ lines.push('## 今天必须做')
2232
+ if (!report.hashInput.mustDo.length) lines.push('(无)')
2233
+ for (let index = 0; index < report.hashInput.mustDo.length; index++) {
2234
+ const item = report.hashInput.mustDo[index]
2235
+ lines.push((index + 1) + '. ' + item.title + (item.localTime ? '(' + item.localTime + ' 截止)' : '(今天到期)'))
2236
+ }
2237
+ lines.push('')
2238
+ lines.push('## 逾期(' + agenda.overdue.length + ')')
2239
+ if (!agenda.overdue.length) lines.push('(无)')
2240
+ for (const item of agenda.overdue) lines.push('- ' + item.title + '(' + (item.localDate ?? '无日期') + ')')
2241
+ lines.push('')
2242
+ lines.push('## 今天会议(' + report.hashInput.meetings.length + ')')
2243
+ if (!report.hashInput.meetings.length) lines.push('(无)')
2244
+ for (const item of report.hashInput.meetings) {
2245
+ const when = item.localTime ? item.localTime + (item.endAt ? '–' + agendaLocalTimeOfInstant(Date.parse(item.endAt)) : '') + ' ' : ''
2246
+ lines.push('- ' + when + item.title)
2247
+ }
2248
+ lines.push('')
2249
+ lines.push('## 未来 7 天(' + report.hashInput.upcoming.length + ')')
2250
+ if (!report.hashInput.upcoming.length) lines.push('(无)')
2251
+ for (const item of report.hashInput.upcoming.slice(0, 20)) lines.push('- ' + item.date.slice(5) + ' ' + item.weekday + ' ' + item.title)
2252
+ lines.push('')
2253
+ lines.push('## 等待他人(' + agenda.waiting.length + ')')
2254
+ if (!agenda.waiting.length) lines.push('(无)')
2255
+ for (const item of agenda.waiting) lines.push('- ' + item.title + (item.debtor ? '(' + item.debtor + ')' : ''))
2256
+ lines.push('')
2257
+ lines.push('## 未排期(' + agenda.unscheduled.length + ')')
2258
+ if (!agenda.unscheduled.length) lines.push('(无)')
2259
+ for (const item of agenda.unscheduled) lines.push('- ' + item.title + '(无截止,建议设置日期)')
2260
+ lines.push('')
2261
+ lines.push('## 风险(' + report.risks.length + ')')
2262
+ if (!report.risks.length) lines.push('(无)')
2263
+ for (const risk of report.risks) lines.push('- ' + risk)
2264
+ lines.push('')
2265
+ lines.push('## 数据说明')
2266
+ lines.push('- 数据来源:本地账本 + 已导入日历;不含邮件正文或附件。')
2267
+ lines.push('- 本文件不构成对外承诺;金额/日期以原始交付物为准。')
2268
+ if (agenda.degraded.length) lines.push('- 数据降级 ' + agenda.degraded.length + ' 条(详见 morning --json 的 degraded 字段)。')
2269
+ return lines.join('\n') + '\n'
2270
+ }
2271
+
2272
+ async function morningReportCommand(args) {
2273
+ const parsed = parseFlags(args)
2274
+ const flags = parsed.flags
2275
+ if (flags.help === true) {
2276
+ console.log('usage: advisers morning [digest morning] [--days 1..31] [--matter id] [--out file] [--json] [--now ISO]')
2277
+ return
2278
+ }
2279
+ const window = parseAgendaWindowFlags(flags, 'morning')
2280
+ if (!window) return
2281
+ try {
2282
+ const inputs = loadAgendaInputs()
2283
+ if (window.matterId) {
2284
+ try { resolveMatterForCommand(inputs.ledger, window.matterId, 'morning') } catch (error) { agendaMatterErrorLine(error); return }
2285
+ }
2286
+ const report = await buildMorningReport({ ledger: inputs.ledger, events: inputs.events, nowMs: window.nowMs, days: window.days, fromDay: window.fromDay, matterId: window.matterId })
2287
+ const markdown = morningMarkdown(report)
2288
+ const payload = Object.assign({ ok: true, command: 'morning', generatedAt: new Date(window.nowMs).toISOString() }, report.hashInput, { dataSha256: report.dataSha256, degraded: report.agenda.degraded })
2289
+ let outPath
2290
+ if (flags.out !== undefined) {
2291
+ if (typeof flags.out !== 'string') { agendaUsageFail('--out requires a file path'); return }
2292
+ outPath = flags.out
2293
+ mkdirSync(dirname(outPath), { recursive: true })
2294
+ atomicWriteFileSync(outPath, markdown, { mode: 0o600 })
2295
+ payload.out = outPath
2296
+ }
2297
+ if (flags.json === true) { console.log(JSON.stringify(payload, null, 2)); return }
2298
+ process.stdout.write(markdown)
2299
+ if (outPath) console.log('wrote ' + outPath + ' (mode 600)')
2300
+ } catch (error) { reportCommandFailure(error) }
2301
+ }
2302
+
928
2303
  function risks(ledger) {
929
2304
  const open = ledger.openCommitments()
930
2305
  const out = []
@@ -953,6 +2328,19 @@ async function collectSourceRows(ledger) {
953
2328
  const rows = []
954
2329
  for (const c of ledger.listCommitments()) {
955
2330
  for (const e of c.evidence ?? []) {
2331
+ if (e && (e.kind === 'manual' || e.type === 'manual' || (e.sessionId === 'local' && e.turnId === 'cli'))) {
2332
+ rows.push({
2333
+ commitmentId: c.id,
2334
+ action: c.action,
2335
+ type: 'manual',
2336
+ ref: null,
2337
+ label: 'manual:operator-entered',
2338
+ quote: e.quote ?? '',
2339
+ source: { sourceVersion: 2, type: 'manual', quote: e.quote ?? '', resolution: 'unverifiable', reason: 'operator_entered' },
2340
+ unverifiable: true,
2341
+ })
2342
+ continue
2343
+ }
956
2344
  const source = normalizeSource(e.source)
957
2345
  const type = source?.type ?? 'conversation'
958
2346
  rows.push({
@@ -976,31 +2364,52 @@ async function printSources(ledger) {
976
2364
  for (const r of rows.slice(0, 20)) console.log(` ${r.commitmentId} ${r.action} ← ${r.label} (${r.ref ?? '-'}) 「${r.quote.slice(0, 80)}」`)
977
2365
  }
978
2366
 
979
- async function today(ledger, { calendar = false, sources = false, json = false } = {}) {
2367
+ async function today(openRows, { calendar = false, sources = false, json = false, ledger = null } = {}) {
980
2368
  const nowMs = Date.now()
981
2369
  const localDay = localDayOf(nowMs)
982
2370
  const weekAhead = nowMs + 7 * 86400_000
983
- // P0-1: classify in one pass, formatting each due date at most once (the old
984
- // four filters called day() up to four times per commitment).
2371
+ // P0-1/P1-2 (0.2.3): cache the parsed time + Asia/Shanghai calendar day of
2372
+ // every DISTINCT dueAt string. A 200k ledger has ~66k open commitments but
2373
+ // only a few hundred distinct due dates, so the old per-row Date.parse /
2374
+ // localDayOf calls (and the sort comparator that re-parsed every dueAt)
2375
+ // dominated today's hot path. Rows with an unparseable dueAt are counted as
2376
+ // no-due instead of crashing on Intl.format(Invalid Date).
2377
+ const dueCache = new Map()
2378
+ const dueInfo = (dueAt) => {
2379
+ let info = dueCache.get(dueAt)
2380
+ if (info === undefined) {
2381
+ const ms = Date.parse(dueAt)
2382
+ info = { ms, day: Number.isNaN(ms) ? null : localDayOf(ms) }
2383
+ dueCache.set(dueAt, info)
2384
+ }
2385
+ return info
2386
+ }
2387
+ // P0-1: classify in one pass, formatting each due date at most once.
985
2388
  const overdue = []
986
2389
  const todayDue = []
987
2390
  const week = []
988
2391
  const waiting = []
989
2392
  const noDue = []
990
- for (const c of ledger.openCommitments()) {
2393
+ let next = null
2394
+ let nextMs = Infinity
2395
+ for (const c of openRows) {
991
2396
  if (c.debtor === 'third' || c.debtor.startsWith('third:')) waiting.push(c)
992
2397
  if (!c.dueAt) { noDue.push(c); continue }
993
- const due = Date.parse(c.dueAt)
994
- if (due < nowMs) {
995
- if (localDayOf(c.dueAt) !== localDay) overdue.push(c)
2398
+ const info = dueInfo(c.dueAt)
2399
+ if (info.day === null) { noDue.push(c); continue }
2400
+ if (info.ms < nowMs) {
2401
+ if (info.day !== localDay) overdue.push(c)
996
2402
  else todayDue.push(c)
997
- } else if (localDayOf(c.dueAt) === localDay) {
2403
+ } else if (info.day === localDay) {
998
2404
  todayDue.push(c)
999
- } else if (due <= weekAhead) {
2405
+ } else if (info.ms <= weekAhead) {
1000
2406
  week.push(c)
1001
2407
  }
2408
+ // next = the earliest due row among the three buckets ; all of them have
2409
+ // ms <= weekAhead, so this single comparison replaces the old Date.parse
2410
+ // sort of the concatenated buckets.
2411
+ if (info.ms <= weekAhead && info.ms < nextMs) { nextMs = info.ms; next = c }
1002
2412
  }
1003
- const next = [...overdue, ...todayDue, ...week].sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt))[0]
1004
2413
  if (json) {
1005
2414
  // JSON contract v1 (docs/CLI-JSON.md): same classification as the human view.
1006
2415
  const payload = {
@@ -1015,7 +2424,7 @@ async function today(ledger, { calendar = false, sources = false, json = false }
1015
2424
  next: next ? { id: next.id, action: next.action, dueAt: next.dueAt } : null,
1016
2425
  }
1017
2426
  if (calendar) payload.calendar = (await calendarOccurrencesToday()).occurrences
1018
- if (sources) {
2427
+ if (sources && ledger) {
1019
2428
  payload.sources = (await collectSourceRows(ledger)).map(({ commitmentId, action, type, ref, quote }) => ({ commitmentId, action, type, ref, quote }))
1020
2429
  }
1021
2430
  console.log(JSON.stringify(payload, null, 2))
@@ -1029,7 +2438,7 @@ async function today(ledger, { calendar = false, sources = false, json = false }
1029
2438
  }
1030
2439
  console.log('下一件:' + (next?.action ?? '先定一个承诺或交付。'))
1031
2440
  if (calendar) await printCalendarToday()
1032
- if (sources) await printSources(ledger)
2441
+ if (sources && ledger) await printSources(ledger)
1033
2442
  }
1034
2443
 
1035
2444
  function tick(ledger, asJson = false) {
@@ -1040,7 +2449,7 @@ function tick(ledger, asJson = false) {
1040
2449
  const due = []
1041
2450
  const candidates = []
1042
2451
  const snoozeKeys = []
1043
- let statusChanged = false
2452
+ const wakeIds = []
1044
2453
  // P0-2: one meta query for every snooze deadline instead of getMeta() per
1045
2454
  // snoozed commitment.
1046
2455
  const snoozeUntil = store ? store.listMetaByPrefix('snooze:') : new Map()
@@ -1050,7 +2459,7 @@ function tick(ledger, asJson = false) {
1050
2459
  const until = snoozeUntil.get(`snooze:${c.id}`)
1051
2460
  if (until && Date.parse(until) > now) continue
1052
2461
  c.status = 'open'
1053
- statusChanged = true
2462
+ wakeIds.push(c.id)
1054
2463
  snoozeKeys.push(`snooze:${c.id}`)
1055
2464
  }
1056
2465
  if (!c.dueAt || Date.parse(c.dueAt) > weekAhead) continue
@@ -1098,11 +2507,17 @@ function tick(ledger, asJson = false) {
1098
2507
  nudgeRows.push({ localDay, level, commitmentId: c.id, body: c.action })
1099
2508
  due.push({ ...c, level })
1100
2509
  }
1101
- // P0-2: one transaction for all nudge inserts and one for snooze cleanup;
1102
- // the ledger snapshot is only rewritten when a snooze actually woke up.
1103
- if (store && nudgeRows.length) store.addNudges(nudgeRows)
1104
- if (store && snoozeKeys.length) store.deleteMetaKeys(snoozeKeys)
1105
- if (statusChanged) saveLedger(ledger)
2510
+ // 0.2.3 §3.3.5: nudge inserts, conditional snooze wake-ups and the snooze
2511
+ // meta cleanup commit in ONE applyTick transaction (no audit row, matching the
2512
+ // historical tick behaviour). A nudge can therefore never be recorded while
2513
+ // its wake-up is lost; the old path did a full saveLedger() on wake-up.
2514
+ if (store && (nudgeRows.length || wakeIds.length || snoozeKeys.length)) {
2515
+ store.applyTick({ nudgeRows, wakeIds, snoozeKeys })
2516
+ } else if (mode === 'json' && wakeIds.length) {
2517
+ // Legacy JSON store has no nudge/meta tables: only the in-memory wake-up can
2518
+ // be persisted (the historical behaviour).
2519
+ saveJson(ledger)
2520
+ }
1106
2521
  if (asJson) {
1107
2522
  console.log(JSON.stringify({ now: new Date(now).toISOString(), localDay, due }, null, 2))
1108
2523
  return
@@ -1117,7 +2532,7 @@ function tick(ledger, asJson = false) {
1117
2532
 
1118
2533
  function printAudit(args = []) {
1119
2534
  ensureHome()
1120
- const store = dbStore()
2535
+ const store = readStoreOrExit()
1121
2536
  if (!store) { console.log('audit requires SQLite store'); return }
1122
2537
  if (args.includes('--check-db')) {
1123
2538
  try {
@@ -1141,7 +2556,7 @@ function printPrivacy(args = []) {
1141
2556
  ensureHome()
1142
2557
  const asJson = args.includes('--json')
1143
2558
  const prove = args.includes('--prove')
1144
- const store = dbStore()
2559
+ const store = readStoreOrExit()
1145
2560
  let audit = null
1146
2561
  try { const v = store?.verifyAudit(); if (v) audit = { ok: v.ok, count: v.count ?? 0 } } catch {}
1147
2562
  // Privacy audit P2-2: list every actual egress surface from the code base
@@ -1202,7 +2617,7 @@ function printPrivacy(args = []) {
1202
2617
  }
1203
2618
 
1204
2619
  function printLinks() {
1205
- const ledger = loadLedger()
2620
+ const ledger = loadReadLedger({ links: {}, matters: {} })
1206
2621
  const rows = ledger.listLinks()
1207
2622
  if (!rows.length) { console.log('no links yet'); return }
1208
2623
  const title = new Map(ledger.listMatters().map((m) => [m.id, m.title]))
@@ -1362,21 +2777,40 @@ async function petBrief(args) {
1362
2777
  if (!result.ok) process.exitCode = 1
1363
2778
  return
1364
2779
  }
1365
- // P1-1/P0-1: pet-brief reads state.db read-only, but it still shares the
1366
- // single-writer HOME. Report a sealed vault with the stable code instead of
1367
- // "store not found", and take the instance lock so the read cannot race a
1368
- // seal/unseal/sync-pull replacing the database.
2780
+ // P1-1/P0-1: pet-brief is a pure read. Report a sealed vault with the stable
2781
+ // code instead of "store not found"; 0.2.3's read path takes no HOME lock, so
2782
+ // a live writer cannot block it and it writes/chmods nothing. A missing
2783
+ // plaintext database stays the documented structured "store not found" error
2784
+ // (this command never initializes a database).
1369
2785
  if (mode === 'sqlite') {
1370
2786
  const sealed = vaultSealedPath()
1371
2787
  if (sealed) return fail('E_VAULT_SEALED', 'the database is sealed at ' + sealed + '; run "ADVISERS_VAULT_PASSPHRASE=... advisers vault unseal" first (no empty database was created)')
1372
- ensureInstanceLock()
1373
2788
  }
1374
- const { readLedgerSnapshotReadOnly } = await import('../lib/pet-brief-store.js')
1375
2789
  let snapshot
1376
- try {
1377
- snapshot = readLedgerSnapshotReadOnly({ store: mode, dbPath: DB, statePath: STATE })
1378
- } catch (error) {
1379
- return fail(error?.code ?? 'E_STORE', error?.message ?? String(error))
2790
+ if (mode === 'json' || !existsSync(DB)) {
2791
+ const { readLedgerSnapshotReadOnly } = await import('../lib/pet-brief-store.js')
2792
+ try {
2793
+ snapshot = readLedgerSnapshotReadOnly({ store: mode, dbPath: DB, statePath: STATE })
2794
+ } catch (error) {
2795
+ return fail(error?.code ?? 'E_STORE', error?.message ?? String(error))
2796
+ }
2797
+ } else {
2798
+ // 0.2.3 P1-1: buildPetBrief only reads matters/commitments/facts, so the
2799
+ // projection no longer pays for the full nine-table snapshot.
2800
+ try {
2801
+ const store = openReadStore()
2802
+ snapshot = store.read(() => ({
2803
+ version: 1,
2804
+ matters: store.loadMatters(),
2805
+ commitments: store.loadCommitments(),
2806
+ // buildPetBrief only ever reads listFacts(), i.e. confirmed + not
2807
+ // expired/deleted; filtering status in SQL avoids mapping history rows.
2808
+ facts: store.loadFacts({ status: 'confirmed' }),
2809
+ }))
2810
+ } catch (error) {
2811
+ const code = error?.code === 'E_SCHEMA_STALE' || error?.code === 'E_SCHEMA_NEWER' ? error.code : 'E_STORE'
2812
+ return fail(code, error?.message ?? String(error))
2813
+ }
1380
2814
  }
1381
2815
  const ledger = Ledger.fromJSON(snapshot)
1382
2816
  const brief = buildPetBrief(ledger, displayPolicy ? { now: Date.now(), displayPolicy } : { now: Date.now() })
@@ -1412,7 +2846,7 @@ function printLearnReceipt(result) {
1412
2846
  }
1413
2847
 
1414
2848
  function printPreferences() {
1415
- const ledger = loadLedger()
2849
+ const ledger = loadReadLedger({ preferences: {} })
1416
2850
  const rows = ledger.listPreferences({ includeCandidates: true })
1417
2851
  if (!rows.length) { console.log('no preferences yet'); return }
1418
2852
  for (const p of rows) {
@@ -1420,7 +2854,16 @@ function printPreferences() {
1420
2854
  }
1421
2855
  }
1422
2856
 
1423
- async function doctor() {
2857
+ /**
2858
+ * `advisers doctor [--check-db]` — local diagnostics.
2859
+ *
2860
+ * Default is intentionally lightweight (0.2.3 Wave 1 / robustness P1-4):
2861
+ * opening the store validates the file header, instance lock and WAL; the O(db)
2862
+ * PRAGMA quick_check and O(index) FTS verification only run with --check-db,
2863
+ * together with WAL/backup/plaintext/temp-file checks. Any FAIL exits non-zero.
2864
+ */
2865
+ async function doctor(args = []) {
2866
+ const checkDb = Array.isArray(args) && args.includes('--check-db')
1424
2867
  const rows = []
1425
2868
  const check = (name, ok, detail = '') => rows.push({ name, ok, detail })
1426
2869
  const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(Number)
@@ -1436,37 +2879,115 @@ async function doctor() {
1436
2879
  check('sqlite', true, 'skipped (vault sealed)')
1437
2880
  check('audit', true, 'skipped (vault sealed)')
1438
2881
  check('schema', true, 'skipped (vault sealed)')
2882
+ } else if (mode === 'json') {
2883
+ // Legacy JSON store: there is no SQLite file/WAL/audit chain to inspect.
2884
+ check('database', true, existsSync(STATE) ? `${STATE} (JSON store)` : `${STATE} (JSON store, not initialized yet)`)
2885
+ check('sqlite', true, 'skipped (ADVISERS_STORE=json)')
2886
+ check('audit', true, 'unavailable (the JSON store has no audit chain)')
2887
+ check('schema', true, 'n/a (JSON store)')
2888
+ if (checkDb) check('db-integrity', true, 'skipped (JSON store mode)')
1439
2889
  } else {
2890
+ // 0.2.3 §4.7: doctor no longer takes the writer lock. The lock row reports
2891
+ // who holds it (informational, never a FAIL), and every read-only check runs
2892
+ // on the lock-free snapshot -- a live mcp/bridge therefore no longer makes
2893
+ // doctor red or blocks diagnosis.
2894
+ let lockDetail = `${LOCK_PATH} (not held)`
2895
+ try {
2896
+ const lockInfo = readInstanceLock(HOME)
2897
+ if (lockInfo?.record && !instanceLockIsStale(lockInfo)) {
2898
+ lockDetail = `${lockInfo.file} (held by pid ${lockInfo.record.pid}${lockInfo.record.command ? `: ${lockInfo.record.command}` : ''})`
2899
+ } else if (lockInfo) {
2900
+ lockDetail = `${lockInfo.file} (stale, reclaimable)`
2901
+ }
2902
+ } catch (error) { lockDetail = `${LOCK_PATH} (unreadable: ${error.message})` }
2903
+ check('lock', true, lockDetail)
1440
2904
  try {
1441
- const store = openStore()
1442
- // P0-1: doctor holds the instance lock while it inspects the store; the
1443
- // row also exposes the lock path so a stuck holder can be diagnosed.
1444
- check('lock', true, `${instanceLock?.path ?? LOCK_PATH} (held by pid ${process.pid})`)
2905
+ const store = openReadStore()
1445
2906
  let dbBytes = 0
1446
2907
  try { dbBytes = statSync(DB).size } catch {}
1447
2908
  check('database', dbBytes > 0, dbBytes > 0 ? `${DB} (${dbBytes} bytes)` : `E_DB_CORRUPT: ${DB} is 0 bytes; back it up and restore`)
1448
- const integrity = store.assertIntegrity()
1449
- check('sqlite', integrity === 'ok', `${DB} (${integrity})`)
2909
+ // The open inspected a broken WAL; surface it here (cheap) even without
2910
+ // --check-db. A read-only open never quarantines: --check-db tells the
2911
+ // user to run a writable command for that.
2912
+ const wal = store.walStatus ?? inspectWalStatus(DB)
2913
+ const walBad = ['invalid', 'truncated', 'unreadable'].includes(String(wal?.status))
2914
+ // The lightweight read-only open cannot quarantine a broken WAL. With
2915
+ // --check-db the writable maintenance section below handles it; only the
2916
+ // default (lightweight) doctor reports it as a standing failure.
2917
+ const walDeferred = checkDb && walBad
2918
+ check('wal', !walBad || walDeferred, `${wal?.status ?? 'unknown'}${wal?.bytes ? ` bytes=${wal.bytes}` : ''}${wal?.reason ? ` (${wal.reason})` : ''}${walDeferred ? '; deferred to --check-db maintenance' : checkDb ? '' : '; run --check-db for quick_check + FTS'}`)
2919
+ // 0.2.3 Wave 1: quick_check/FTS moved behind --check-db so the default
2920
+ // doctor stays sub-200ms on a large ledger.
2921
+ check('sqlite', true, `${DB} (opened read-only; run --check-db for quick_check + FTS integrity)`)
1450
2922
  const audit = store.verifyAudit()
1451
2923
  check('audit', audit.ok, audit.ok ? `${audit.count} entries` : `BROKEN at seq ${audit.seq}`)
1452
- check('schema', true, String(store.db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value ?? '?'))
2924
+ check('schema', true, String(store.schemaVersion() ?? '?'))
1453
2925
  } catch (error) {
1454
2926
  if (error?.code === 'E_DB_LOCKED') {
1455
- // Another live process holds the store; this is a real FAIL, not a
1456
- // reason to silently inspect a stale snapshot.
1457
- check('lock', false, error.message)
1458
- check('sqlite', false, 'skipped (another instance holds the instance lock)')
2927
+ // Only possible before the database exists (a first run needs the
2928
+ // writable path); nothing can be read, so this stays a real FAIL.
2929
+ check('sqlite', false, 'skipped (database does not exist yet and another instance holds the writer lock)')
1459
2930
  } else if (error?.code === 'E_DB_CORRUPT') {
1460
- check('lock', true, `${instanceLock?.path ?? LOCK_PATH} (held by pid ${process.pid})`)
1461
2931
  check('database', false, error.message)
1462
2932
  check('sqlite', false, 'refusing to open a 0-byte/corrupt database (no silent rebuild)')
1463
2933
  check('audit', false, 'skipped (database damaged)')
1464
2934
  check('schema', false, 'skipped (database damaged)')
2935
+ } else if (error?.code === 'E_SCHEMA_STALE' || error?.code === 'E_SCHEMA_NEWER') {
2936
+ check('sqlite', false, error.message)
2937
+ check('schema', false, 'skipped (schema needs a writable command)')
1465
2938
  } else {
1466
- check('lock', Boolean(instanceLock?.held), instanceLock?.held ? `${LOCK_PATH} (held by pid ${process.pid})` : 'not taken')
1467
2939
  check('sqlite', false, error.message)
1468
2940
  }
1469
2941
  }
2942
+ if (checkDb && !sealed) {
2943
+ // 0.2.3 §4.7: --check-db is the explicit maintenance path. FTS5's
2944
+ // 'integrity-check' writes an internal row, so quick_check/FTS verification
2945
+ // needs a WRITABLE connection inside the instance lock; a read-only one
2946
+ // reports 'attempt to write a readonly database' and turned a healthy
2947
+ // fresh home into a FAIL. A live ui/mcp/bridge holder therefore fails this
2948
+ // explicit check with a clear E_DB_LOCKED hint instead; the default
2949
+ // lightweight doctor above stays read-only and works while locked.
2950
+ try {
2951
+ const maintenanceStore = openStore()
2952
+ // One aggregate report reuses the Wave 0 lib contracts:
2953
+ // store.integrityReport() (quick_check + walReport + verifyFtsIntegrity).
2954
+ const report = maintenanceStore.integrityReport({ quickCheck: true, fts: true })
2955
+ const quick = report.quickCheck
2956
+ check('db-quick-check', quick?.ok === true, quick ? (quick.ok ? 'ok' : String(quick.verdict ?? quick.error ?? 'failed')) : 'skipped')
2957
+ const fts = report.fts
2958
+ const ftsOk = Boolean(fts && fts.ok)
2959
+ check('db-fts', ftsOk, !fts
2960
+ ? 'skipped'
2961
+ : `state=${fts.state} tokenizer=${fts.tokenizer ?? '-'}${ftsOk ? '' : ` errors=${(fts.errors ?? []).slice(0, 2).join(' | ')}`}`)
2962
+ const walReport = report.wal ?? maintenanceStore.walReport()
2963
+ check('db-wal', walReport.ok === true, `journal=${walReport.journalMode ?? '?'} initial=${walReport.initial?.status ?? '?'} current=${walReport.current?.status ?? '?'}${walReport.ok ? '' : `; ${(report.errors ?? []).slice(0, 1).join('')}`}`)
2964
+ checkBackupReadable(check)
2965
+ } catch (error) {
2966
+ if (error?.code === 'E_DB_LOCKED') {
2967
+ check('db-integrity', false, `${error.message}; stop the long-running advisers process (ui/mcp/bridge) and retry, or run the lightweight \`advisers doctor\` without --check-db`)
2968
+ } else {
2969
+ check('db-integrity', false, `cannot open a writable connection for the database checks: ${error.message}`)
2970
+ }
2971
+ }
2972
+ }
2973
+ }
2974
+ if (checkDb) {
2975
+ // Crash residue from an interrupted sync pull: only stale temp files whose
2976
+ // pid is gone are removed (a concurrent pull is never disturbed).
2977
+ try {
2978
+ const { cleanupStalePullTemps } = await loadSync()
2979
+ const swept = cleanupStalePullTemps(HOME)
2980
+ check('pull-temps', swept.errors.length === 0, `${swept.removed.length} stale temp(s) removed, ${swept.kept.length} kept${swept.errors.length ? `; errors: ${swept.errors.slice(0, 2).join(' | ')}` : ''}`)
2981
+ } catch (error) {
2982
+ check('pull-temps', false, String(error?.message ?? error))
2983
+ }
2984
+ const copies = plaintextDbCopies()
2985
+ const detail = copies.length
2986
+ ? `${copies.length} plaintext cop(ies)${sealed ? ' after seal' : ' (documented DB copies; purge with \`advisers vault seal --remove\`)'}: ${copies.slice(0, 6).map((file) => basename(file)).join(', ')}`
2987
+ : 'none'
2988
+ // A sealed vault plus leftover plaintext copies is a leak (FAIL); with a
2989
+ // live plaintext DB these copies are documented backups (informational).
2990
+ check('plaintext', sealed ? copies.length === 0 : true, detail)
1470
2991
  }
1471
2992
  // P2-3 (0.2.1): probe resolvability instead of importing the office barrel
1472
2993
  // (222-573ms, and only needed to answer "is the peer installed?").
@@ -1517,14 +3038,25 @@ function printStatus(asJson = false) {
1517
3038
  // count four of them (664ms / 352MB RSS at 50k rows in the round-2 audit).
1518
3039
  // listMatters()/listPreferences()/listRoutines()/listLinks() filter status,
1519
3040
  // so the counts replicate those filters exactly.
1520
- const store = openLedgerStore()
1521
- data.matters = store.countMatters({ status: 'active' })
1522
- data.prefs = store.countPreferences({ status: 'confirmed' })
1523
- data.routines = store.countRoutines()
1524
- data.links = store.countLinks({ excludeRejected: true })
1525
- data.sessions = store.countSessions()
1526
- data.deliveries = store.countDeliveries()
1527
- const usage = store.sumModelUsage()
3041
+ // 0.2.3: read through the lock-free store; one read transaction keeps the
3042
+ // seven aggregates on the same committed snapshot (§4.5).
3043
+ const store = readStoreOrExit()
3044
+ const counts = store.read(() => ({
3045
+ matters: store.countMatters({ status: 'active' }),
3046
+ prefs: store.countPreferences({ status: 'confirmed' }),
3047
+ routines: store.countRoutines(),
3048
+ links: store.countLinks({ excludeRejected: true }),
3049
+ sessions: store.countSessions(),
3050
+ deliveries: store.countDeliveries(),
3051
+ usage: store.sumModelUsage(),
3052
+ }))
3053
+ data.matters = counts.matters
3054
+ data.prefs = counts.prefs
3055
+ data.routines = counts.routines
3056
+ data.links = counts.links
3057
+ data.sessions = counts.sessions
3058
+ data.deliveries = counts.deliveries
3059
+ const usage = counts.usage
1528
3060
  if (usage.calls) data.modelUsage = usage
1529
3061
  }
1530
3062
  if (asJson) { console.log(JSON.stringify(data, null, 2)); return }
@@ -1644,6 +3176,49 @@ function safetyReasonFor(result, fallbackSurface = 'model.output') {
1644
3176
  }
1645
3177
  }
1646
3178
 
3179
+ /**
3180
+ * Print runAgent safety warnings to stderr (0.2.3 Wave 1: bin must consume
3181
+ * result.safetyWarnings; design §3.10 / security audit SEC3-03) and record one
3182
+ * actor=safety audit row per warning. External text is never printed/persisted.
3183
+ */
3184
+ async function reportAgentSafetyWarnings(warnings) {
3185
+ if (!Array.isArray(warnings) || !warnings.length) return
3186
+ const { sanitizeLabel } = await loadUntrusted()
3187
+ for (const warning of warnings) {
3188
+ const ruleIds = Array.isArray(warning?.ruleIds) ? warning.ruleIds.join(',') : ''
3189
+ const source = sanitizeLabel(warning?.source ?? 'unknown')
3190
+ const direction = String(warning?.direction ?? '-')
3191
+ const action = String(warning?.action ?? 'warn')
3192
+ const code = String(warning?.code ?? 'SAFETY_WARNING')
3193
+ const redacted = Number(warning?.redactedCount) > 0 ? ` redacted=${warning.redactedCount}` : ''
3194
+ console.error(`[safety] ${direction}/${action} ${code}${ruleIds ? ` rules=${ruleIds}` : ''} source=${source}${redacted}`)
3195
+ try {
3196
+ dbStore()?.appendAudit({
3197
+ actor: 'safety',
3198
+ action: 'safety.warning',
3199
+ allowed: action !== 'block',
3200
+ reason: auditSafeReason(`direction=${direction};action=${action};code=${code};severity=${warning?.severity ?? '-'};rules=${ruleIds || '-'};source=${source}`),
3201
+ })
3202
+ } catch {}
3203
+ }
3204
+ console.error(`[safety] ${warnings.length} 条安全提醒:外部内容按数据处理,未作为指令执行。`)
3205
+ }
3206
+
3207
+ /** Audit reason for a blocked agent turn (code/rules/source only, no content). */
3208
+ function agentBlockAuditReason(blockReason) {
3209
+ const code = safeAuditToken(blockReason?.code, 'UNTRUSTED_INJECTION')
3210
+ const rules = Array.isArray(blockReason?.ruleIds) && blockReason.ruleIds.length ? blockReason.ruleIds.join(',') : '-'
3211
+ return `code=${code};rules=${rules};source=${safeAuditToken(blockReason?.source, '-')}`
3212
+ }
3213
+
3214
+ /** Explain a blocked agent turn: it is never rendered as a successful reply. */
3215
+ async function reportAgentBlock(blockReason) {
3216
+ const ruleIds = Array.isArray(blockReason?.ruleIds) && blockReason.ruleIds.length
3217
+ ? blockReason.ruleIds.join(',')
3218
+ : (blockReason?.code ?? 'UNTRUSTED_INJECTION')
3219
+ console.error(`[safety] 已阻止:外部内容包含高风险提示注入(${ruleIds}),该内容没有发送给模型。`)
3220
+ console.error('[safety] 这不是成功交付:没有写入回复、没有生成文件或回执。请先核实来源;如确需把该内容当数据分析,可显式设置 ADVISERS_INJECTION_POLICY=warn 后重试。')
3221
+ }
1647
3222
  /**
1648
3223
  * Report a local content-safety block without echoing or persisting the original
1649
3224
  * text (privacy audit P2 / security audit SEC2-04): user-facing rejection plus a
@@ -1693,7 +3268,7 @@ async function runTurn(options) {
1693
3268
  }
1694
3269
  }
1695
3270
 
1696
- async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [] }) {
3271
+ async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [], allowPaths = [] }) {
1697
3272
  const result = await runtime.ingest({
1698
3273
  linkId: 'cli',
1699
3274
  accountId: 'local',
@@ -1728,21 +3303,25 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
1728
3303
  return
1729
3304
  }
1730
3305
  const intent = context.intent
1731
- let agentText = text
3306
+ // 0.2.3 Wave 1 (security audit SEC3-02 / design §3.10): attachment text is
3307
+ // external data, never part of the typed user message. It is handed to
3308
+ // runAgent as untrusted[] so lib/agent.js classifies and wraps it in the
3309
+ // <untrusted-data> boundary; the old "<file>" concatenation is no longer
3310
+ // emitted by bin (lib keeps a compatibility parser only).
3311
+ const untrusted = []
1732
3312
  const extracted = []
1733
3313
  const attachmentLib = attachments.length ? await loadAttachments() : null
1734
3314
  for (const file of attachments) {
1735
3315
  try {
1736
3316
  const attachment = await attachmentLib.extractAttachment(file, { cwd: process.cwd() })
1737
3317
  extracted.push(attachment)
3318
+ if (attachment?.text) untrusted.push({ label: 'attachment:' + attachment.name, text: attachment.text })
1738
3319
  console.log(`[attach] ${attachment.name} (${attachment.text.length} chars${attachment.truncated ? ', truncated' : ''})`)
1739
3320
  } catch (error) {
1740
3321
  console.log(`[attach] ${file}: ${error.message}`)
1741
3322
  }
1742
3323
  }
1743
- if (extracted.length) {
1744
- agentText = `${text}\n\n[attachments]\n` + extracted.map((a) => `<file name="${a.name}">\n${a.text}\n</file>`).join('\n\n')
1745
- }
3324
+ const agentText = text
1746
3325
  try {
1747
3326
  dbStore()?.upsertSession({ conversationId, matterId: context.matter.id, title: text.slice(0, 80) })
1748
3327
  } catch {}
@@ -1776,7 +3355,14 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
1776
3355
  const fitted = fitHistory({ system: prompt, summary: history.summary, history: history.turns, current: agentText, maxTokens: Number(process.env.ADVISERS_CONTEXT_TOKENS || 12000) })
1777
3356
  if (fitted.trimmed) console.log(`[compact] 裁剪 ${fitted.trimmed} 轮旧历史`)
1778
3357
  const { runAgent } = await loadAgent()
1779
- const { reply, artifacts, toolLog } = await runAgent({
3358
+ // 0.2.3 Wave 1 default workspace: agent file tools are confined to a 0700
3359
+ // directory under ADVISERS_HOME, not to whatever directory the CLI was
3360
+ // started from. --allow-path / ADVISERS_ALLOW_PATHS are the explicit escape.
3361
+ const workspaceRoot = ensureAgentWorkspace()
3362
+ const effectiveAllowPaths = resolveAllowPaths(allowPaths)
3363
+ if (effectiveAllowPaths.length) console.error(`[workspace] explicit allow-path: ${effectiveAllowPaths.join(', ')}`)
3364
+ const turnId = `cli_${Date.now()}_${cliSeq}`
3365
+ const agentResult = await runAgent({
1780
3366
  runtime,
1781
3367
  text: agentText,
1782
3368
  context: { ...context, prompt },
@@ -1784,18 +3370,35 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
1784
3370
  summary: history.summary,
1785
3371
  ledger,
1786
3372
  matterId: context.matter.id,
1787
- turnId: `cli_${Date.now()}_${cliSeq}`,
3373
+ turnId,
1788
3374
  backupDir: join(HOME, 'undo'),
1789
3375
  store: dbStore(),
1790
3376
  apiKey,
1791
3377
  baseUrl: process.env.ADVISERS_BASE_URL || 'https://api.deepseek.com',
1792
3378
  model: process.env.ADVISERS_MODEL || 'deepseek-flash',
1793
- cwd: process.cwd(),
3379
+ cwd: workspaceRoot,
3380
+ workspaceRoot,
3381
+ allowPaths: effectiveAllowPaths,
3382
+ untrusted,
3383
+ safetyKey: process.env.ADVISERS_AUDIT_KEY,
1794
3384
  force: process.env.ADVISERS_FORCE === '1',
1795
3385
  confirm,
1796
3386
  effort: process.env.ADVISERS_THINKING_EFFORT,
1797
3387
  onTool: (name) => { if (debug || process.env.ADVISERS_PROGRESS !== '0') console.log(`[tool] ${name}`) },
3388
+ onToolAction: auditToolAction,
1798
3389
  })
3390
+ // 0.2.3 Wave 1: consume the structured warnings (they used to be discarded)
3391
+ // and treat a blocked turn as a failure, never as a successful reply.
3392
+ const { reply, artifacts, toolLog } = agentResult
3393
+ const safetyWarnings = Array.isArray(agentResult.safetyWarnings) ? agentResult.safetyWarnings : []
3394
+ if (safetyWarnings.length) await reportAgentSafetyWarnings(safetyWarnings)
3395
+ if (agentResult.blocked) {
3396
+ lastTurnSafetyBlock = agentResult.blockReason ?? { code: 'UNTRUSTED_INJECTION', ruleIds: [], source: null }
3397
+ await reportAgentBlock(agentResult.blockReason)
3398
+ recordTurn(conversationId, 'user', text)
3399
+ try { dbStore()?.appendAudit({ actor: 'safety', action: 'policy.agent.block', allowed: false, reason: agentBlockAuditReason(agentResult.blockReason) }) } catch {}
3400
+ return
3401
+ }
1799
3402
  lastRun = { artifacts: [...new Set(artifacts)], toolLog }
1800
3403
  recordTurn(conversationId, 'user', text)
1801
3404
  recordTurn(conversationId, 'assistant', reply || '')
@@ -1868,33 +3471,38 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
1868
3471
 
1869
3472
  function parseChatArgs(args) {
1870
3473
  const files = []
3474
+ const allowPaths = []
1871
3475
  const words = []
1872
3476
  for (let i = 0; i < args.length; i++) {
1873
3477
  if (args[i] === '--file' || args[i] === '-f') {
1874
3478
  if (args[i + 1]) files.push(args[++i])
3479
+ } else if (args[i] === '--allow-path') {
3480
+ // Repeatable explicit workspace escape; ADVISERS_ALLOW_PATHS is the env
3481
+ // equivalent. Sensitive paths stay denied by the lib policy.
3482
+ if (args[i + 1]) allowPaths.push(args[++i])
1875
3483
  } else {
1876
3484
  words.push(args[i])
1877
3485
  }
1878
3486
  }
1879
- return { text: words.join(' ').trim(), files }
3487
+ return { text: words.join(' ').trim(), files, allowPaths }
1880
3488
  }
1881
3489
 
1882
3490
  async function chat(args) {
1883
- const { text, files } = parseChatArgs(args)
3491
+ const { text, files, allowPaths } = parseChatArgs(args)
1884
3492
  if (!text) {
1885
- if (process.stdin.isTTY) { await repl(); return }
1886
- console.error('usage: advisers chat [--file <path>] <text>')
3493
+ if (process.stdin.isTTY) { await repl({ allowPaths }); return }
3494
+ console.error('usage: advisers chat [--file <path>] [--allow-path <dir>]... <text>')
1887
3495
  process.exitCode = 1
1888
3496
  return
1889
3497
  }
1890
3498
  const ledger = loadLedger()
1891
3499
  const runtime = runtimeFor(ledger)
1892
- await runTurn({ runtime, ledger, text, conversationId: latestConversationId(), attachments: files })
3500
+ await runTurn({ runtime, ledger, text, conversationId: latestConversationId(), attachments: files, allowPaths })
1893
3501
  if (lastTurnSafetyBlock) process.exitCode = 1
1894
3502
  saveLedger(ledger)
1895
3503
  }
1896
3504
 
1897
- async function repl() {
3505
+ async function repl({ allowPaths = [] } = {}) {
1898
3506
  const readline = await import('node:readline/promises')
1899
3507
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout, historySize: 100 })
1900
3508
  const ledger = loadLedger()
@@ -1927,7 +3535,7 @@ async function repl() {
1927
3535
  }
1928
3536
  lastTask = { text: taskText, files: [...files] }
1929
3537
  try {
1930
- const question = await runTurn({ runtime, ledger, text: taskText, conversationId, debug, confirm, attachments: files })
3538
+ const question = await runTurn({ runtime, ledger, text: taskText, conversationId, debug, confirm, attachments: files, allowPaths })
1931
3539
  saveLedger(ledger)
1932
3540
  pendingFiles = []
1933
3541
  if (question) {
@@ -1938,7 +3546,7 @@ async function repl() {
1938
3546
  return
1939
3547
  }
1940
3548
  if (answer.trim()) {
1941
- await runTurn({ runtime, ledger, text: `${taskText}\n补充:${answer.trim()}`, conversationId, debug, confirm, attachments: files })
3549
+ await runTurn({ runtime, ledger, text: `${taskText}\n补充:${answer.trim()}`, conversationId, debug, confirm, attachments: files, allowPaths })
1942
3550
  saveLedger(ledger)
1943
3551
  }
1944
3552
  }
@@ -1967,6 +3575,8 @@ async function repl() {
1967
3575
  console.log(' /retry rerun the last task')
1968
3576
  console.log(' /correct <text> record a correction; 2nd time promotes it')
1969
3577
  console.log(' /who who I owe / who owes me')
3578
+ console.log(' /matter use <id> set the default matter for later writes')
3579
+ console.log(' /agenda 7-day agenda (commitments + calendar)')
1970
3580
  console.log(' /memory what I remember')
1971
3581
  console.log(' /commit add <action> --quote <text> [--due ISO]')
1972
3582
  console.log(' /commit ls')
@@ -2033,6 +3643,22 @@ async function repl() {
2033
3643
  continue
2034
3644
  }
2035
3645
  if (text === '/week') { printWeek(ledger); continue }
3646
+ if (text === '/agenda') {
3647
+ try {
3648
+ const inputs = loadAgendaInputs()
3649
+ const data = await buildAgendaData({ ledger: inputs.ledger, events: inputs.events, nowMs: Date.now(), days: 7, includeCalendar: true, includeDone: false })
3650
+ printAgenda(data)
3651
+ } catch (error) { console.log('agenda failed: ' + (error && error.message ? error.message : error)) }
3652
+ continue
3653
+ }
3654
+ if (text.startsWith('/matter use ')) {
3655
+ const requested = text.slice('/matter use '.length).trim()
3656
+ const matter = requested ? ledger.getMatter(requested) : undefined
3657
+ if (!matter) console.log('用法:/matter use <matter-id>(先用 advisers matter ls 查看)')
3658
+ else if (matter.status !== 'active') console.log('matter 已归档:' + requested)
3659
+ else { ledger.setRoute('active-matter', requested); saveLedger(ledger); console.log('active matter: ' + requested + ' ' + matter.title) }
3660
+ continue
3661
+ }
2036
3662
  if (text === '/digest' || text === '/digest day' || text === '/digest week') {
2037
3663
  const store = dbStore()
2038
3664
  const { buildDigest } = await loadDigest()
@@ -2062,9 +3688,11 @@ async function repl() {
2062
3688
  if (positional[0] === 'add') {
2063
3689
  const action = positional.slice(1).join(' ')
2064
3690
  if (!action || !flags.quote) { console.log('用法:/commit add <action> --quote <原话> [--due ISO]'); continue }
2065
- const c = ledger.addCommitment({ matterId: activeMatterId(ledger), debtor: flags.debtor ?? 'user', creditor: flags.creditor ?? 'me', action, dueAt: flags.due, capability: 'todo', evidence: [{ sessionId: conversationId, turnId: 'cli', quote: String(flags.quote) }] })
2066
- saveLedger(ledger)
2067
- console.log(`${c.id} open ${c.action}`)
3691
+ try {
3692
+ const c = ledger.addCommitment({ matterId: resolveMatterForCommand(ledger, flags.matter, 'commit add'), debtor: flags.debtor ?? 'user', creditor: flags.creditor ?? 'me', action, dueAt: flags.due, capability: 'todo', evidence: [manualEvidence(String(flags.quote), 'repl commit add')] })
3693
+ saveLedger(ledger)
3694
+ console.log(`${c.id} open ${c.action}`)
3695
+ } catch (error) { console.log(error && error.message ? error.message : String(error)) }
2068
3696
  continue
2069
3697
  }
2070
3698
  console.log('用法:/commit add ... 或 /commit ls'); continue
@@ -2073,7 +3701,7 @@ async function repl() {
2073
3701
  const { flags, positional } = parseFlags(text.slice(6).trim().split(/\s+/))
2074
3702
  const id = positional[0]
2075
3703
  if (!id || !flags.evidence) { console.log('用法:/done <id> --evidence <证据>'); continue }
2076
- ledger.completeCommitment(id, [{ sessionId: conversationId, turnId: 'cli', quote: String(flags.evidence) }])
3704
+ ledger.completeCommitment(id, [manualEvidence(String(flags.evidence), 'repl commit done')])
2077
3705
  saveLedger(ledger)
2078
3706
  console.log(`done: ${id}`)
2079
3707
  continue
@@ -2152,7 +3780,7 @@ async function repl() {
2152
3780
  }
2153
3781
 
2154
3782
  function ls() {
2155
- const matters = loadLedger().listMatters()
3783
+ const matters = loadReadLedger({ matters: {} }).listMatters()
2156
3784
  if (!matters.length) {
2157
3785
  console.log('no matters yet')
2158
3786
  return
@@ -2169,7 +3797,7 @@ function why(id) {
2169
3797
  return
2170
3798
  }
2171
3799
  if (id.startsWith('fact_')) {
2172
- const ledger = loadLedger()
3800
+ const ledger = loadReadLedger({ facts: {} })
2173
3801
  const fact = ledger.listFacts(undefined, true).find((f) => f.id === id)
2174
3802
  if (!fact) { console.error(`unknown fact: ${id}`); process.exitCode = 1; return }
2175
3803
  console.log(`${fact.id} [${fact.authority}] ${fact.subject} ${fact.predicate} ${fact.object}`)
@@ -2177,7 +3805,7 @@ function why(id) {
2177
3805
  for (const e of fact.evidence ?? []) console.log(`evidence: ${e.ref ?? '-'} 「${e.quote ?? ''}」`)
2178
3806
  return
2179
3807
  }
2180
- const pref = loadLedger().findPreference(id)
3808
+ const pref = loadReadLedger({ preferences: {} }).findPreference(id)
2181
3809
  if (!pref) {
2182
3810
  console.error(`unknown preference: ${id}`)
2183
3811
  process.exitCode = 1
@@ -2189,24 +3817,60 @@ function why(id) {
2189
3817
  console.log(`confidence: ${pref.confidence}; status: ${pref.status}`)
2190
3818
  }
2191
3819
 
3820
+ /**
3821
+ * `advisers forget <id>` — soft delete (fact tombstone / preference deprecated).
3822
+ *
3823
+ * 0.2.3 §3.3.8: one targeted UPDATE, no full load/save and (as in 0.2.2) no audit
3824
+ * row. An unknown id writes nothing and keeps the "unknown <kind>: <id>" text.
3825
+ */
2192
3826
  function forget(id) {
2193
3827
  if (!id) {
2194
3828
  console.error('usage: advisers forget <pref-id>')
2195
3829
  process.exitCode = 1
2196
3830
  return
2197
3831
  }
2198
- const ledger = loadLedger()
2199
3832
  const kind = id.startsWith('fact_') ? 'fact' : 'preference'
2200
- const ok = ledger.forget(kind, id)
2201
- saveLedger(ledger)
2202
- console.log(ok ? `forgotten: ${id}` : `unknown ${kind}: ${id}`)
2203
- if (!ok) process.exitCode = 1
3833
+ if (mode === 'json') {
3834
+ const ledger = loadJson()
3835
+ const ok = ledger.forget(kind, id)
3836
+ saveJson(ledger)
3837
+ console.log(ok ? `forgotten: ${id}` : `unknown ${kind}: ${id}`)
3838
+ if (!ok) process.exitCode = 1
3839
+ return
3840
+ }
3841
+ try {
3842
+ const { result: ok } = mutateWithAudit((store) => {
3843
+ if (kind === 'fact') {
3844
+ if (!store.getFact(id)) return false
3845
+ store.updateFact(id, { status: 'deleted', deletedAt: now() })
3846
+ return true
3847
+ }
3848
+ if (!store.getPreference(id)) return false
3849
+ store.updatePreference(id, { status: 'deprecated' })
3850
+ return true
3851
+ }, null)
3852
+ console.log(ok ? `forgotten: ${id}` : `unknown ${kind}: ${id}`)
3853
+ if (!ok) process.exitCode = 1
3854
+ } catch (error) { reportCommandFailure(error) }
2204
3855
  }
2205
3856
 
2206
3857
  async function exportLedger(all = false, options = {}) {
2207
- const ledger = loadLedger().toJSON()
3858
+ // 0.2.3 §4.3: exporting to stdout is a pure read (lock-free, one read
3859
+ // transaction). --out additionally appends an audit row, so that variant keeps
3860
+ // the writer lock; the legacy JSON store keeps the in-memory path.
3861
+ const writesAudit = Boolean(options.out)
3862
+ let ledger
3863
+ let store = null
3864
+ if (mode === 'json') {
3865
+ ledger = loadJson().toJSON()
3866
+ } else if (writesAudit) {
3867
+ store = dbStore()
3868
+ ledger = loadLedger().toJSON()
3869
+ } else {
3870
+ store = readStoreOrExit()
3871
+ ledger = store.read(() => store.load())
3872
+ }
2208
3873
  const payload = all ? (() => {
2209
- const store = dbStore()
2210
3874
  const tables = ['sessions', 'turns', 'session_summaries', 'summary_versions', 'deliveries', 'nudges', 'task_runs', 'audit', 'memory_candidates', 'permit_consumed']
2211
3875
  const data = {}
2212
3876
  for (const table of tables) data[table] = store ? store.db.prepare(`SELECT * FROM ${table}`).all() : []
@@ -2221,8 +3885,16 @@ async function exportLedger(all = false, options = {}) {
2221
3885
  }
2222
3886
  if (options.out) {
2223
3887
  ensureHome()
2224
- writeFileSync(options.out, text + '\n', { mode: 0o600 })
2225
- dbStore()?.appendAudit({ actor: 'local', action: options.encrypted ? 'export.encrypted' : 'export', allowed: true, reason: basename(options.out) })
3888
+ // 0.2.3 Wave 1: staged durable write (short-write loop + fsync + atomic
3889
+ // rename) so an ENOSPC export can never leave a truncated ledger file.
3890
+ try {
3891
+ atomicWriteFileSync(options.out, text + '\n', { mode: 0o600 })
3892
+ } catch (error) {
3893
+ console.error(`export failed: ${describeFsError(error, { action: 'writing the export to', target: options.out })}`)
3894
+ process.exitCode = 1
3895
+ return
3896
+ }
3897
+ store?.appendAudit({ actor: 'local', action: options.encrypted ? 'export.encrypted' : 'export', allowed: true, reason: basename(options.out) })
2226
3898
  console.log(`wrote ${options.out}${options.encrypted ? ' (AES-256-GCM)' : ''}`)
2227
3899
  } else console.log(text)
2228
3900
  }
@@ -2249,8 +3921,30 @@ async function importLedger(file, { replace = false } = {}) {
2249
3921
  ensureInstanceLock()
2250
3922
  try {
2251
3923
  const store = dbStore()
2252
- if (store) copyFileSync(DB, join(HOME, `import-backup-${Date.now()}.db`))
2253
- } catch {}
3924
+ if (store) {
3925
+ // 0.2.3 §3.3.11: fold the WAL into the main database before copying, so the
3926
+ // pre-import backup cannot silently miss committed transactions (the old
3927
+ // copyFileSync could). A busy checkpoint refuses the import: the ledger is
3928
+ // not replaced and the current database stays authoritative.
3929
+ const checkpoint = store.checkpoint({ mode: 'TRUNCATE' })
3930
+ if (checkpoint.busy) {
3931
+ console.error('import failed: database is busy (another advisers process is writing); close it and retry. The ledger was NOT replaced.')
3932
+ process.exitCode = 1
3933
+ return
3934
+ }
3935
+ // 0.2.3 Wave 1: the pre-import backup is plaintext data. Copy with retry
3936
+ // and fsync it; if the backup cannot be made, refuse to replace the ledger
3937
+ // (never proceed without a recovery copy).
3938
+ const backupFile = join(HOME, `import-backup-${Date.now()}.db`)
3939
+ copyFileWithRetrySync(DB, backupFile)
3940
+ fsyncFileSync(backupFile)
3941
+ try { chmodSync(backupFile, 0o600) } catch {}
3942
+ }
3943
+ } catch (error) {
3944
+ console.error(`import failed: cannot back up the current database before replacing it (${describeFsError(error, { action: 'copying', target: DB })})`)
3945
+ process.exitCode = 1
3946
+ return
3947
+ }
2254
3948
  try {
2255
3949
  const ledger = Ledger.fromJSON(data, LOCAL_PORTS)
2256
3950
  saveLedgerWithAudit(ledger, { actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) })
@@ -2271,9 +3965,22 @@ function backup(file) {
2271
3965
  const store = openStore()
2272
3966
  const checkpoint = store.checkpoint()
2273
3967
  if (checkpoint.busy) { console.error('backup failed: database is busy (another advisers process is writing); close it and retry'); process.exitCode = 1; return }
2274
- mkdirSync(dirname(file), { recursive: true })
2275
- copyFileSync(DB, file)
2276
- chmodSync(file, 0o600)
3968
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
3969
+ // 0.2.3 Wave 1: retry transient Windows locks and fsync the copy before
3970
+ // reporting success (a crash right after a plain copy can lose the backup).
3971
+ const existed = existsSync(file)
3972
+ try {
3973
+ copyFileWithRetrySync(DB, file)
3974
+ fsyncFileSync(file)
3975
+ chmodSync(file, 0o600)
3976
+ } catch (error) {
3977
+ // Only remove the target when this command created it: a pre-existing
3978
+ // backup must never be destroyed just because a new copy failed.
3979
+ if (!existed) { try { rmWithRetrySync(file) } catch {} }
3980
+ console.error(`backup failed: ${describeFsError(error, { action: 'copying the database to', target: file })}`)
3981
+ process.exitCode = 1
3982
+ return
3983
+ }
2277
3984
  console.log(`backup: ${file}`)
2278
3985
  }
2279
3986
 
@@ -2288,8 +3995,12 @@ async function brief(text, deep = false) {
2288
3995
  console.log(core.renderIntentBrief(brief))
2289
3996
  console.log('\n' + core.renderReadback(brief))
2290
3997
  if (deep && process.env.ADVISERS_API_KEY) {
2291
- const briefLedger = loadLedger()
2292
- const briefDenied = egressDeniedReason(briefLedger.getMatter(activeMatterId(briefLedger)), 'brief --deep')
3998
+ // 0.2.3: --deep only reads the active matter for the egress gate (the model
3999
+ // call itself is explicit egress); it takes no writer lock.
4000
+ const briefStore = mode === 'sqlite' ? readStoreOrExit() : null
4001
+ const briefLedger = readLedgerForCommand({ matters: {} })
4002
+ const briefMatterId = briefStore?.listSessions(1)?.[0]?.matterId ?? briefLedger.listMatters()[0]?.id
4003
+ const briefDenied = egressDeniedReason(briefLedger.getMatter(briefMatterId), 'brief --deep')
2293
4004
  if (briefDenied) { console.error(briefDenied); process.exitCode = 1; return }
2294
4005
  try {
2295
4006
  const { chatCompletion } = await loadModel()
@@ -2471,10 +4182,658 @@ async function routine(sub, arg, arg2) {
2471
4182
  process.exitCode = 1
2472
4183
  }
2473
4184
 
2474
- async function template(name, dataFile, outFile) {
4185
+ // ---------------------------------------------------------------------------
4186
+ // 0.2.3 P2: quote / proposal templates.
4187
+ //
4188
+ // Two deterministic Office builders on top of the existing office package
4189
+ // (buildDocx/buildXlsx/validateOffice), so no new dependency and no model call.
4190
+ // Money is parsed as integer cents (BigInt while multiplying, then a safe
4191
+ // Number) — never floating point. The same normalized data + totals are embedded
4192
+ // in the document so 'advisers verify --content' can re-check them.
4193
+ // ---------------------------------------------------------------------------
4194
+ const QUOTE_TEMPLATE_VERSION = '1'
4195
+ const QUOTE_CURRENCIES = { CNY: '¥', USD: '$', EUR: '€', HKD: 'HK$' }
4196
+ const QUOTE_MAX_ITEMS = 200
4197
+ const QUOTE_DEFAULT_DISCLAIMER = '本文件由本地模板确定性生成,仅供商务沟通参考;不构成任何法律或税务意见。金额、日期与条款以双方最终书面约定为准。'
4198
+ const QUOTE_DEFAULT_CHANGE_PROCESS = '范围或交付物发生变化时,双方先书面确认变更内容、费用与时间影响,再执行变更。'
4199
+
4200
+ function templateDataError(message, path) {
4201
+ const error = new Error(message)
4202
+ error.code = 'E_TEMPLATE_INVALID'
4203
+ if (path) error.details = { path: path }
4204
+ return error
4205
+ }
4206
+
4207
+ function templateAmountError(message, path) {
4208
+ const error = new Error(message)
4209
+ error.code = 'E_AMOUNT'
4210
+ if (path) error.details = { path: path }
4211
+ return error
4212
+ }
4213
+
4214
+ function templateFail(error) {
4215
+ console.error(JSON.stringify({
4216
+ error: {
4217
+ code: typeof error?.code === 'string' ? error.code : 'E_TEMPLATE_INVALID',
4218
+ message: error?.message ?? String(error),
4219
+ ...(error?.hint ? { hint: error.hint } : {}),
4220
+ ...(error?.details ? { details: error.details } : {}),
4221
+ },
4222
+ }))
4223
+ process.exitCode = 1
4224
+ }
4225
+
4226
+ function templateRejectUnknown(object, allowed, path) {
4227
+ if (!object || typeof object !== 'object' || Array.isArray(object)) return
4228
+ for (const key of Object.keys(object)) {
4229
+ if (!allowed.includes(key)) throw templateDataError('unknown field: ' + path + '.' + key, path + '.' + key)
4230
+ }
4231
+ }
4232
+
4233
+ function templateText(value, path, options = {}) {
4234
+ if (value === undefined || value === null) {
4235
+ if (options.optional) return undefined
4236
+ throw templateDataError(path + ' is required', path)
4237
+ }
4238
+ if (typeof value !== 'string') throw templateDataError(path + ' must be a string', path)
4239
+ const text = value.trim()
4240
+ const length = Array.from(text).length
4241
+ const min = options.min ?? 1
4242
+ const max = options.max ?? 200
4243
+ if (length < min) throw templateDataError(path + ' is empty or too short', path)
4244
+ if (length > max) throw templateDataError(path + ' is longer than ' + max + ' characters', path)
4245
+ return text
4246
+ }
4247
+
4248
+ function templateOptionalText(value, path, options = {}) {
4249
+ if (value === undefined || value === null) return undefined
4250
+ return templateText(value, path, options)
4251
+ }
4252
+
4253
+ function templateList(value, path, options = {}) {
4254
+ if (value === undefined || value === null) {
4255
+ if (options.optional) return []
4256
+ throw templateDataError(path + ' is required', path)
4257
+ }
4258
+ if (!Array.isArray(value)) throw templateDataError(path + ' must be an array', path)
4259
+ const maxItems = options.maxItems ?? 20
4260
+ if (value.length > maxItems) throw templateDataError(path + ' has more than ' + maxItems + ' items', path)
4261
+ if (options.minItems && value.length < options.minItems) throw templateDataError(path + ' needs at least ' + options.minItems + ' item(s)', path)
4262
+ const maxLen = options.maxLen ?? 200
4263
+ return value.map((item, index) => templateText(item, path + '[' + index + ']', { max: maxLen }))
4264
+ }
4265
+
4266
+ function templateDate(value, path) {
4267
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) throw templateDataError(path + ' must be YYYY-MM-DD', path)
4268
+ const ms = Date.parse(value + 'T00:00:00.000Z')
4269
+ if (!Number.isFinite(ms)) throw templateDataError(path + ' is not a valid date', path)
4270
+ return value
4271
+ }
4272
+
4273
+ /** Parse a decimal string into integer units (BigInt) at a fixed scale. */
4274
+ function templateDecimalBig(value, path, scale, options = {}) {
4275
+ if (typeof value !== 'string' || !/^\d+(?:\.\d+)?$/.test(value.trim())) {
4276
+ throw templateAmountError(path + ' must be a decimal string like "8000.00"', path)
4277
+ }
4278
+ const text = value.trim()
4279
+ const split = text.split('.')
4280
+ const whole = split[0]
4281
+ const frac = split[1] ?? ''
4282
+ if (frac.length > scale) throw templateAmountError(path + ' has more than ' + scale + ' decimal place(s)', path)
4283
+ if (whole.length > 15) throw templateAmountError(path + ' is too large', path)
4284
+ let units = BigInt(whole + frac.padEnd(scale, '0'))
4285
+ if (options.positive && units <= 0n) throw templateAmountError(path + ' must be greater than 0', path)
4286
+ if (options.max !== undefined && units > options.max) throw templateAmountError(path + ' is out of range', path)
4287
+ if (options.min !== undefined && units < options.min) throw templateAmountError(path + ' is out of range', path)
4288
+ return units
4289
+ }
4290
+
4291
+ function roundHalfUpBig(numerator, denominator) {
4292
+ const divisor = BigInt(denominator)
4293
+ return (BigInt(numerator) + divisor / 2n) / divisor
4294
+ }
4295
+
4296
+ function formatCentsNumber(cents) {
4297
+ const value = Number(cents)
4298
+ const sign = value < 0 ? '-' : ''
4299
+ const absolute = Math.abs(value)
4300
+ const whole = Math.floor(absolute / 100)
4301
+ const fraction = String(absolute % 100).padStart(2, '0')
4302
+ return sign + String(whole).replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + fraction
4303
+ }
4304
+
4305
+ function formatMoney(cents, currency) {
4306
+ const symbol = QUOTE_CURRENCIES[currency] ?? ''
4307
+ return symbol + formatCentsNumber(cents)
4308
+ }
4309
+
4310
+ function formatDiscountMoney(cents, currency) {
4311
+ return Number(cents) > 0 ? '-' + formatMoney(cents, currency) : formatMoney(0, currency)
4312
+ }
4313
+
4314
+ function normalizeQuoteParty(value, path, extraFields) {
4315
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw templateDataError(path + ' must be an object', path)
4316
+ const allowed = ['name', ...extraFields]
4317
+ templateRejectUnknown(value, allowed, path)
4318
+ const out = { name: templateText(value.name, path + '.name', { max: 100 }) }
4319
+ for (const field of extraFields) {
4320
+ const text = templateOptionalText(value[field], path + '.' + field, { max: 200 })
4321
+ if (text !== undefined) out[field] = text
4322
+ }
4323
+ return out
4324
+ }
4325
+
4326
+ function normalizeQuoteScope(value, path) {
4327
+ if (value === undefined || value === null) return { included: [], excluded: [], assumptions: [] }
4328
+ if (typeof value !== 'object' || Array.isArray(value)) throw templateDataError(path + ' must be an object', path)
4329
+ templateRejectUnknown(value, ['included', 'excluded', 'assumptions'], path)
4330
+ return {
4331
+ included: templateList(value.included, path + '.included', { optional: true }),
4332
+ excluded: templateList(value.excluded, path + '.excluded', { optional: true }),
4333
+ assumptions: templateList(value.assumptions, path + '.assumptions', { optional: true }),
4334
+ }
4335
+ }
4336
+
4337
+ function normalizeQuoteItems(value, path, required) {
4338
+ if (value === undefined || value === null) {
4339
+ if (required) throw templateDataError(path + ' is required (1..' + QUOTE_MAX_ITEMS + ' rows)', path)
4340
+ return { items: [], lines: [] }
4341
+ }
4342
+ if (!Array.isArray(value) || value.length < 1 || value.length > QUOTE_MAX_ITEMS) {
4343
+ throw templateDataError(path + ' must be an array of 1..' + QUOTE_MAX_ITEMS + ' rows', path)
4344
+ }
4345
+ const items = []
4346
+ const lines = []
4347
+ const prices = []
4348
+ for (let index = 0; index < value.length; index++) {
4349
+ const row = value[index]
4350
+ const rowPath = path + '[' + index + ']'
4351
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw templateDataError(rowPath + ' must be an object', rowPath)
4352
+ templateRejectUnknown(row, ['desc', 'qty', 'unit', 'unitPrice'], rowPath)
4353
+ const qtyUnits = templateDecimalBig(row.qty, rowPath + '.qty', 3, { positive: true, max: 1000000000n })
4354
+ const priceCents = templateDecimalBig(row.unitPrice, rowPath + '.unitPrice', 2, { max: 1000000000n })
4355
+ const lineCents = roundHalfUpBig(qtyUnits * priceCents, 1000)
4356
+ if (lineCents > 100000000000n) throw templateAmountError(rowPath + ' line amount exceeds 1e9', rowPath)
4357
+ items.push({
4358
+ desc: templateText(row.desc, rowPath + '.desc', { max: 200 }),
4359
+ qty: String(row.qty).trim(),
4360
+ unit: templateText(row.unit === undefined ? '项' : row.unit, rowPath + '.unit', { max: 10 }),
4361
+ unitPrice: String(row.unitPrice).trim(),
4362
+ })
4363
+ lines.push(Number(lineCents))
4364
+ prices.push(Number(priceCents))
4365
+ }
4366
+ return { items: items, lines: lines, prices: prices }
4367
+ }
4368
+
4369
+ function normalizeQuoteDiscount(value, path) {
4370
+ if (value === undefined || value === null) return { data: { kind: 'none', value: '0' }, units: 0n }
4371
+ if (typeof value !== 'object' || Array.isArray(value)) throw templateDataError(path + ' must be an object', path)
4372
+ templateRejectUnknown(value, ['kind', 'value'], path)
4373
+ const kind = value.kind ?? 'none'
4374
+ if (!['none', 'percent', 'amount'].includes(kind)) throw templateDataError(path + '.kind must be none|percent|amount', path + '.kind')
4375
+ if (kind === 'none') return { data: { kind: 'none', value: '0' }, units: 0n }
4376
+ const raw = value.value === undefined ? '0' : String(value.value).trim()
4377
+ const units = kind === 'percent'
4378
+ ? templateDecimalBig(raw, path + '.value', 2, { max: 10000n })
4379
+ : templateDecimalBig(raw, path + '.value', 2, { max: 100000000000n })
4380
+ return { data: { kind: kind, value: raw }, units: units }
4381
+ }
4382
+
4383
+ function normalizeQuoteTax(value, path) {
4384
+ if (value === undefined || value === null) return { data: { mode: 'none', ratePct: '0' }, units: 0n }
4385
+ if (typeof value !== 'object' || Array.isArray(value)) throw templateDataError(path + ' must be an object', path)
4386
+ templateRejectUnknown(value, ['mode', 'ratePct'], path)
4387
+ const mode = value.mode ?? 'none'
4388
+ if (!['none', 'inclusive', 'exclusive'].includes(mode)) throw templateDataError(path + '.mode must be none|inclusive|exclusive', path + '.mode')
4389
+ const raw = value.ratePct === undefined ? '0' : String(value.ratePct).trim()
4390
+ if (mode === 'none') return { data: { mode: 'none', ratePct: '0' }, units: 0n }
4391
+ const units = templateDecimalBig(raw, path + '.ratePct', 2, { max: 3000n })
4392
+ return { data: { mode: mode, ratePct: raw }, units: units }
4393
+ }
4394
+
4395
+ function normalizeQuotePayment(value, path) {
4396
+ if (value === undefined || value === null) return { milestones: [], terms: undefined }
4397
+ if (typeof value !== 'object' || Array.isArray(value)) throw templateDataError(path + ' must be an object', path)
4398
+ templateRejectUnknown(value, ['milestones', 'terms'], path)
4399
+ const milestones = []
4400
+ if (value.milestones !== undefined) {
4401
+ if (!Array.isArray(value.milestones) || value.milestones.length > 20) throw templateDataError(path + '.milestones must be an array (max 20)', path + '.milestones')
4402
+ for (let index = 0; index < value.milestones.length; index++) {
4403
+ const row = value.milestones[index]
4404
+ const rowPath = path + '.milestones[' + index + ']'
4405
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw templateDataError(rowPath + ' must be an object', rowPath)
4406
+ templateRejectUnknown(row, ['name', 'pct', 'due'], rowPath)
4407
+ const pctUnits = templateDecimalBig(row.pct, rowPath + '.pct', 2, { max: 10000n })
4408
+ milestones.push({ name: templateText(row.name, rowPath + '.name', { max: 100 }), pct: String(row.pct).trim(), due: row.due === undefined ? undefined : templateDate(row.due, rowPath + '.due'), pctUnits: pctUnits })
4409
+ }
4410
+ if (milestones.reduce((sum, row) => sum + row.pctUnits, 0n) > 10000n) throw templateDataError(path + '.milestones percentages exceed 100', path + '.milestones')
4411
+ }
4412
+ const terms = templateOptionalText(value.terms, path + '.terms', { max: 2000 })
4413
+ return { milestones: milestones, terms: terms }
4414
+ }
4415
+
4416
+ function normalizeQuoteTimeline(value, path) {
4417
+ if (value === undefined || value === null) return []
4418
+ if (!Array.isArray(value) || value.length > 50) throw templateDataError(path + ' must be an array (max 50)', path)
4419
+ const rows = []
4420
+ for (let index = 0; index < value.length; index++) {
4421
+ const row = value[index]
4422
+ const rowPath = path + '[' + index + ']'
4423
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw templateDataError(rowPath + ' must be an object', rowPath)
4424
+ templateRejectUnknown(row, ['name', 'start', 'end'], rowPath)
4425
+ const start = templateDate(row.start, rowPath + '.start')
4426
+ const end = templateDate(row.end, rowPath + '.end')
4427
+ if (Date.parse(end) < Date.parse(start)) throw templateDataError(rowPath + '.end must be >= start', rowPath + '.end')
4428
+ rows.push({ name: templateText(row.name, rowPath + '.name', { max: 100 }), start: start, end: end })
4429
+ }
4430
+ return rows
4431
+ }
4432
+
4433
+ function normalizeQuoteSignature(value, path) {
4434
+ if (value === undefined || value === null) return { issuerName: '', clientName: '' }
4435
+ if (typeof value !== 'object' || Array.isArray(value)) throw templateDataError(path + ' must be an object', path)
4436
+ templateRejectUnknown(value, ['issuerName', 'clientName'], path)
4437
+ return {
4438
+ issuerName: templateOptionalText(value.issuerName, path + '.issuerName', { max: 100 }) ?? '',
4439
+ clientName: templateOptionalText(value.clientName, path + '.clientName', { max: 100 }) ?? '',
4440
+ }
4441
+ }
4442
+
4443
+ /**
4444
+ * Validate + normalize quote/proposal input. All validation happens before any
4445
+ * output file is created; unknown fields are rejected so a typo cannot silently
4446
+ * produce a document that ignores user data.
4447
+ */
4448
+ function normalizeQuoteData(raw, kind) {
4449
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw templateDataError('data must be a JSON object', '$')
4450
+ templateRejectUnknown(raw, ['schemaVersion', 'quoteNo', 'issuedAt', 'validUntil', 'currency', 'issuer', 'client', 'project', 'scope', 'items', 'discount', 'tax', 'payment', 'timeline', 'changeProcess', 'disclaimer', 'signature'], '$')
4451
+ if (raw.schemaVersion !== undefined && raw.schemaVersion !== 1) throw templateDataError('schemaVersion must be 1', 'schemaVersion')
4452
+ const issuedAt = templateDate(raw.issuedAt, 'issuedAt')
4453
+ const validUntil = templateDate(raw.validUntil, 'validUntil')
4454
+ const issuedMs = Date.parse(issuedAt + 'T00:00:00.000Z')
4455
+ const validMs = Date.parse(validUntil + 'T00:00:00.000Z')
4456
+ if (validMs < issuedMs) throw templateDataError('validUntil must be >= issuedAt', 'validUntil')
4457
+ if (validMs - issuedMs > 180 * 86400000) throw templateDataError('validUntil is more than 180 days after issuedAt', 'validUntil')
4458
+ if (typeof raw.currency !== 'string' || !Object.prototype.hasOwnProperty.call(QUOTE_CURRENCIES, raw.currency)) {
4459
+ throw templateDataError('currency must be one of ' + Object.keys(QUOTE_CURRENCIES).join('|'), 'currency')
4460
+ }
4461
+ const quoteNo = raw.quoteNo === undefined || raw.quoteNo === null
4462
+ ? 'Q-' + issuedAt.split('-').join('') + '-001'
4463
+ : templateText(raw.quoteNo, 'quoteNo', { max: 40 })
4464
+ const issuer = normalizeQuoteParty(raw.issuer, 'issuer', ['contact', 'address'])
4465
+ const client = normalizeQuoteParty(raw.client, 'client', ['company', 'contact', 'address'])
4466
+ if (!raw.project || typeof raw.project !== 'object' || Array.isArray(raw.project)) throw templateDataError('project must be an object', 'project')
4467
+ templateRejectUnknown(raw.project, ['name', 'summary', 'deliverables'], 'project')
4468
+ const project = {
4469
+ name: templateText(raw.project.name, 'project.name', { max: 100 }),
4470
+ summary: templateOptionalText(raw.project.summary, 'project.summary', { max: 2000 }),
4471
+ deliverables: templateList(raw.project.deliverables, 'project.deliverables', { optional: kind !== 'proposal', minItems: kind === 'proposal' ? 1 : 0 }),
4472
+ }
4473
+ const scope = normalizeQuoteScope(raw.scope, 'scope')
4474
+ if (kind === 'proposal' && scope.included.length === 0) throw templateDataError('scope.included is required for a proposal', 'scope.included')
4475
+ const itemResult = normalizeQuoteItems(raw.items, 'items', kind === 'quote')
4476
+ if (kind === 'proposal' && itemResult.items.length > 0 && raw.tax !== undefined) {
4477
+ // allowed: a proposal may carry a fee summary, so no rejection here
4478
+ }
4479
+ const discount = normalizeQuoteDiscount(raw.discount, 'discount')
4480
+ const tax = normalizeQuoteTax(raw.tax, 'tax')
4481
+ const payment = normalizeQuotePayment(raw.payment, 'payment')
4482
+ const timeline = normalizeQuoteTimeline(raw.timeline, 'timeline')
4483
+ const changeProcess = templateOptionalText(raw.changeProcess, 'changeProcess', { max: 2000 }) ?? QUOTE_DEFAULT_CHANGE_PROCESS
4484
+ const disclaimerRaw = templateOptionalText(raw.disclaimer, 'disclaimer', { max: 2000 })
4485
+ const disclaimer = disclaimerRaw && disclaimerRaw.length ? disclaimerRaw : QUOTE_DEFAULT_DISCLAIMER
4486
+ const signature = normalizeQuoteSignature(raw.signature, 'signature')
4487
+ const data = {
4488
+ schemaVersion: 1,
4489
+ quoteNo: quoteNo,
4490
+ issuedAt: issuedAt,
4491
+ validUntil: validUntil,
4492
+ currency: raw.currency,
4493
+ issuer: issuer,
4494
+ client: client,
4495
+ project: project,
4496
+ scope: scope,
4497
+ items: itemResult.items,
4498
+ discount: discount.data,
4499
+ tax: tax.data,
4500
+ payment: { milestones: payment.milestones.map((row) => ({ name: row.name, pct: row.pct, ...(row.due ? { due: row.due } : {}) })), ...(payment.terms ? { terms: payment.terms } : {}) },
4501
+ timeline: timeline,
4502
+ changeProcess: changeProcess,
4503
+ disclaimer: disclaimer,
4504
+ signature: signature,
4505
+ }
4506
+ const subtotalCents = itemResult.lines.reduce((sum, cents) => sum + cents, 0)
4507
+ let discountCents = 0
4508
+ if (discount.data.kind === 'percent') discountCents = Number(roundHalfUpBig(BigInt(subtotalCents) * discount.units, 10000))
4509
+ else if (discount.data.kind === 'amount') discountCents = Number(discount.units)
4510
+ if (discountCents > subtotalCents) throw templateDataError('discount exceeds subtotal', 'discount')
4511
+ const netCents = subtotalCents - discountCents
4512
+ let taxCents = 0
4513
+ let totalCents = netCents
4514
+ if (tax.data.mode === 'exclusive') {
4515
+ taxCents = Number(roundHalfUpBig(BigInt(netCents) * tax.units, 10000))
4516
+ totalCents = netCents + taxCents
4517
+ } else if (tax.data.mode === 'inclusive') {
4518
+ const netOfTax = Number(roundHalfUpBig(BigInt(netCents) * 10000n, 10000n + tax.units))
4519
+ taxCents = netCents - netOfTax
4520
+ totalCents = netCents
4521
+ }
4522
+ const totals = { subtotalCents: subtotalCents, discountCents: discountCents, taxCents: taxCents, totalCents: totalCents }
4523
+ return { kind: kind, data: data, lines: itemResult.lines, prices: itemResult.prices, totals: totals }
4524
+ }
4525
+
4526
+ function quoteTotalsJson(normalized) {
4527
+ const currency = normalized.data.currency
4528
+ return {
4529
+ subtotal: formatCentsNumber(normalized.totals.subtotalCents),
4530
+ discount: formatCentsNumber(normalized.totals.discountCents),
4531
+ tax: formatCentsNumber(normalized.totals.taxCents),
4532
+ total: formatCentsNumber(normalized.totals.totalCents),
4533
+ currency: currency,
4534
+ formatted: {
4535
+ subtotal: formatMoney(normalized.totals.subtotalCents, currency),
4536
+ discount: formatDiscountMoney(normalized.totals.discountCents, currency),
4537
+ tax: formatMoney(normalized.totals.taxCents, currency),
4538
+ total: formatMoney(normalized.totals.totalCents, currency),
4539
+ },
4540
+ }
4541
+ }
4542
+
4543
+ function quoteDocxSpec(normalized, dataSha256) {
4544
+ const data = normalized.data
4545
+ const currency = data.currency
4546
+ const totals = normalized.totals
4547
+ const itemRows = normalized.lines.map((lineCents, index) => {
4548
+ const item = data.items[index]
4549
+ return [
4550
+ String(index + 1),
4551
+ item.desc,
4552
+ item.qty,
4553
+ item.unit,
4554
+ formatCentsNumber(normalized.prices[index]),
4555
+ formatCentsNumber(lineCents),
4556
+ ]
4557
+ })
4558
+ const scopeBullets = []
4559
+ for (const line of data.scope.included) scopeBullets.push('包含:' + line)
4560
+ for (const line of data.scope.excluded) scopeBullets.push('不包含:' + line)
4561
+ for (const line of data.scope.assumptions) scopeBullets.push('假设:' + line)
4562
+ const milestoneRows = data.timeline.map((row) => [row.name, row.start, row.end])
4563
+ const paymentBullets = data.payment.milestones.map((row) => row.name + ' ' + row.pct + '%' + (row.due ? ',' + row.due : ''))
4564
+ if (data.payment.terms) paymentBullets.push('付款条件:' + data.payment.terms)
4565
+ const taxLabel = data.tax.mode === 'inclusive' ? '税额(含税价内)' : data.tax.mode === 'exclusive' ? '税额(未税价外加)' : '税额(未计)'
4566
+ const totalsRows = [
4567
+ ['小计', formatMoney(totals.subtotalCents, currency)],
4568
+ ['折扣', formatDiscountMoney(totals.discountCents, currency)],
4569
+ [taxLabel, formatMoney(totals.taxCents, currency)],
4570
+ ['合计', formatMoney(totals.totalCents, currency)],
4571
+ ]
4572
+ const sections = [
4573
+ {
4574
+ heading: '双方信息',
4575
+ table: {
4576
+ headers: ['角色', '名称', '联系人', '地址'],
4577
+ rows: [
4578
+ ['报价方', data.issuer.name, data.issuer.contact ?? '', data.issuer.address ?? ''],
4579
+ ['客户', data.client.name + (data.client.company ? '(' + data.client.company + ')' : ''), data.client.contact ?? '', data.client.address ?? ''],
4580
+ ],
4581
+ },
4582
+ },
4583
+ { heading: '需求理解', paragraphs: [data.project.name + (data.project.summary && data.project.summary.length ? ' — ' + data.project.summary : '(详见范围与交付物)')] },
4584
+ { heading: '范围与假设', bullets: scopeBullets.length ? scopeBullets : ['待双方书面确认'] },
4585
+ { heading: '交付物与里程碑', bullets: data.project.deliverables.length ? data.project.deliverables : ['以双方书面确认的交付物为准'], ...(milestoneRows.length ? { table: { headers: ['阶段', '开始', '结束'], rows: milestoneRows } } : {}) },
4586
+ { heading: '报价明细', table: { headers: ['序号', '项目', '数量', '单位', '单价', '小计'], rows: itemRows.length ? itemRows : [['1', '(见范围)', '1', '项', formatMoney(0, currency), formatMoney(0, currency)]] } },
4587
+ { heading: '金额汇总', table: { headers: ['项目', '金额'], rows: totalsRows } },
4588
+ { heading: '付款条件', bullets: paymentBullets.length ? paymentBullets : ['以双方书面确认的付款条件为准'] },
4589
+ { heading: '变更流程', paragraphs: [data.changeProcess] },
4590
+ { heading: '签章', paragraphs: ['报价方(签章):' + (data.signature.issuerName ? ' ' + data.signature.issuerName : ''), '客户(签章):' + (data.signature.clientName ? ' ' + data.signature.clientName : '')] },
4591
+ { heading: '免责声明', paragraphs: [data.disclaimer] },
4592
+ { heading: '校验', paragraphs: ['模板版本:' + QUOTE_TEMPLATE_VERSION, '数据哈希(SHA-256):' + dataSha256] },
4593
+ ]
4594
+ return { title: '报价单', subtitle: data.quoteNo + ' · 日期 ' + data.issuedAt + ' · 有效期至 ' + data.validUntil, sections: sections }
4595
+ }
4596
+
4597
+ function proposalDocxSpec(normalized, dataSha256) {
4598
+ const data = normalized.data
4599
+ const currency = data.currency
4600
+ const sections = [
4601
+ { heading: '背景与目标', paragraphs: [data.project.summary && data.project.summary.length ? data.project.summary : data.project.name] },
4602
+ { heading: '范围(包含)', bullets: data.scope.included.length ? data.scope.included : ['以双方书面确认的范围为准'] },
4603
+ { heading: '范围(不包含)', bullets: data.scope.excluded.length ? data.scope.excluded : ['(未特别列出的工作不包含在本提案内)'] },
4604
+ { heading: '交付物', bullets: data.project.deliverables },
4605
+ {
4606
+ heading: '里程碑与验收标准',
4607
+ ...(data.timeline.length ? { table: { headers: ['阶段', '开始', '结束'], rows: data.timeline.map((row) => [row.name, row.start, row.end]) } } : { paragraphs: ['里程碑以双方书面确认的时间表为准。'] }),
4608
+ bullets: ['验收标准:各阶段以书面确认的交付物为验收依据。'],
4609
+ },
4610
+ { heading: '假设与依赖', bullets: data.scope.assumptions.length ? data.scope.assumptions : ['(无特别假设)'] },
4611
+ { heading: '双方职责', bullets: ['报价方:按约定完成交付物,并主动同步进度与风险。', '客户:按约定提供资料、反馈与验收确认。'] },
4612
+ {
4613
+ heading: '费用概要',
4614
+ ...(data.items.length
4615
+ ? { table: { headers: ['项目', '金额'], rows: [['小计', formatMoney(normalized.totals.subtotalCents, currency)], ['折扣', formatDiscountMoney(normalized.totals.discountCents, currency)], ['税额', formatMoney(normalized.totals.taxCents, currency)], ['合计', formatMoney(normalized.totals.totalCents, currency)]] } }
4616
+ : { paragraphs: ['费用另行书面确认(本提案不构成报价)。'] }),
4617
+ },
4618
+ { heading: '风险与变更', paragraphs: [data.changeProcess] },
4619
+ { heading: '有效期与免责声明', paragraphs: ['有效期至 ' + data.validUntil + '。', data.disclaimer] },
4620
+ { heading: '签章', paragraphs: ['报价方(签章):' + (data.signature.issuerName ? ' ' + data.signature.issuerName : ''), '客户(签章):' + (data.signature.clientName ? ' ' + data.signature.clientName : '')] },
4621
+ { heading: '校验', paragraphs: ['模板版本:' + QUOTE_TEMPLATE_VERSION, '数据哈希(SHA-256):' + dataSha256] },
4622
+ ]
4623
+ return { title: '项目提案', subtitle: data.client.name + ' · ' + data.project.name + ' · ' + data.quoteNo + ' · 日期 ' + data.issuedAt + ' · 有效期至 ' + data.validUntil, sections: sections }
4624
+ }
4625
+
4626
+ function quoteXlsxSpec(normalized, dataSha256) {
4627
+ const data = normalized.data
4628
+ const currency = data.currency
4629
+ const rows = normalized.lines.map((lineCents, index) => {
4630
+ const item = data.items[index]
4631
+ return {
4632
+ index: String(index + 1),
4633
+ desc: item.desc,
4634
+ qty: item.qty,
4635
+ unit: item.unit,
4636
+ unitPrice: formatCentsNumber(normalized.prices[index]),
4637
+ subtotal: formatCentsNumber(lineCents),
4638
+ }
4639
+ })
4640
+ const summary = [
4641
+ { index: '', desc: '小计', qty: '', unit: '', unitPrice: '', subtotal: formatMoney(normalized.totals.subtotalCents, currency) },
4642
+ { index: '', desc: '折扣', qty: '', unit: '', unitPrice: '', subtotal: formatDiscountMoney(normalized.totals.discountCents, currency) },
4643
+ { index: '', desc: '税额', qty: '', unit: '', unitPrice: '', subtotal: formatMoney(normalized.totals.taxCents, currency) },
4644
+ { index: '', desc: '合计', qty: '', unit: '', unitPrice: '', subtotal: formatMoney(normalized.totals.totalCents, currency) },
4645
+ ]
4646
+ // Header metadata + verification block travel inside the sheet so
4647
+ // `verify --content --template quote --data <json>` can re-check identity,
4648
+ // totals and data hash on XLSX exactly like on DOCX.
4649
+ const metaRow = (label) => ({ index: '', desc: label, qty: '', unit: '', unitPrice: '', subtotal: '' })
4650
+ const meta = [
4651
+ metaRow('报价单:' + data.quoteNo),
4652
+ metaRow('客户:' + data.client.name + (data.client.company ? '(' + data.client.company + ')' : '')),
4653
+ metaRow('项目:' + data.project.name),
4654
+ metaRow('日期:' + data.issuedAt),
4655
+ metaRow('有效期至:' + data.validUntil),
4656
+ metaRow('数据哈希(SHA-256):' + dataSha256),
4657
+ metaRow('本文件由本地模板确定性生成,仅供商务沟通参考'),
4658
+ metaRow(''),
4659
+ ]
4660
+ return {
4661
+ sheet: '报价明细',
4662
+ columns: [
4663
+ { header: '序号', key: 'index', width: 8 },
4664
+ { header: '项目', key: 'desc', width: 32 },
4665
+ { header: '数量', key: 'qty', width: 10 },
4666
+ { header: '单位', key: 'unit', width: 10 },
4667
+ { header: '单价', key: 'unitPrice', width: 16 },
4668
+ { header: '小计', key: 'subtotal', width: 16 },
4669
+ ],
4670
+ rows: meta.concat(rows).concat(summary),
4671
+ formulas: [],
4672
+ }
4673
+ }
4674
+
4675
+ async function loadOfficeBarrel() {
4676
+ if (process.env.ADVISERS_OFFICE_LOCAL === '1') return import('../../office/dist/index.js')
4677
+ try {
4678
+ return await import('advisers-office')
4679
+ } catch {
4680
+ try { return await import('../../office/dist/index.js') } catch { return null }
4681
+ }
4682
+ }
4683
+
4684
+ async function readOfficeText(file, ext) {
4685
+ const readModule = await importOfficeSubmodule('read')
4686
+ const readOffice = readModule?.readOffice
4687
+ const officeToText = readModule?.officeToText
4688
+ if (typeof readOffice !== 'function' || typeof officeToText !== 'function') return null
4689
+ try {
4690
+ const doc = await readOffice(readFileSync(file), ext)
4691
+ return officeToText(doc, 200000)
4692
+ } catch { return null }
4693
+ }
4694
+
4695
+ function quoteTemplateChecks(kind, normalized, dataSha256, text) {
4696
+ const data = normalized.data
4697
+ const currency = data.currency
4698
+ const totals = normalized.totals
4699
+ const checks = []
4700
+ const check = (id, ok, detail) => checks.push({ id: id, ok: Boolean(ok), ...(detail ? { detail: detail } : {}) })
4701
+ const expected = [
4702
+ data.client.name,
4703
+ data.project.name,
4704
+ data.quoteNo,
4705
+ data.issuedAt,
4706
+ data.validUntil,
4707
+ ]
4708
+ const prefix = kind === 'proposal' ? 'proposal' : 'quote'
4709
+ const hasFeeItems = normalized.data.items.length > 0
4710
+ if (hasFeeItems) expected.push(formatMoney(totals.totalCents, currency))
4711
+ if (kind === 'proposal') expected.push(data.project.deliverables[0] ?? '', data.scope.included[0] ?? '', '项目提案')
4712
+ check(prefix + '.required', expected.every((value) => !value || text.includes(value)), 'missing required document text')
4713
+ if (hasFeeItems) check(prefix + '.totals', [formatMoney(totals.subtotalCents, currency), formatDiscountMoney(totals.discountCents, currency), formatMoney(totals.taxCents, currency), formatMoney(totals.totalCents, currency)].every((value) => text.includes(value)), 'totals in the document do not match the input data')
4714
+ else check(prefix + '.totals', true, 'no fee items in this input; totals not applicable')
4715
+ check(prefix + '.data_hash', text.includes(dataSha256), 'dataSha256 not found in the document')
4716
+ const placeholder = /\{\{|T[O]DO|TBD|F[I]XME|占位|待填写|undefined|NaN/.test(text)
4717
+ check(prefix + '.no_placeholders', !placeholder, 'placeholder text found')
4718
+ return checks
4719
+ }
4720
+
4721
+ /** 'advisers template quote|proposal <data.json> <out>' — new deterministic templates. */
4722
+ async function templateQuoteOrProposal(name, dataFile, outFile, flags) {
4723
+ try {
4724
+ if (!dataFile || !outFile) throw templateDataError('usage: advisers template ' + name + ' <data.json> <out.docx|out.xlsx>', '$')
4725
+ const ext = outFile.split('.').pop()?.toLowerCase()
4726
+ const expected = name === 'quote' ? ['docx', 'xlsx'] : ['docx']
4727
+ if (!expected.includes(ext)) {
4728
+ const error = new Error('template ' + name + ' writes ' + expected.join('/') + '; got .' + ext)
4729
+ error.code = 'E_TEMPLATE_OUTPUT'
4730
+ throw error
4731
+ }
4732
+ let raw
4733
+ try {
4734
+ raw = JSON.parse(readFileSync(dataFile, 'utf8'))
4735
+ } catch (error) {
4736
+ const wrapped = new Error('cannot read template data JSON: ' + error.message)
4737
+ wrapped.code = 'E_TEMPLATE_INVALID'
4738
+ throw wrapped
4739
+ }
4740
+ const normalized = normalizeQuoteData(raw, name)
4741
+ const evidence = await loadEvidence()
4742
+ const dataSha256 = evidence.sha256Hex(evidence.stableStringify(normalized.data, { space: 0 }))
4743
+ // Import only the dist submodules the chosen format needs (build +
4744
+ // validate + deterministic content checks), never the office barrel: the
4745
+ // barrel also pulls exceljs/pptxgenjs and costs seconds per CLI start.
4746
+ const builderModule = ext === 'docx' ? await importOfficeSubmodule('docx') : await importOfficeSubmodule('xlsx')
4747
+ const validateModule = await importOfficeSubmodule('validate')
4748
+ const checkModule = await importOfficeSubmodule('check')
4749
+ let buffer
4750
+ let structure
4751
+ let content
4752
+ if (ext === 'docx') {
4753
+ const spec = name === 'quote' ? quoteDocxSpec(normalized, dataSha256) : proposalDocxSpec(normalized, dataSha256)
4754
+ if (typeof builderModule?.buildDocx === 'function') buffer = await builderModule.buildDocx(spec)
4755
+ else {
4756
+ const mod = await loadOfficeBarrel()
4757
+ if (!mod || typeof mod.buildDocx !== 'function') throw Object.assign(new Error('advisers-office is not installed; run: npm i -g advisers-office@next'), { code: 'E_TEMPLATE_INVALID' })
4758
+ buffer = await mod.buildDocx(spec)
4759
+ }
4760
+ } else {
4761
+ if (typeof builderModule?.buildXlsx === 'function') buffer = await builderModule.buildXlsx(quoteXlsxSpec(normalized, dataSha256))
4762
+ else {
4763
+ const mod = await loadOfficeBarrel()
4764
+ if (!mod || typeof mod.buildXlsx !== 'function') throw Object.assign(new Error('advisers-office is not installed; run: npm i -g advisers-office@next'), { code: 'E_TEMPLATE_INVALID' })
4765
+ buffer = await mod.buildXlsx(quoteXlsxSpec(normalized, dataSha256))
4766
+ }
4767
+ }
4768
+ if (typeof validateModule?.validateOffice === 'function') structure = await validateModule.validateOffice(buffer, ext)
4769
+ else {
4770
+ const mod = await loadOfficeBarrel()
4771
+ if (!mod || typeof mod.validateOffice !== 'function') throw Object.assign(new Error('advisers-office is not installed; run: npm i -g advisers-office@next'), { code: 'E_TEMPLATE_INVALID' })
4772
+ structure = await mod.validateOffice(buffer, ext)
4773
+ }
4774
+ if (typeof checkModule?.checkOffice === 'function') content = await checkModule.checkOffice(buffer, ext)
4775
+ if (!structure || structure.ok !== true) {
4776
+ const error = new Error('generated ' + ext + ' failed structural validation' + (structure && structure.missing && structure.missing.length ? ': ' + structure.missing.join('; ') : ''))
4777
+ error.code = 'E_VERIFY_FAILED'
4778
+ throw error
4779
+ }
4780
+ mkdirSync(dirname(outFile), { recursive: true })
4781
+ await backupCliFile(outFile)
4782
+ writeFileSync(outFile, buffer)
4783
+ dbStore()?.appendAudit({ actor: 'local', action: 'office.template', allowed: true, reason: name })
4784
+ let deliveryId
4785
+ if (flags['record-delivery'] === true) {
4786
+ recordDeliveryWithAudit({
4787
+ files: [outFile],
4788
+ tool: 'template:' + name,
4789
+ title: typeof flags.title === 'string' ? flags.title : (name === 'quote' ? '报价单' : '项目提案'),
4790
+ validation: ext + ((content && content.ok === false) ? ':content-warn' : ':ok'),
4791
+ audit: { actor: 'local', action: 'template.record', allowed: true, reason: name },
4792
+ matterId: typeof flags.matter === 'string' ? flags.matter : undefined,
4793
+ })
4794
+ try { deliveryId = dbStore()?.listDeliveries(1)?.[0]?.id } catch {}
4795
+ }
4796
+ if (flags.json === true) {
4797
+ console.log(JSON.stringify({
4798
+ ok: true,
4799
+ command: 'template',
4800
+ template: name,
4801
+ format: ext,
4802
+ out: outFile,
4803
+ bytes: buffer.length,
4804
+ templateVersion: QUOTE_TEMPLATE_VERSION,
4805
+ dataSha256: dataSha256,
4806
+ quoteNo: normalized.data.quoteNo,
4807
+ totals: quoteTotalsJson(normalized),
4808
+ verify: { structure: structure, content: content ?? null },
4809
+ ...(deliveryId ? { deliveryId: deliveryId } : {}),
4810
+ }, null, 2))
4811
+ return
4812
+ }
4813
+ console.log('wrote ' + outFile + ' (' + buffer.length + ' bytes)')
4814
+ console.log('合计:' + formatMoney(normalized.totals.totalCents, normalized.data.currency))
4815
+ } catch (error) {
4816
+ templateFail(error)
4817
+ }
4818
+ }
4819
+
4820
+ /**
4821
+ * 'advisers template ...' dispatcher.
4822
+ * quote/proposal are the 0.2.3 product templates (deterministic Office builders,
4823
+ * no model); every pre-0.2.3 template name keeps the exact legacy behaviour.
4824
+ */
4825
+ async function template(rawArgs) {
4826
+ const parsed = parseFlags(rawArgs)
4827
+ const positional = parsed.positional
4828
+ const name = positional[0]
4829
+ if (name === 'quote' || name === 'proposal') return templateQuoteOrProposal(name, positional[1], positional[2], parsed.flags)
4830
+ return legacyTemplate(name, positional[1], positional[2])
4831
+ }
4832
+
4833
+ async function legacyTemplate(name, dataFile, outFile) {
2475
4834
  const names = ['weekly', 'budget', 'presentation', 'flow', 'mindmap', 'minutes', 'notice']
2476
4835
  if (!names.includes(name) || !dataFile || !outFile) {
2477
- console.error('usage: advisers template <weekly|budget|presentation|flow|mindmap|minutes|notice> <data.json> <out>')
4836
+ console.error('usage: advisers template quote|proposal <data.json> <out.docx> or advisers template <weekly|budget|presentation|flow|mindmap|minutes|notice> <data.json> <out>')
2478
4837
  process.exitCode = 1
2479
4838
  return
2480
4839
  }
@@ -2654,7 +5013,8 @@ async function capture(args) {
2654
5013
  const store = dbStore()
2655
5014
  if (!store) { console.error('capture requires SQLite store'); process.exitCode = 1; return }
2656
5015
  const ledger = loadLedger()
2657
- const matterId = activeMatterId(ledger, flags.matter)
5016
+ let matterId
5017
+ try { matterId = resolveMatterForCommand(ledger, flags.matter, 'capture') } catch (error) { console.error(error.message); process.exitCode = 1; return }
2658
5018
  const denied = egressDeniedReason(ledger.getMatter(matterId), 'capture')
2659
5019
  if (denied) { console.error(denied); process.exitCode = 1; return }
2660
5020
  saveLedger(ledger)
@@ -2681,7 +5041,8 @@ async function captureFromMail(flags) {
2681
5041
  ensureHome()
2682
5042
  const store = dbStore()
2683
5043
  const ledger = loadLedger()
2684
- const matterId = activeMatterId(ledger, flags.matter)
5044
+ let matterId
5045
+ try { matterId = resolveMatterForCommand(ledger, flags.matter, 'capture') } catch (error) { console.error(error.message); process.exitCode = 1; return }
2685
5046
  const denied = egressDeniedReason(ledger.getMatter(matterId), 'mail')
2686
5047
  if (denied) { console.error(denied); process.exitCode = 1; return }
2687
5048
  saveLedger(ledger)
@@ -2732,7 +5093,8 @@ async function captureFromTranscript(flags) {
2732
5093
  ensureHome()
2733
5094
  const store = dbStore()
2734
5095
  const ledger = loadLedger()
2735
- const matterId = activeMatterId(ledger, flags.matter)
5096
+ let matterId
5097
+ try { matterId = resolveMatterForCommand(ledger, flags.matter, 'capture') } catch (error) { console.error(error.message); process.exitCode = 1; return }
2736
5098
  const denied = egressDeniedReason(ledger.getMatter(matterId), 'transcript')
2737
5099
  if (denied) { console.error(denied); process.exitCode = 1; return }
2738
5100
  saveLedger(ledger)
@@ -2769,7 +5131,8 @@ async function captureFromImap(flags) {
2769
5131
  ensureHome()
2770
5132
  const store = dbStore()
2771
5133
  const ledger = loadLedger()
2772
- const matterId = activeMatterId(ledger, flags.matter)
5134
+ let matterId
5135
+ try { matterId = resolveMatterForCommand(ledger, flags.matter, 'capture') } catch (error) { console.error(error.message); process.exitCode = 1; return }
2773
5136
  const denied = egressDeniedReason(ledger.getMatter(matterId), 'imap')
2774
5137
  if (denied) { console.error(denied); process.exitCode = 1; return }
2775
5138
  saveLedger(ledger)
@@ -2892,8 +5255,10 @@ async function ui(args) {
2892
5255
  const flags = parseFlags(args).flags
2893
5256
  // --port 0 requests an ephemeral port (used by tests and scripts).
2894
5257
  const port = typeof flags.port === 'string' && flags.port.trim() !== '' ? Number(flags.port) : 17860
2895
- const ledger = loadLedger()
2896
- const store = dbStore()
5258
+ // 0.2.3 §4.8: ui only serves a read snapshot. It loads the tables it needs
5259
+ // (commitments) through the lock-free read store and holds NO writer lock, so
5260
+ // ordinary CLI writes keep working while it runs.
5261
+ const ledger = loadReadLedger({ commitments: {} })
2897
5262
  const { buildReminders } = await loadRemind()
2898
5263
  const snapshot = {
2899
5264
  today: () => {
@@ -2928,11 +5293,17 @@ async function ui(args) {
2928
5293
  async function remind(args) {
2929
5294
  const { flags, positional } = parseFlags(args)
2930
5295
  ensureHome()
2931
- const store = dbStore()
2932
- const ledger = loadLedger()
2933
- const scheduler = await loadScheduler()
2934
5296
  const sub = positional[0]
2935
5297
  const apply = flags.apply === true
5298
+ // 0.2.3 §4.3: only the branches that write (audit rows for install/uninstall/
5299
+ // ICS export/delivered reminders) take the writer lock; the plain
5300
+ // `remind`/`--json`/`status` reads use the lock-free store and load only
5301
+ // commitments. These branches are mutually exclusive with a plain read.
5302
+ const mutating = sub === 'install' || sub === 'uninstall' || flags.install === true ||
5303
+ flags.uninstall === true || flags.ics !== undefined || flags.deliver === true || flags.notify === true
5304
+ const store = mutating ? dbStore() : readStoreOrExit()
5305
+ const ledger = mutating ? loadLedger({ commitments: {} }) : loadReadLedger({ commitments: {} })
5306
+ const scheduler = await loadScheduler()
2936
5307
  if (sub === 'install' || flags.install) {
2937
5308
  const dir = join(HOME, 'scheduler')
2938
5309
  mkdirSync(dir, { recursive: true, mode: 0o700 })
@@ -3001,11 +5372,9 @@ async function remind(args) {
3001
5372
  return
3002
5373
  }
3003
5374
  const { buildReminders, toIcs } = await loadRemind()
5375
+ // One prefix query instead of getMeta() per commitment (read-only store safe).
3004
5376
  const snoozed = {}
3005
- for (const c of ledger.listCommitments()) {
3006
- const until = store?.getMeta('snooze:' + c.id)
3007
- if (until) snoozed[c.id] = until
3008
- }
5377
+ for (const [key, value] of store?.listMetaByPrefix('snooze:') ?? []) snoozed[key.slice('snooze:'.length)] = value
3009
5378
  const reminders = buildReminders(ledger, { now: new Date(), snoozedUntil: snoozed })
3010
5379
  if (flags.ics) {
3011
5380
  const path = typeof flags.ics === 'string' ? flags.ics : (positional[0] || join(HOME, 'reminders.ics'))
@@ -3206,12 +5575,23 @@ async function deliver(args) {
3206
5575
  */
3207
5576
  async function mcpServer() {
3208
5577
  ensureHome()
5578
+ // 0.2.3 P0-2 / §4.8: `initialize` is protocol-only. The writable store (writer
5579
+ // lock + audit sink) opens now, but the LEDGER is loaded lazily on the first
5580
+ // tool that needs it, and only the tables that tool reads — so a 200k-row
5581
+ // ledger no longer costs ~2s before the first response. mcp still writes audit
5582
+ // rows, so it keeps the writer lock (0.3 makes it a shared writer).
3209
5583
  const store = dbStore()
3210
- const ledger = loadLedger()
5584
+ const loadLedgerFor = (kind) => {
5585
+ if (mode === 'json') return loadJson()
5586
+ if (!store) return new Ledger(LOCAL_PORTS)
5587
+ if (kind === 'matters') return Ledger.fromParts({ version: 1, matters: store.loadMatters() }, LOCAL_PORTS)
5588
+ if (kind === 'commitments') return Ledger.fromParts({ version: 1, commitments: store.loadCommitments() }, LOCAL_PORTS)
5589
+ return Ledger.fromJSON(store.load(), LOCAL_PORTS)
5590
+ }
3211
5591
  const { createMcpServer } = await loadMcpServer()
3212
5592
  const server = createMcpServer({
3213
5593
  store,
3214
- ledger,
5594
+ loadLedger: loadLedgerFor,
3215
5595
  version: VERSION,
3216
5596
  audit: (entry) => store?.appendAudit(entry),
3217
5597
  })
@@ -3259,12 +5639,17 @@ function vaultPass() {
3259
5639
  }
3260
5640
 
3261
5641
  /**
3262
- * Plaintext database copies left behind by unseal/migrate/import/sync and by an
3263
- * interrupted unseal (robustness audit P1-2). `vault seal --remove` must delete
3264
- * these too, otherwise the CLI says "plaintext removed" while a readable SQLite
3265
- * copy (including the before-unseal backup) is still in HOME.
5642
+ * Plaintext database copies and crash residue left in HOME (robustness audit
5643
+ * P1-2/P1-3). `vault seal --remove`, `vault status` and `doctor --check-db`
5644
+ * must see all of these, otherwise the CLI says "plaintext removed" while a
5645
+ * readable SQLite image is still on disk:
5646
+ * - before-unseal/migrate/sync backups and import backups (0.2.2);
5647
+ * - interrupted sync-pull staging files `.advisers-pull-verify-*` (0.2.3);
5648
+ * - quarantined WAL files `state.db-wal.corrupt-*` (WAL frames are plaintext);
5649
+ * - crash-safe temp files from lib/fs-safe (`.<name>.tmp-*`) and the legacy
5650
+ * pet-brief writer (`.<name>.<pid>.<ts>.tmp`).
3266
5651
  */
3267
- const PLAINTEXT_DB_COPY_RE = /^(?:state\.db\.before-(?:unseal|migrate|sync)-|\.state\.db\.unseal-|import-backup-)/
5652
+ const PLAINTEXT_DB_COPY_RE = /^(?:state\.db\.before-(?:unseal|migrate|sync)-|\.state\.db\.unseal-|import-backup-|\.advisers-pull-verify-|state\.db-wal\.corrupt-|\..*\.tmp-|\..*\.tmp$)/
3268
5653
  function plaintextDbCopies() {
3269
5654
  try {
3270
5655
  return readdirSync(HOME).filter((name) => PLAINTEXT_DB_COPY_RE.test(name)).map((name) => join(HOME, name))
@@ -3273,9 +5658,49 @@ function plaintextDbCopies() {
3273
5658
  }
3274
5659
  }
3275
5660
 
5661
+ /** DB-shaped backup files that doctor --check-db verifies are readable. */
5662
+ const BACKUP_FILE_RE = /^(?:state\.db\.before-(?:unseal|migrate|sync)-|import-backup-.*\.db$)/
5663
+ function newestPlaintextBackup() {
5664
+ try {
5665
+ let newest = null
5666
+ let newestMs = -1
5667
+ for (const name of readdirSync(HOME)) {
5668
+ if (!BACKUP_FILE_RE.test(name)) continue
5669
+ const file = join(HOME, name)
5670
+ try {
5671
+ const info = statSync(file)
5672
+ if (!info.isFile() || info.size === 0) continue
5673
+ if (info.mtimeMs > newestMs) { newest = file; newestMs = info.mtimeMs }
5674
+ } catch {}
5675
+ }
5676
+ return newest
5677
+ } catch {
5678
+ return null
5679
+ }
5680
+ }
5681
+
5682
+ /** `doctor --check-db`: the newest pre-migrate/sync/unseal/import backup must open. */
5683
+ function checkBackupReadable(check) {
5684
+ const backup = newestPlaintextBackup()
5685
+ if (!backup) {
5686
+ check('db-backup', true, 'none found (create one with `advisers backup <path.db>`)')
5687
+ return
5688
+ }
5689
+ let store = null
5690
+ try {
5691
+ store = new SqliteStore(backup, { readOnly: true, checkIntegrity: true })
5692
+ check('db-backup', true, `${basename(backup)} (readable, quick_check ok)`)
5693
+ } catch (error) {
5694
+ check('db-backup', false, `${basename(backup)}: ${String(error?.message ?? error).slice(0, 200)}`)
5695
+ } finally {
5696
+ try { store?.close() } catch {}
5697
+ }
5698
+ }
5699
+
3276
5700
  /**
3277
5701
  * Remove the live plaintext database and every plaintext copy. Failures are
3278
5702
  * collected (never swallowed) so the caller can report them and exit non-zero.
5703
+ * Removal uses the bounded retry helper (Windows AV/OneDrive can hold a file).
3279
5704
  */
3280
5705
  function removePlaintextDatabase() {
3281
5706
  const removed = []
@@ -3283,13 +5708,13 @@ function removePlaintextDatabase() {
3283
5708
  for (const file of [DB, `${DB}-wal`, `${DB}-shm`, ...plaintextDbCopies()]) {
3284
5709
  try {
3285
5710
  if (!existsSync(file)) continue
3286
- rmSync(file)
5711
+ rmWithRetrySync(file)
3287
5712
  removed.push(file)
3288
5713
  } catch (error) {
3289
5714
  failures.push(`${file}: ${error.message}`)
3290
5715
  }
3291
5716
  }
3292
- fsyncDir(HOME)
5717
+ fsyncDirSync(HOME)
3293
5718
  return { removed, failures }
3294
5719
  }
3295
5720
 
@@ -3345,15 +5770,31 @@ async function vaultSeal(args) {
3345
5770
  const sha = createHash('sha256').update(bytes).digest('hex')
3346
5771
  const envelope = encryptJson({ kind: 'advisers-db', version: VERSION, sha256: sha, db: bytes.toString('base64') }, pass)
3347
5772
  const out = typeof flags.out === 'string' ? flags.out : `${DB}.vault`
3348
- atomicWriteFileSync(out, JSON.stringify(envelope) + '\n', { mode: 0o600 })
3349
- const check = decryptJson(JSON.parse(readFileSync(out, 'utf8')), pass)
3350
- if (check.sha256 !== sha) throw new Error('sealed file verification failed')
5773
+ // 0.2.3 Wave 1 (robustness audit P1-2): stage the envelope in a temp file
5774
+ // (short-write loop + fsync + size verification), verify it decrypts back to
5775
+ // the same bytes, and only then commit it with an atomic rename. A short
5776
+ // write/ENOSPC can no longer install a truncated .vault, and any failure
5777
+ // after staging removes the temp file instead of leaving plaintext behind.
5778
+ let tmp = null
5779
+ try {
5780
+ tmp = writeAllToTempSync(out, JSON.stringify(envelope) + '\n', { mode: 0o600 })
5781
+ const check = decryptJson(JSON.parse(readFileSync(tmp, 'utf8')), pass)
5782
+ if (check.sha256 !== sha) throw new Error('sealed file verification failed (the staged copy does not decrypt to the database)')
5783
+ commitTempFileSync(tmp, out, { mode: 0o600 })
5784
+ tmp = null
5785
+ } catch (error) {
5786
+ if (tmp) { try { rmWithRetrySync(tmp) } catch {} }
5787
+ throw error
5788
+ }
3351
5789
  if (removePlaintext) {
3352
5790
  if (!reportPlaintextCleanup(removePlaintextDatabase(), out)) return
3353
5791
  return
3354
5792
  }
3355
5793
  console.log(`sealed ${DB} -> ${out} (plaintext kept; pass --remove)`)
3356
- } catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1 }
5794
+ } catch (error) {
5795
+ console.error(`vault seal failed: ${describeFsError(error, { action: 'sealing the database to', target: typeof flags.out === 'string' ? flags.out : DB + '.vault' })}`)
5796
+ process.exitCode = 1
5797
+ }
3357
5798
  }
3358
5799
 
3359
5800
  async function vaultUnseal(args) {
@@ -3383,7 +5824,9 @@ async function vaultUnseal(args) {
3383
5824
  // database (and its WAL) as a backup, then rename atomically.
3384
5825
  const tmp = join(HOME, `.state.db.unseal-${process.pid}-${randomBytes(4).toString('hex')}`)
3385
5826
  try {
3386
- writeDurableTemp(tmp, bytes)
5827
+ // 0.2.3 Wave 1: durable staged write (short-write loop + fsync + size check)
5828
+ // instead of a one-shot writeSync that ENOSPC can truncate.
5829
+ writeAllToTempSync(DB, bytes, { mode: 0o600, tempPath: tmp })
3387
5830
  let check
3388
5831
  try {
3389
5832
  check = new SqliteStore(tmp, { readOnly: true, checkIntegrity: true })
@@ -3395,20 +5838,26 @@ async function vaultUnseal(args) {
3395
5838
  let backup
3396
5839
  if (existsSync(DB)) {
3397
5840
  backup = `${DB}.before-unseal-${Date.now()}`
3398
- copyFileSync(DB, backup)
5841
+ // The pre-unseal copy is plaintext data: copy with retry, then fsync it so
5842
+ // a crash right after the rename cannot leave a zero-length backup.
5843
+ copyFileWithRetrySync(DB, backup)
5844
+ fsyncFileSync(backup)
3399
5845
  for (const suffix of ['-wal', '-shm']) {
3400
- try { if (existsSync(DB + suffix)) copyFileSync(DB + suffix, backup + suffix) } catch {}
5846
+ try {
5847
+ if (existsSync(DB + suffix)) {
5848
+ copyFileWithRetrySync(DB + suffix, backup + suffix)
5849
+ fsyncFileSync(backup + suffix)
5850
+ }
5851
+ } catch {}
3401
5852
  }
3402
5853
  }
3403
5854
  // A WAL from the old database must never be replayed onto the new file.
3404
- for (const suffix of ['-wal', '-shm']) { try { if (existsSync(DB + suffix)) rmSync(DB + suffix) } catch {} }
3405
- renameSync(tmp, DB)
3406
- try { chmodSync(DB, 0o600) } catch {}
3407
- fsyncDir(HOME)
5855
+ for (const suffix of ['-wal', '-shm']) { try { if (existsSync(DB + suffix)) rmWithRetrySync(DB + suffix) } catch {} }
5856
+ commitTempFileSync(tmp, DB, { mode: 0o600 })
3408
5857
  console.log(`unsealed ${file} -> ${DB} (${bytes.length} bytes, integrity ok${backup ? `; previous database kept at ${backup}` : ''})`)
3409
5858
  } catch (error) {
3410
- try { if (existsSync(tmp)) rmSync(tmp) } catch {}
3411
- console.error(`vault unseal failed: ${error.message}`)
5859
+ try { rmWithRetrySync(tmp) } catch {}
5860
+ console.error(`vault unseal failed: ${describeFsError(error, { action: 'installing the unsealed database', target: DB })}`)
3412
5861
  console.error(`The sealed file ${file} is intact (${bytes.length} bytes of plaintext); the existing database was not replaced.`)
3413
5862
  console.error('Fix the disk/permissions problem and retry `advisers vault unseal`.')
3414
5863
  process.exitCode = 1
@@ -3422,7 +5871,10 @@ function vaultStatus() {
3422
5871
  console.log(`sealed: ${existsSync(sealed) ? sealed : 'none'}`)
3423
5872
  console.log(`state: ${existsSync(DB) ? 'plaintext at rest' : existsSync(sealed) ? 'encrypted at rest (run vault unseal)' : 'empty'}`)
3424
5873
  const copies = plaintextDbCopies()
3425
- if (copies.length) console.log(`plaintext copies: ${copies.length} (run \`advisers vault seal --remove\` to purge them)`)
5874
+ if (copies.length) {
5875
+ console.log(`plaintext copies: ${copies.length} (run \`advisers vault seal --remove\` to purge them)`)
5876
+ for (const copy of copies) console.log(` ${copy}`)
5877
+ }
3426
5878
  }
3427
5879
 
3428
5880
  async function timestampCommand(args) {
@@ -3444,8 +5896,9 @@ async function tui(args) {
3444
5896
  const once = args.includes('--once')
3445
5897
  const { buildReminders } = await loadRemind()
3446
5898
  const render = () => {
3447
- const ledger = loadLedger()
3448
- const store = dbStore()
5899
+ // 0.2.3 §4.8: no writer lock; each refresh reads the current committed snapshot.
5900
+ const ledger = loadReadLedger({ commitments: {} })
5901
+ const store = readStoreOrExit()
3449
5902
  const open = ledger.openCommitments()
3450
5903
  const localDay = localDayOf(Date.now())
3451
5904
  const due = open.filter((c) => c.dueAt && c.dueAt.slice(0, 10) <= localDay)
@@ -3530,6 +5983,33 @@ function checkpointLocalDatabase() {
3530
5983
  }
3531
5984
  }
3532
5985
 
5986
+ /**
5987
+ * 0.2.3 Wave 1 (robustness audit P1-1): explain exactly which sync-pull decision
5988
+ * the library made. The old output only said "pulled", so a new-device bootstrap
5989
+ * and a --force overwrite of a newer local ledger looked identical.
5990
+ */
5991
+ function reportSyncPullResult(result) {
5992
+ const snapshotLabel = `${result.file}${result.createdAt ? ` (created ${result.createdAt}${result.device ? `, device ${result.device}` : ''})` : ''}`
5993
+ const backupNote = result.backup ? `; previous database backed up to ${result.backup}` : ''
5994
+ if (!result.changed || result.status === 'unchanged') {
5995
+ console.log(`unchanged: the local database already matches the selected snapshot ${result.file}`)
5996
+ return
5997
+ }
5998
+ if (result.status === 'bootstrapped') {
5999
+ console.log(`pulled (bootstrapped): this device had no local ledger data; installed snapshot ${snapshotLabel}${result.replacedLocalEmpty ? ' over an empty schema-only database (no user rows were lost)' : ''}${result.sameDevice ? '; the snapshot was pushed from this device' : ''}${backupNote}`)
6000
+ return
6001
+ }
6002
+ if (result.status === 'forced') {
6003
+ console.log(`pulled (forced): --force replaced the local database with snapshot ${snapshotLabel}${backupNote}`)
6004
+ if (result.snapshotOlder) {
6005
+ console.error('warning: the installed snapshot is OLDER than the local database; local writes after the snapshot exist only in the backup (export them before continuing if they matter)')
6006
+ }
6007
+ return
6008
+ }
6009
+ console.log(`pulled: installed snapshot ${snapshotLabel}${result.sameDevice ? '; pushed from this device' : ''}${backupNote}`)
6010
+ if (result.snapshotOlder) console.error('warning: the installed snapshot is older than the local database; the previous database is in the backup')
6011
+ }
6012
+
3533
6013
  async function syncCommand(args) {
3534
6014
  const { flags, positional } = parseFlags(args)
3535
6015
  const sub = positional[0]
@@ -3572,6 +6052,7 @@ async function syncCommand(args) {
3572
6052
  } catch (error) { console.error(`sync push failed: ${error.message}`); process.exitCode = 1 }
3573
6053
  } else if (sub === 'pull') {
3574
6054
  const force = Boolean(flags.force)
6055
+ const { pullSnapshot, cleanupStalePullTemps } = await loadSync()
3575
6056
  try {
3576
6057
  // Capture the local write time before checkpointing (checkpoint touches mtime).
3577
6058
  const localMtimeMs = latestLocalDbMtime()
@@ -3580,7 +6061,6 @@ async function syncCommand(args) {
3580
6061
  if (checkpoint.busy && !force) throw new Error('local database is busy (another advisers process is writing); close it and retry sync pull, or re-run with --force (a backup is kept)')
3581
6062
  if (!checkpoint.busy && checkpoint.error) console.error(`note: local database could not be checkpointed (${checkpoint.error.message}); the snapshot replaces it and a backup is kept.`)
3582
6063
  }
3583
- const { pullSnapshot } = await loadSync()
3584
6064
  const result = pullSnapshot({
3585
6065
  dir,
3586
6066
  dbPath: DB,
@@ -3590,13 +6070,24 @@ async function syncCommand(args) {
3590
6070
  localMtimeMs,
3591
6071
  localDevice: await readSyncDevice(),
3592
6072
  })
3593
- if (!result.changed) console.log('local database already matches the latest snapshot')
3594
- else console.log(`pulled ${result.file} (${result.sha256})${result.backup ? `; backup ${result.backup}` : ''}`)
6073
+ // 0.2.3 Wave 1: distinguish bootstrapped / forced / plain pull / unchanged.
6074
+ reportSyncPullResult(result)
3595
6075
  if (result.changed) {
3596
6076
  try { dbStore()?.appendAudit({ actor: 'local', action: 'sync.pull', allowed: true, reason: result.file }) }
3597
6077
  catch (error) { console.error(`warning: database replaced but the sync.pull audit row failed: ${error.message}`); process.exitCode = 1 }
3598
6078
  }
3599
- } catch (error) { console.error(`sync pull failed: ${error.message}`); process.exitCode = 1 }
6079
+ } catch (error) {
6080
+ // Failure cleanup: the library removes its own staged temp file, but a
6081
+ // previously crashed pull may have left stale plaintext staging files.
6082
+ // Only stale files whose pid is gone are removed (never a live pull).
6083
+ try {
6084
+ const swept = cleanupStalePullTemps(HOME)
6085
+ if (swept.removed.length) console.error(`note: removed ${swept.removed.length} stale sync-pull temp file(s)`)
6086
+ if (swept.errors.length) console.error(`warning: could not clean sync-pull temp file(s): ${swept.errors.slice(0, 2).join(' | ')}`)
6087
+ } catch {}
6088
+ console.error(`sync pull failed: ${error.message}`)
6089
+ process.exitCode = 1
6090
+ }
3600
6091
  } else { console.error('usage: advisers sync push|pull|status --dir <sync-dir>'); process.exitCode = 1 }
3601
6092
  }
3602
6093
 
@@ -3626,10 +6117,12 @@ async function printEvidence(args) {
3626
6117
  return
3627
6118
  }
3628
6119
  ensureHome()
3629
- const store = dbStore()
3630
- const ledger = loadLedger()
6120
+ // 0.2.3 §4.3: evidence show is a pure read. The lock-free store supplies the
6121
+ // turn lookup and only the one ledger table the id prefix needs is loaded.
6122
+ const store = mode === 'sqlite' ? readStoreOrExit() : null
3631
6123
  const id = positional[1] || positional[0]
3632
6124
  if (!id) { console.error('usage: advisers evidence show <id> [--json]'); process.exitCode = 1; return }
6125
+ const ledger = readLedgerForCommand(id.startsWith('fact_') ? { facts: {} } : id.startsWith('pref_') ? { preferences: {} } : { commitments: {} })
3633
6126
  let result
3634
6127
  try {
3635
6128
  const { evidenceForCommitment, evidenceForFact, evidenceForPreference } = await loadEvidence()
@@ -3640,12 +6133,22 @@ async function printEvidence(args) {
3640
6133
  } catch (error) { console.error(error.message); process.exitCode = 1; return }
3641
6134
  if (!result || (!result.commitment && !result.fact && !result.preference)) { console.error(`not found: ${id}`); process.exitCode = 1; return }
3642
6135
  await normalizeEvidenceSources(result)
3643
- if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
6136
+ const unverifiable = Array.isArray(result.unverifiable) ? result.unverifiable : []
6137
+ const manualSources = unverifiable.filter((item) => item && (item.kind === 'manual' || item.type === 'manual'))
6138
+ const summary = {
6139
+ byKind: { observed: result.sources.length, manual: manualSources.length },
6140
+ missing: result.missing.length,
6141
+ unverifiable: unverifiable.length,
6142
+ operatorEntered: manualSources.length,
6143
+ }
6144
+ if (flags.json) { console.log(JSON.stringify(Object.assign({}, result, { summary: summary }), null, 2)); return }
3644
6145
  const label = result.commitment ? `${result.commitment.action}` : result.fact ? `${result.fact.subject} ${result.fact.predicate}` : result.preference?.statement
3645
6146
  console.log(`${id} ${label ?? ''}`)
3646
- if (!result.sources.length) console.log(' (没有可回溯来源)')
6147
+ if (!result.sources.length && !unverifiable.length) console.log(' (没有可回溯来源)')
3647
6148
  for (const s of result.sources) console.log(` ${s.sessionId}#${s.turnId} 「${(s.quote ?? '').slice(0, 120)}」`)
3648
6149
  for (const m of result.missing) console.log(` MISSING ${m.reason}${m.ref ? ` ${m.ref}` : ''}`)
6150
+ for (const item of unverifiable) console.log(` MANUAL 操作者录入(未外部核验,不是缺失) 「${(item.quote ?? '').slice(0, 120)}」 sha256:${String(item.quoteSha256 ?? '').slice(0, 16)}`)
6151
+ if (unverifiable.length) console.log(' 说明:manual/operator-entered 证据由用户手工录入;本地无法外部核验,不计入 missing。')
3649
6152
  }
3650
6153
 
3651
6154
  async function evidencePack(args) {
@@ -4418,6 +6921,7 @@ const KNOWN_COMMANDS = new Set([
4418
6921
  'who', 'memory', 'digest', 'week', 'prefs', 'privacy', 'audit', 'purge', 'decay', 'correct', 'ls', 'why',
4419
6922
  'forget', 'sync', 'vault', 'export', 'import', 'backup', 'brief', 'review', 'research', 'capture', 'policy',
4420
6923
  'office-edit', 'office-read', 'verify', 'office', 'routine', 'template', 'link', 'bridge', 'soul', 'tos',
6924
+ 'matter', 'agenda', 'morning',
4421
6925
  ])
4422
6926
 
4423
6927
  /** Append a TOS audit row; audit is best-effort (JSON store has no audit chain). */
@@ -4697,7 +7201,7 @@ if (!command) {
4697
7201
  } else if (command === 'status') {
4698
7202
  printStatus(args.includes('--json'))
4699
7203
  } else if (command === 'doctor') {
4700
- await doctor()
7204
+ await doctor(args)
4701
7205
  } else if (command === 'init') {
4702
7206
  init()
4703
7207
  } else if (command === 'history') {
@@ -4720,68 +7224,95 @@ if (!command) {
4720
7224
  } else if (command === 'deliveries') {
4721
7225
  if (args.includes('--receipt')) await receiptPack(args)
4722
7226
  else if (args.includes('--pack')) await evidencePack(args)
4723
- else if (args.includes('--json')) console.log(JSON.stringify(dbStore()?.listDeliveries(100) ?? [], null, 2))
7227
+ else if (args.includes('--json')) console.log(JSON.stringify(readStoreOrExit()?.listDeliveries(100) ?? [], null, 2))
4724
7228
  else printDeliveries()
4725
7229
  } else if (command === 'learn') {
4726
7230
  const sub = args[0]
4727
- const store = dbStore()
4728
- let learnDenied = null
4729
- if (sub === 'review') {
4730
- const learnLedger = loadLedger()
4731
- learnDenied = egressDeniedReason(learnLedger.getMatter(activeMatterId(learnLedger)), 'learn review')
4732
- }
4733
- if (sub === 'review' && learnDenied) { console.error(learnDenied); process.exitCode = 1 }
4734
- else if (sub === 'ls') {
4735
- for (const r of store?.listTaskRuns(20) ?? []) console.log(`${r.id}\t${r.outcome}\t${r.tools.map((t) => t.name).join(',')}\t${r.task.slice(0, 60)}`)
7231
+ if (sub === 'ls') {
7232
+ // 0.2.3: read-only task-run list, lock-free.
7233
+ for (const r of readStoreOrExit()?.listTaskRuns(20) ?? []) console.log(`${r.id}\t${r.outcome}\t${r.tools.map((t) => t.name).join(',')}\t${r.task.slice(0, 60)}`)
4736
7234
  } else if (sub === 'review') {
4737
- const run = store?.listTaskRuns(100).find((r) => r.id === args[1])
4738
- const apiKey = process.env.ADVISERS_API_KEY
4739
- if (!run || !apiKey) { console.error('usage: ADVISERS_API_KEY=... advisers learn review <run-id>'); process.exitCode = 1 }
7235
+ const learnLedger = loadLedger()
7236
+ const learnDenied = egressDeniedReason(learnLedger.getMatter(activeMatterId(learnLedger)), 'learn review')
7237
+ if (learnDenied) { console.error(learnDenied); process.exitCode = 1 }
4740
7238
  else {
4741
- const ledger = loadLedger()
4742
- const { reviewRun, lintReview, materializeReview } = await loadReview()
4743
- const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
4744
- const checked = lintReview(review, { run, routines: ledger.listRoutines() })
4745
- if (!checked.ok) { console.error(`review rejected: ${checked.error}`); process.exitCode = 1 }
7239
+ const store = dbStore()
7240
+ const run = store?.listTaskRuns(100).find((r) => r.id === args[1])
7241
+ const apiKey = process.env.ADVISERS_API_KEY
7242
+ if (!run || !apiKey) { console.error('usage: ADVISERS_API_KEY=... advisers learn review <run-id>'); process.exitCode = 1 }
4746
7243
  else {
4747
- const made = materializeReview(checked.review, { run, ledger })
4748
- saveLedger(ledger)
4749
- console.log(`verdict: ${made.verdict}${made.routine ? ` draft ${made.routine.id}` : made.patch ? ` patch ${made.patch.id}` : ''}`)
7244
+ const ledger = loadLedger()
7245
+ const { reviewRun, lintReview, materializeReview } = await loadReview()
7246
+ const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
7247
+ const checked = lintReview(review, { run, routines: ledger.listRoutines() })
7248
+ if (!checked.ok) { console.error(`review rejected: ${checked.error}`); process.exitCode = 1 }
7249
+ else {
7250
+ const made = materializeReview(checked.review, { run, ledger })
7251
+ saveLedger(ledger)
7252
+ console.log(`verdict: ${made.verdict}${made.routine ? ` draft ${made.routine.id}` : made.patch ? ` patch ${made.patch.id}` : ''}`)
7253
+ }
4750
7254
  }
4751
7255
  }
4752
7256
  } else { console.error('usage: advisers learn ls|review <run-id>'); process.exitCode = 1 }
4753
7257
  } else if (command === 'commit') {
7258
+ // 0.2.3 persistence v2 §3.3.1-§3.3.4: every commit write is one directed
7259
+ // INSERT/UPDATE + meta upsert + exactly one audit row inside a single
7260
+ // BEGIN IMMEDIATE (mutateWithAudit). Validation and file checks stay outside
7261
+ // the transaction; JSON-store mode keeps the legacy in-memory path.
4754
7262
  const sub = args[0]
4755
- const ledger = loadLedger()
4756
7263
  const { flags, positional } = parseFlags(args.slice(1))
4757
7264
  if (sub === 'add') {
7265
+ const usage = 'usage: advisers commit add "<action>" --quote "<原话>" [--due ISO] [--debtor user|agent] [--creditor name] [--matter id] [--remind-offsets "-1d,-2h"]'
4758
7266
  const action = positional.join(' ').trim()
4759
- if (!action || !flags.quote) { console.error('usage: advisers commit add "<action>" --quote "<原话>" [--due ISO] [--debtor user|agent] [--creditor name] [--matter id] [--remind-offsets "-1d,-2h"]'); process.exitCode = 1 }
7267
+ if (!action || !flags.quote) { console.error(usage); process.exitCode = 1 }
4760
7268
  else {
4761
7269
  let reminderOffsets
4762
7270
  let offsetsError
4763
7271
  try { reminderOffsets = await parseReminderOffsetsFlag(flags) } catch (error) { offsetsError = error }
4764
7272
  if (offsetsError) { console.error(offsetsError.message); process.exitCode = 1 }
4765
- else {
4766
- const c = ledger.addCommitment({
4767
- matterId: activeMatterId(ledger, flags.matter),
4768
- debtor: flags.debtor ?? 'user',
4769
- creditor: flags.creditor ?? /(?:发给|给|向|对)([\u4e00-\u9fa5A-Za-z0-9_]{1,12})/.exec(action)?.[1] ?? 'someone',
4770
- action,
4771
- dueAt: flags.due,
4772
- timezone: flags.tz ?? 'Asia/Shanghai',
4773
- capability: flags.capability ?? 'todo',
4774
- evidence: [{ sessionId: latestConversationId(), turnId: 'cli', quote: String(flags.quote) }],
4775
- ...(reminderOffsets !== undefined ? { reminderOffsets } : {}),
4776
- })
4777
- saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.add', allowed: true, reason: c.id })
4778
- console.log(`${c.id} open ${c.action}${c.dueAt ? ` due ${c.dueAt}` : ''}`)
4779
- if (reminderOffsets !== undefined) console.log('reminder-offsets: ' + JSON.stringify(reminderOffsets))
7273
+ else if (mode === 'json') {
7274
+ try {
7275
+ const ledger = loadJson()
7276
+ const c = ledger.addCommitment({
7277
+ matterId: resolveMatterForCommand(ledger, flags.matter, 'commit add'),
7278
+ debtor: flags.debtor ?? 'user',
7279
+ creditor: flags.creditor ?? /(?:发给|给|向|对)([\u4e00-\u9fa5A-Za-z0-9_]{1,12})/.exec(action)?.[1] ?? 'someone',
7280
+ action,
7281
+ dueAt: flags.due,
7282
+ timezone: flags.tz ?? 'Asia/Shanghai',
7283
+ capability: flags.capability ?? 'todo',
7284
+ evidence: [manualEvidence(String(flags.quote), 'commit add')],
7285
+ ...(reminderOffsets !== undefined ? { reminderOffsets } : {}),
7286
+ })
7287
+ saveJson(ledger)
7288
+ printCommitAdded(c, reminderOffsets)
7289
+ } catch (error) { reportCommandFailure(error) }
7290
+ } else {
7291
+ const audit = { actor: 'local', action: 'commit.add', allowed: true, reason: '' }
7292
+ try {
7293
+ const { result: c } = mutateWithAudit((store) => {
7294
+ const commitment = core.createCommitment({ clock: LOCAL_PORTS.clock, ids: LOCAL_PORTS.ids }, {
7295
+ matterId: resolveWriteMatterId(store, flags.matter),
7296
+ debtor: flags.debtor ?? 'user',
7297
+ creditor: flags.creditor ?? /(?:发给|给|向|对)([\u4e00-\u9fa5A-Za-z0-9_]{1,12})/.exec(action)?.[1] ?? 'someone',
7298
+ action,
7299
+ dueAt: flags.due,
7300
+ timezone: flags.tz ?? 'Asia/Shanghai',
7301
+ capability: flags.capability ?? 'todo',
7302
+ evidence: [manualEvidence(String(flags.quote), 'commit add')],
7303
+ ...(reminderOffsets !== undefined ? { reminderOffsets } : {}),
7304
+ })
7305
+ store.insertCommitment(commitment)
7306
+ audit.reason = commitment.id
7307
+ return commitment
7308
+ }, audit)
7309
+ printCommitAdded(c, reminderOffsets)
7310
+ } catch (error) { reportCommandFailure(error) }
4780
7311
  }
4781
7312
  }
4782
7313
  } else if (sub === 'edit' || sub === 'update') {
4783
7314
  const id = positional[0]
4784
- const usage = 'usage: advisers commit edit <id> [--action text] [--due ISO] [--remind-offsets "<list>" | --no-remind]'
7315
+ const usage = 'usage: advisers commit edit <id> [--action text] [--due ISO] [--matter id] [--remind-offsets "<list>" | --no-remind]'
4785
7316
  if (!id) { console.error(usage); process.exitCode = 1 }
4786
7317
  else {
4787
7318
  const patch = {}
@@ -4789,6 +7320,7 @@ if (!command) {
4789
7320
  if (typeof flags.due === 'string') patch.dueAt = flags.due
4790
7321
  if (typeof flags.tz === 'string') patch.timezone = flags.tz
4791
7322
  if (typeof flags.capability === 'string') patch.capability = flags.capability
7323
+ if (typeof flags.matter === 'string') patch.matterId = flags.matter
4792
7324
  let offsetsError
4793
7325
  try {
4794
7326
  if (flags['no-remind'] === true) patch.reminderOffsets = null
@@ -4801,38 +7333,89 @@ if (!command) {
4801
7333
  else if (!Object.keys(patch).length) { console.error(usage); process.exitCode = 1 }
4802
7334
  else {
4803
7335
  try {
4804
- const c = ledger.updateCommitment(id, patch)
4805
- saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.update', allowed: true, reason: id })
4806
- console.log(`updated: ${c.id}`)
4807
- if ('reminderOffsets' in patch) console.log('reminder-offsets: ' + JSON.stringify(c.reminderOffsets ?? []))
4808
- if (patch.dueAt !== undefined) console.log('due: ' + (c.dueAt ?? '未定'))
4809
- } catch (error) { console.error(error.message); process.exitCode = 1 }
7336
+ if (mode === 'json') {
7337
+ try {
7338
+ const ledger = loadJson()
7339
+ if (typeof patch.matterId === 'string') {
7340
+ const matter = ledger.getMatter(patch.matterId)
7341
+ if (!matter) throw matterCommandError('E_MATTER_NOT_FOUND', 'unknown matter: ' + patch.matterId, 'advisers matter ls')
7342
+ if (matter.status !== 'active') throw matterCommandError('E_MATTER_ARCHIVED', 'matter is archived: ' + patch.matterId, 'advisers matter ls')
7343
+ const current = ledger.listCommitments().find((row) => row.id === id)
7344
+ if (!current) throw new Error('unknown commitment: ' + id)
7345
+ current.matterId = patch.matterId
7346
+ }
7347
+ const c = ledger.updateCommitment(id, patch)
7348
+ saveJson(ledger)
7349
+ printCommitUpdated(c, patch)
7350
+ } catch (error) { reportCommandFailure(error) }
7351
+ } else {
7352
+ const audit = { actor: 'local', action: 'commit.update', allowed: true, reason: id }
7353
+ const { result: c } = mutateWithAudit((store) => {
7354
+ const current = store.getCommitment(id)
7355
+ if (!current) throw new Error(`unknown commitment: ${id}`)
7356
+ const effectivePatch = { ...patch }
7357
+ if (typeof effectivePatch.matterId === 'string') effectivePatch.matterId = resolveWriteMatterId(store, effectivePatch.matterId)
7358
+ const next = core.updateCommitmentFields(current, effectivePatch)
7359
+ if (effectivePatch.matterId) next.matterId = effectivePatch.matterId
7360
+ store.updateCommitment(id, effectivePatch)
7361
+ return next
7362
+ }, audit)
7363
+ printCommitUpdated(c, patch)
7364
+ }
7365
+ } catch (error) { reportCommandFailure(error) }
4810
7366
  }
4811
7367
  }
4812
- } else if (sub === 'ls') printCommitments(ledger, flags.json)
4813
- else if (sub === 'snooze') {
7368
+ } else if (sub === 'ls') {
7369
+ if (mode === 'json') printCommitments(loadJson(), flags.json)
7370
+ else printCommitments(loadReadLedger({ commitments: {} }), flags.json)
7371
+ } else if (sub === 'snooze') {
4814
7372
  const id = positional[0]
4815
7373
  const hours = Number(positional[1] ?? 24)
4816
- const c = ledger.listCommitments().find((x) => x.id === id)
4817
- if (!c || !Number.isFinite(hours) || hours <= 0) { console.error('usage: advisers commit snooze <id> <hours>'); process.exitCode = 1 }
4818
- else {
4819
- c.status = 'snoozed'
4820
- saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.snooze', allowed: true, reason: id }, (store) => store.setMeta(`snooze:${id}`, new Date(Date.now() + hours * 3600_000).toISOString()))
4821
- console.log(`snoozed: ${id} for ${hours}h`)
7374
+ const usage = 'usage: advisers commit snooze <id> <hours>'
7375
+ if (!id || !Number.isFinite(hours) || hours <= 0) { console.error(usage); process.exitCode = 1 }
7376
+ else if (mode === 'json') {
7377
+ const ledger = loadJson()
7378
+ const c = ledger.listCommitments().find((x) => x.id === id)
7379
+ if (!c) { console.error(usage); process.exitCode = 1 }
7380
+ else { c.status = 'snoozed'; saveJson(ledger); console.log(`snoozed: ${id} for ${hours}h`) }
7381
+ } else {
7382
+ try {
7383
+ if (!dbStore().getCommitment(id)) { console.error(usage); process.exitCode = 1 }
7384
+ else {
7385
+ const audit = { actor: 'local', action: 'commit.snooze', allowed: true, reason: id }
7386
+ mutateWithAudit((store) => {
7387
+ store.updateCommitment(id, { status: 'snoozed' })
7388
+ store.setMeta(`snooze:${id}`, new Date(Date.now() + hours * 3600_000).toISOString())
7389
+ }, audit)
7390
+ console.log(`snoozed: ${id} for ${hours}h`)
7391
+ }
7392
+ } catch (error) { reportCommandFailure(error) }
4822
7393
  }
4823
7394
  }
4824
7395
  else if (sub === 'done') {
4825
7396
  const id = positional[0]
4826
7397
  const evidence = flags.evidence
4827
7398
  if (!id || !evidence) { console.error('usage: advisers commit done <id> --evidence "<证据/原话>"'); process.exitCode = 1 }
4828
- else {
4829
- if (String(evidence).startsWith('file:') && !existsSync(String(evidence).slice(5))) {
4830
- console.error(`evidence file not found: ${String(evidence).slice(5)}`); process.exitCode = 1
4831
- } else {
4832
- ledger.completeCommitment(id, [{ sessionId: latestConversationId(), turnId: 'cli', quote: String(evidence) }])
4833
- saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.done', allowed: true, reason: id })
7399
+ else if (String(evidence).startsWith('file:') && !existsSync(String(evidence).slice(5))) {
7400
+ console.error(`evidence file not found: ${String(evidence).slice(5)}`); process.exitCode = 1
7401
+ } else if (mode === 'json') {
7402
+ const ledger = loadJson()
7403
+ try {
7404
+ ledger.completeCommitment(id, [manualEvidence(String(evidence), 'commit done')])
7405
+ saveJson(ledger)
4834
7406
  console.log(`done: ${id}`)
4835
- }
7407
+ } catch (error) { console.error(error.message); process.exitCode = 1 }
7408
+ } else {
7409
+ const audit = { actor: 'local', action: 'commit.done', allowed: true, reason: id }
7410
+ try {
7411
+ mutateWithAudit((store) => {
7412
+ const current = store.getCommitment(id)
7413
+ if (!current) throw new Error(`unknown commitment: ${id}`)
7414
+ const next = core.completeCommitment(current, [manualEvidence(String(evidence), 'commit done')], now())
7415
+ store.updateCommitment(id, { status: next.status, doneAt: next.doneAt, evidence: next.evidence })
7416
+ }, audit)
7417
+ console.log(`done: ${id}`)
7418
+ } catch (error) { reportCommandFailure(error) }
4836
7419
  }
4837
7420
  } else { console.error('usage: advisers commit add|edit|ls|done|snooze'); process.exitCode = 1 }
4838
7421
  } else if (command === 'diff') {
@@ -4850,11 +7433,14 @@ if (!command) {
4850
7433
  if (!result.ok) process.exitCode = 1
4851
7434
  }
4852
7435
  } else if (command === 'compact') {
4853
- const store = dbStore()
4854
- const conversationId = latestConversationId()
4855
7436
  if (args[0] === 'ls') {
7437
+ // 0.2.3: version listing is a pure read (lock-free).
7438
+ const store = readStoreOrExit()
7439
+ const conversationId = store?.listSessions(1)?.[0]?.conversationId ?? 'local'
4856
7440
  for (const v of store?.listSummaryVersions(conversationId) ?? []) console.log(`${v.version}\t${v.throughSeq}\t${v.summary.slice(0, 100)}`)
4857
7441
  } else if (args[0] === 'rollback') {
7442
+ const store = dbStore()
7443
+ const conversationId = latestConversationId()
4858
7444
  const version = Number(args[1])
4859
7445
  const old = store?.listSummaryVersions(conversationId).find((v) => v.version === version)
4860
7446
  if (!old) { console.error('usage: advisers compact rollback <version>'); process.exitCode = 1 }
@@ -4864,30 +7450,41 @@ if (!command) {
4864
7450
  const q = args.join(' ').trim()
4865
7451
  if (!q) { console.error('usage: advisers search <text>'); process.exitCode = 1 }
4866
7452
  else {
4867
- const rows = dbStore()?.searchTurns(q, { limit: 10 }) ?? []
7453
+ // 0.2.3: turn search is a pure read (lock-free; reads the WAL snapshot).
7454
+ const rows = readStoreOrExit()?.searchTurns(q, { limit: 10 }) ?? []
4868
7455
  if (!rows.length) console.log('没有匹配')
4869
7456
  for (const r of rows) console.log(`${r.seq}\t${r.role}\t${r.content.replace(/\s+/g, ' ').slice(0, 160)}`)
4870
7457
  }
4871
7458
  } else if (command === 'nudge') {
4872
7459
  const sub = args[0]
4873
- const store = dbStore()
4874
7460
  if (sub === 'list') {
4875
- for (const n of store?.listNudges(50) ?? []) console.log(`${n.id}\t${n.local_day}\t${n.level}\t${n.outcome}\t${n.body}`)
7461
+ for (const n of readStoreOrExit()?.listNudges(50) ?? []) console.log(`${n.id}\t${n.local_day}\t${n.level}\t${n.outcome}\t${n.body}`)
4876
7462
  } else if (sub === 'done' || sub === 'ignore') {
4877
7463
  const id = args[1]
7464
+ const store = dbStore()
4878
7465
  if (!id || !store?.setNudgeOutcome(id, sub === 'done' ? 'accepted' : 'ignored')) { console.error('usage: advisers nudge done|ignore <nudge-id>'); process.exitCode = 1 }
4879
7466
  else console.log(`${sub}: ${id}`)
4880
7467
  } else { console.error('usage: advisers nudge list|done|ignore'); process.exitCode = 1 }
4881
7468
  } else if (command === 'risks') {
4882
- risks(loadLedger({ commitments: { status: 'open' } }))
7469
+ risks(readLedgerForCommand({ commitments: { status: 'open' } }))
4883
7470
  } else if (command === 'pet-brief') {
4884
7471
  await petBrief(args)
4885
7472
  } else if (command === 'today') {
4886
7473
  // P1-2 (0.2.2): today only reads open commitments; --sources reports source
4887
- // rows for every commitment, so that flag keeps the wider load.
7474
+ // rows for every commitment, so that flag keeps the wider load. 0.2.3 reads
7475
+ // it through the lock-free store.
4888
7476
  const sources = args.includes('--sources')
4889
- await today(loadLedger({ commitments: sources ? {} : { status: 'open' } }), { calendar: args.includes('--calendar'), sources, json: args.includes('--json') })
7477
+ const asJson = args.includes('--json')
7478
+ if (asJson || sources) {
7479
+ // The JSON contract and --sources need full commitment entities (evidence).
7480
+ const ledger = readLedgerForCommand({ commitments: sources ? {} : { status: 'open' } })
7481
+ await today(ledger.openCommitments(), { calendar: args.includes('--calendar'), sources, json: asJson, ledger })
7482
+ } else {
7483
+ // Human view: six columns + the cached classification (0.2.3 hot path).
7484
+ await today(loadOpenCommitmentRowsForToday(), { calendar: args.includes('--calendar') })
7485
+ }
4890
7486
  } else if (command === 'tick') {
7487
+ // tick is a WRITER (nudges + snooze wake-ups) but only needs commitments.
4891
7488
  tick(loadLedger({ commitments: {} }), args.includes('--json'))
4892
7489
  } else if (command === 'ui') {
4893
7490
  await ui(args)
@@ -4896,7 +7493,7 @@ if (!command) {
4896
7493
  } else if (command === 'calendar') {
4897
7494
  await calendarImport(args.slice(1))
4898
7495
  } else if (command === 'who') {
4899
- const open = loadLedger({ commitments: { status: 'open' } }).openCommitments()
7496
+ const open = readLedgerForCommand({ commitments: { status: 'open' } }).openCommitments()
4900
7497
  const mine = open.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
4901
7498
  const waiting = open.filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:'))
4902
7499
  if (args.includes('--json')) { console.log(JSON.stringify({ mine, waiting }, null, 2)); }
@@ -4907,66 +7504,111 @@ if (!command) {
4907
7504
  for (const c of waiting) console.log(` ${c.id} ${c.debtor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
4908
7505
  }
4909
7506
  } else if (command === 'memory') {
4910
- const ledger = loadLedger()
4911
- if (args[0] === 'candidates') {
4912
- const rows = dbStore()?.listCandidates(args.includes('--all') ? 'all' : 'pending') ?? []
7507
+ // 0.2.3: candidates/search printMemory are pure reads (lock-free, partial);
7508
+ // accept is the most involved directed write (§3.3.9) — candidate status,
7509
+ // entity row and audit all commit or roll back together.
7510
+ const sub = args[0]
7511
+ const sourceRef = (e) => ({ ...(e.sessionId ? { quote: e.quote, ref: `${e.sessionId}#${e.turnId}` } : { quote: e.quote, ref: e.turnId ? `legacy#${e.turnId}` : undefined }), ...(e.source ? { source: e.source } : {}) })
7512
+ if (sub === 'candidates') {
7513
+ const store = readStoreOrExit()
7514
+ const rows = store?.listCandidates(args.includes('--all') ? 'all' : 'pending') ?? []
4913
7515
  if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2))
4914
7516
  else {
4915
7517
  if (!rows.length) console.log('(没有待确认记忆)')
4916
7518
  for (const c of rows) console.log(`${c.id}\t${c.kind}\t${JSON.stringify(c.payload)}\t${c.status}`)
4917
7519
  }
4918
- } else if (args[0] === 'accept') {
4919
- const store = dbStore()
4920
- const candidate = store?.getCandidate(args[1])
4921
- if (!candidate) { console.error('candidate not found'); process.exitCode = 1 }
4922
- else {
4923
- try {
4924
- const sourceRef = (e) => ({ ...(e.sessionId ? { quote: e.quote, ref: `${e.sessionId}#${e.turnId}` } : { quote: e.quote, ref: e.turnId ? `legacy#${e.turnId}` : undefined }), ...(e.source ? { source: e.source } : {}) })
4925
- const commitmentEvidence = (e) => {
4926
- if (!e.sessionId) return { quote: e.quote, turnId: e.turnId, sessionId: 'legacy', ...(e.source ? { source: e.source } : {}) }
4927
- const turn = store.getTurn(e.turnId)
4928
- if (!turn || turn.conversationId !== e.sessionId) throw new Error(`evidence turn not found: ${e.turnId}`)
4929
- return { quote: e.quote, turnId: e.turnId, sessionId: e.sessionId, ...(e.source ? { source: e.source } : {}) }
4930
- }
4931
- if (candidate.kind === 'fact') ledger.remember({ ...candidate.payload, authority: 'user', evidence: candidate.evidence.map(sourceRef) })
4932
- else if (candidate.kind === 'preference') ledger.addPreference({ ...candidate.payload, evidence: candidate.evidence.map(sourceRef) })
4933
- else if (candidate.kind === 'commitment') ledger.addCommitment({ ...candidate.payload, matterId: candidate.payload.matterId ?? ledger.listMatters()[0]?.id, evidence: candidate.evidence.map(commitmentEvidence) })
4934
- saveLedgerWithAudit(ledger, { actor: 'local', action: 'memory.accept', allowed: true, reason: candidate.id }, (s) => s.reviewCandidate(candidate.id, 'accepted'))
4935
- console.log(`accepted ${candidate.id}`)
4936
- } catch (error) { console.error(error.message); process.exitCode = 1 }
7520
+ } else if (sub === 'accept') {
7521
+ if (mode === 'json') {
7522
+ // The legacy JSON store has no candidate table (same as 0.2.2).
7523
+ console.error('candidate not found'); process.exitCode = 1
7524
+ } else {
7525
+ const store = dbStore()
7526
+ const candidate = store?.getCandidate(args[1])
7527
+ if (!candidate) { console.error('candidate not found'); process.exitCode = 1 }
7528
+ else {
7529
+ try {
7530
+ const commitmentEvidence = (e) => {
7531
+ if (!e.sessionId) return { quote: e.quote, turnId: e.turnId, sessionId: 'legacy', ...(e.source ? { source: e.source } : {}) }
7532
+ const turn = store.getTurn(e.turnId)
7533
+ if (!turn || turn.conversationId !== e.sessionId) throw new Error(`evidence turn not found: ${e.turnId}`)
7534
+ return { quote: e.quote, turnId: e.turnId, sessionId: e.sessionId, ...(e.source ? { source: e.source } : {}) }
7535
+ }
7536
+ const audit = { actor: 'local', action: 'memory.accept', allowed: true, reason: candidate.id }
7537
+ mutateWithAudit((s) => {
7538
+ const opsPorts = { clock: LOCAL_PORTS.clock, ids: LOCAL_PORTS.ids }
7539
+ if (candidate.kind === 'fact') {
7540
+ const input = { ...candidate.payload, authority: 'user', evidence: candidate.evidence.map(sourceRef) }
7541
+ const current = s.findFactCurrent({ subject: input.subject, predicate: input.predicate, matterId: input.matterId ?? null })
7542
+ const outcome = core.applyRemember(current, input, opsPorts)
7543
+ if (outcome.op === 'update') {
7544
+ s.updateFact(outcome.row.id, { evidence: outcome.row.evidence, source: outcome.row.source, authority: outcome.row.authority, lastSeenAt: outcome.row.lastSeenAt })
7545
+ } else if (outcome.op === 'insert') {
7546
+ s.insertFact(outcome.row)
7547
+ } else {
7548
+ s.updateFact(outcome.old.id, { status: outcome.old.status, validTo: outcome.old.validTo, expiredAt: outcome.old.expiredAt, supersededBy: outcome.old.supersededBy })
7549
+ s.insertFact(outcome.row)
7550
+ }
7551
+ } else if (candidate.kind === 'preference') {
7552
+ s.insertPreference(core.createPreference(opsPorts, { ...candidate.payload, evidence: candidate.evidence.map(sourceRef) }))
7553
+ } else if (candidate.kind === 'commitment') {
7554
+ const input = {
7555
+ ...candidate.payload,
7556
+ matterId: candidate.payload.matterId ?? s.firstActiveMatter?.()?.id,
7557
+ evidence: candidate.evidence.map(commitmentEvidence),
7558
+ }
7559
+ s.insertCommitment(core.createCommitment(opsPorts, input))
7560
+ }
7561
+ s.reviewCandidate(candidate.id, 'accepted')
7562
+ }, audit)
7563
+ console.log(`accepted ${candidate.id}`)
7564
+ } catch (error) { console.error(error.message); process.exitCode = 1 }
7565
+ }
4937
7566
  }
4938
- } else if (args[0] === 'reject') {
7567
+ } else if (sub === 'reject') {
4939
7568
  const store = dbStore()
4940
7569
  const candidate = store?.getCandidate(args[1])
4941
7570
  if (!candidate) { console.error('candidate not found'); process.exitCode = 1 }
4942
7571
  else {
4943
- updateStoreWithAudit((s) => s.reviewCandidate(candidate.id, 'rejected', args.slice(2).join(' ') || undefined), { actor: 'local', action: 'memory.reject', allowed: true, reason: candidate.id })
4944
- console.log(`rejected ${candidate.id}`)
7572
+ try {
7573
+ updateStoreWithAudit((s) => s.reviewCandidate(candidate.id, 'rejected', args.slice(2).join(' ') || undefined), { actor: 'local', action: 'memory.reject', allowed: true, reason: candidate.id })
7574
+ console.log(`rejected ${candidate.id}`)
7575
+ } catch (error) { reportCommandFailure(error) }
4945
7576
  }
4946
- } else if (args[0] === 'search') {
7577
+ } else if (sub === 'search') {
4947
7578
  const q = args.slice(1).join(' ').trim()
4948
7579
  if (!q) { console.error('usage: advisers memory search <query>'); process.exitCode = 1 }
4949
7580
  else {
4950
- const store = dbStore()
4951
- const rows = store?.searchMemory(q) ?? ledger.searchMemory(q)
7581
+ const store = readStoreOrExit()
7582
+ const rows = store ? store.searchMemory(q) : loadJson().searchMemory(q)
4952
7583
  if (!rows.length) console.log('(没有记忆匹配)')
4953
7584
  for (const r of rows) console.log(`${r.kind}\t${r.id}\t${r.text}${r.matterId ? `\t[${r.matterId}]` : ''}`)
4954
7585
  const turns = store?.searchTurns(q) ?? []
4955
7586
  for (const t of turns) console.log(`turn\t${t.conversationId}#${t.seq}\t${String(t.text).replace(/\s+/g, ' ').slice(0, 120)}`)
4956
7587
  }
4957
- } else printMemory(ledger)
7588
+ } else if (mode === 'json') printMemory(loadJson())
7589
+ else printMemory(loadReadLedger({ preferences: {}, commitments: {}, routines: {} }))
7590
+ } else if (command === 'matter') {
7591
+ await matterCommand(args)
7592
+ } else if (command === 'agenda') {
7593
+ await agendaCommand(args)
7594
+ } else if (command === 'morning') {
7595
+ await morningReportCommand(args)
4958
7596
  } else if (command === 'digest') {
7597
+ if (args[0] === 'morning') await morningReportCommand(args.slice(1))
7598
+ else {
4959
7599
  const period = args[0] === 'week' ? 'week' : 'day'
4960
- const store = dbStore()
7600
+ const store = readStoreOrExit()
4961
7601
  const { buildDigest } = await loadDigest()
4962
- console.log(buildDigest({
4963
- period,
4964
- turns: store?.listTurns(latestConversationId(), 200) ?? [],
4965
- commitments: loadLedger().listCommitments(),
4966
- deliveries: store?.listDeliveries(100) ?? [],
4967
- }))
7602
+ const ledger = mode === 'json' ? loadJson() : loadReadLedger({ commitments: {} })
7603
+ const conversationId = store?.listSessions(1)?.[0]?.conversationId ?? 'local'
7604
+ const { turns, deliveries } = store
7605
+ ? store.read(() => ({ turns: store.listTurns(conversationId, 200), deliveries: store.listDeliveries(100) }))
7606
+ : { turns: [], deliveries: [] }
7607
+ console.log(buildDigest({ period, turns, commitments: ledger.listCommitments(), deliveries }))
7608
+ }
4968
7609
  } else if (command === 'week') {
4969
- printWeek(loadLedger({ commitments: {} }))
7610
+ if (mode === 'json') printWeek(loadJson())
7611
+ else printWeek(loadReadLedger({ commitments: {} }))
4970
7612
  } else if (command === 'prefs') {
4971
7613
  printPreferences()
4972
7614
  } else if (command === 'privacy') {
@@ -4976,19 +7618,67 @@ if (!command) {
4976
7618
  } else if (command === 'purge') {
4977
7619
  purgeMatter(args[0], args.includes('--yes'))
4978
7620
  } else if (command === 'decay') {
4979
- const ledger = loadLedger()
7621
+ // 0.2.3 §3.3.7: read one table, update only the changed preferences (no audit,
7622
+ // historical behaviour). WAL grows with changed rows, not ledger size.
4980
7623
  const { applyPreferenceDecay } = await loadLearning()
4981
- const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
4982
- saveLedger(ledger)
4983
- console.log(`[decay] ${changed.length} preference(s) updated`)
7624
+ if (mode === 'json') {
7625
+ const ledger = loadJson()
7626
+ const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
7627
+ saveJson(ledger)
7628
+ console.log(`[decay] ${changed.length} preference(s) updated`)
7629
+ } else {
7630
+ try {
7631
+ const store = dbStore()
7632
+ const changed = applyPreferenceDecay(store.loadPreferences())
7633
+ if (changed.length) {
7634
+ mutateWithAudit((s) => {
7635
+ for (const pref of changed) s.updatePreference(pref.id, { confidence: pref.confidence, status: pref.status })
7636
+ }, null)
7637
+ }
7638
+ console.log(`[decay] ${changed.length} preference(s) updated`)
7639
+ } catch (error) { reportCommandFailure(error) }
7640
+ }
4984
7641
  } else if (command === 'correct') {
7642
+ // 0.2.3 §3.3.6: same confirmation rule as learnPreference, applied as one
7643
+ // targeted UPDATE/INSERT + audit (no full ledger load/save).
4985
7644
  const statement = args.join(' ').trim()
4986
7645
  if (!statement) { console.error('usage: advisers correct <statement>'); process.exitCode = 1 }
4987
- else {
4988
- const ledger = loadLedger()
7646
+ else if (mode === 'json') {
7647
+ const ledger = loadJson()
4989
7648
  const result = learnPreference(ledger, statement, statement, { explicit: true })
4990
- saveLedgerWithAudit(ledger, { actor: 'local', action: 'correct', allowed: true, reason: result.preference.id })
7649
+ saveJson(ledger)
4991
7650
  printLearnReceipt(result)
7651
+ } else {
7652
+ try {
7653
+ const timestamp = now()
7654
+ const audit = { actor: 'local', action: 'correct', allowed: true, reason: '' }
7655
+ const { result } = mutateWithAudit((store) => {
7656
+ const opsPorts = { clock: LOCAL_PORTS.clock, ids: LOCAL_PORTS.ids }
7657
+ const existing = store.findPreferenceByStatement(statement)
7658
+ let next
7659
+ if (existing) {
7660
+ next = core.confirmPreference(existing, timestamp)
7661
+ store.updatePreference(existing.id, {
7662
+ confidence: next.preference.confidence,
7663
+ lastConfirmed: next.preference.lastConfirmed,
7664
+ status: next.preference.status,
7665
+ })
7666
+ } else {
7667
+ const pref = core.createPreference(opsPorts, {
7668
+ kind: 'preference',
7669
+ statement,
7670
+ source: { type: 'user_explicit', quote: statement },
7671
+ confidence: 0.8,
7672
+ status: 'confirmed',
7673
+ })
7674
+ store.insertPreference(pref)
7675
+ next = { preference: pref, promoted: false }
7676
+ }
7677
+ audit.reason = next.preference.id
7678
+ return next
7679
+ }, audit)
7680
+ printLearnReceipt(result)
7681
+ } catch (error) { reportCommandFailure(error) }
4992
7682
  }
4993
7683
  } else if (command === 'ls') {
4994
7684
  ls()
@@ -5076,6 +7766,20 @@ if (!command) {
5076
7766
  if (flags.content === true) {
5077
7767
  const checkOffice = await loadOfficeOperation('check', 'checkOffice')
5078
7768
  const content = await checkOffice(readFileSync(file), ext)
7769
+ if (typeof flags.template === 'string') {
7770
+ const templateName = flags.template
7771
+ if (templateName !== 'quote' && templateName !== 'proposal') throw new Error('E_TEMPLATE_UNKNOWN: unknown template ' + templateName)
7772
+ if (typeof flags.data !== 'string') throw new Error('E_TEMPLATE_INVALID: --template requires --data <data.json>')
7773
+ const raw = JSON.parse(readFileSync(flags.data, 'utf8'))
7774
+ const normalized = normalizeQuoteData(raw, templateName)
7775
+ const evidence = await loadEvidence()
7776
+ const dataSha256 = evidence.sha256Hex(evidence.stableStringify(normalized.data, { space: 0 }))
7777
+ const text = (await readOfficeText(file, ext)) ?? ''
7778
+ const extraChecks = quoteTemplateChecks(templateName, normalized, dataSha256, text)
7779
+ content.checks = Array.isArray(content.checks) ? content.checks.concat(extraChecks) : extraChecks
7780
+ content.template = { name: templateName, version: QUOTE_TEMPLATE_VERSION, dataSha256: dataSha256, totals: quoteTotalsJson(normalized) }
7781
+ if (!extraChecks.every((check) => check.ok)) content.ok = false
7782
+ }
5079
7783
  console.log(JSON.stringify({ structure: result, content }, null, 2))
5080
7784
  if (!content.ok) process.exitCode = 1
5081
7785
  } else console.log(JSON.stringify(result, null, 2))
@@ -5092,7 +7796,7 @@ if (!command) {
5092
7796
  } else if (command === 'routine') {
5093
7797
  await routine(args[0], args[1], args[2])
5094
7798
  } else if (command === 'template') {
5095
- await template(args[0], args[1], args[2])
7799
+ await template(args)
5096
7800
  process.exit(process.exitCode || 0)
5097
7801
  } else if (command === 'link') {
5098
7802
  link(args[0], args[1], args[2], args[3])