advisers 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE +0 -0
  2. package/NOTICE +0 -0
  3. package/README-zh.md +10 -6
  4. package/README.md +15 -6
  5. package/THIRD-PARTY-NOTICES.md +1 -1
  6. package/bin/advisers.js +3323 -222
  7. package/index.js +1 -1
  8. package/lib/agent.js +0 -0
  9. package/lib/attachments.js +0 -0
  10. package/lib/audit-anchor.js +683 -0
  11. package/lib/backup.js +1345 -0
  12. package/lib/capture.js +0 -0
  13. package/lib/context-window.js +0 -0
  14. package/lib/digest.js +0 -0
  15. package/lib/doc-review.js +0 -0
  16. package/lib/egress.js +0 -0
  17. package/lib/error-codes.js +1373 -0
  18. package/lib/evidence.js +202 -26
  19. package/lib/fs-safe.js +70 -7
  20. package/lib/ical.js +0 -0
  21. package/lib/imap.js +6 -2
  22. package/lib/importers.js +0 -0
  23. package/lib/learning.js +0 -0
  24. package/lib/ledger-read.js +608 -0
  25. package/lib/mcp-server.js +294 -38
  26. package/lib/model.js +0 -0
  27. package/lib/node-warning-filter.js +15 -0
  28. package/lib/notify.js +13 -3
  29. package/lib/nudge.js +0 -0
  30. package/lib/ocr.js +0 -0
  31. package/lib/pdf.js +0 -0
  32. package/lib/pet-brief-store.js +0 -0
  33. package/lib/pet-brief.js +102 -39
  34. package/lib/receipt-verify.js +213 -15
  35. package/lib/relative-date.js +0 -0
  36. package/lib/remind.js +91 -36
  37. package/lib/research.js +0 -0
  38. package/lib/review.js +0 -0
  39. package/lib/routine.js +0 -0
  40. package/lib/safety/classifier.js +0 -0
  41. package/lib/safety/explain.js +0 -0
  42. package/lib/safety/index.js +0 -0
  43. package/lib/safety/redact.js +0 -0
  44. package/lib/safety/rules.js +0 -0
  45. package/lib/scheduler.js +0 -0
  46. package/lib/source.js +0 -0
  47. package/lib/sqlite.js +1214 -24
  48. package/lib/sync.js +0 -0
  49. package/lib/text-safe.js +229 -0
  50. package/lib/timestamp.js +0 -0
  51. package/lib/tos/index.js +1 -1
  52. package/lib/tos/manifest.json +6 -6
  53. package/lib/tos/privacy.zh-CN.md +12 -9
  54. package/lib/tos/safety.zh-CN.md +4 -3
  55. package/lib/tos/summary.zh-CN.md +3 -3
  56. package/lib/tos/terms.zh-CN.md +8 -6
  57. package/lib/tui/color.js +164 -0
  58. package/lib/tui/index.js +33 -0
  59. package/lib/tui/json.js +124 -0
  60. package/lib/tui/labels.js +50 -0
  61. package/lib/tui/policy.js +108 -0
  62. package/lib/tui/render.js +371 -0
  63. package/lib/tui/sanitize.js +142 -0
  64. package/lib/tui/text-file.js +116 -0
  65. package/lib/tui/width.js +577 -0
  66. package/lib/ui.js +0 -0
  67. package/lib/undo.js +0 -0
  68. package/lib/untrusted.js +0 -0
  69. package/lib/vault.js +0 -0
  70. package/package.json +6 -5
package/lib/sqlite.js CHANGED
@@ -24,10 +24,19 @@ import { copyFileWithRetrySync, fsyncDirSync, fsyncFileSync, rmWithRetrySync } f
24
24
  *
25
25
  * v20 (0.2.3 persistence v2): adds the schema_migrations ledger, the
26
26
  * idx_turns_seq / idx_facts_identity / idx_memory_candidates_status indexes,
27
- * and turns migrate() into a per-version step table. This is NOT the wire
27
+ * and turns migrate() into a per-version step table.
28
+ *
29
+ * v21 (0.3.0 customer entities): adds clients / projects / client_notes,
30
+ * matters.client_id/project_id (nullable ownership; the single source of
31
+ * truth for who a matter belongs to), commitments.created_at (the derived
32
+ * customer timeline needs the moment a commitment was recorded, not its due
33
+ * date), and the deliveries lineage columns (client_id/project_id snapshot +
34
+ * template_name/template_version/quote_no/data_sha256). There is no event
35
+ * table and no stored counter: the timeline and the client views are derived
36
+ * from these rows by packages/core/src/customer.ts. This is NOT the wire
28
37
  * format: LedgerSnapshot.version stays 1 (see core/src/ledger.ts).
29
38
  */
30
- export const SCHEMA_VERSION = 20
39
+ export const SCHEMA_VERSION = 21
31
40
  /** The last schema built by the single-block legacy migration (0.2.2). */
32
41
  const LEGACY_SCHEMA_VERSION = 19
33
42
  const DEFAULT_BUSY_TIMEOUT_MS = 5000
@@ -439,7 +448,8 @@ const SCHEMA = `
439
448
  CREATE TABLE IF NOT EXISTS matters (
440
449
  id TEXT PRIMARY KEY, title TEXT NOT NULL, status TEXT NOT NULL, domain TEXT NOT NULL,
441
450
  secrecy INTEGER NOT NULL, summary TEXT, participants TEXT NOT NULL, deadlines TEXT NOT NULL,
442
- open_questions TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
451
+ open_questions TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
452
+ client_id TEXT, project_id TEXT
443
453
  );
444
454
  CREATE TABLE IF NOT EXISTS facts (
445
455
  id TEXT PRIMARY KEY, matter_id TEXT, subject TEXT NOT NULL, predicate TEXT NOT NULL,
@@ -451,7 +461,8 @@ CREATE TABLE IF NOT EXISTS facts (
451
461
  CREATE TABLE IF NOT EXISTS commitments (
452
462
  id TEXT PRIMARY KEY, matter_id TEXT NOT NULL, debtor TEXT NOT NULL, creditor TEXT NOT NULL,
453
463
  action TEXT NOT NULL, due_at TEXT, timezone TEXT NOT NULL, status TEXT NOT NULL,
454
- evidence TEXT NOT NULL, capability TEXT NOT NULL, done_at TEXT, reminder_offsets TEXT
464
+ evidence TEXT NOT NULL, capability TEXT NOT NULL, done_at TEXT, reminder_offsets TEXT,
465
+ created_at TEXT
455
466
  );
456
467
  CREATE TABLE IF NOT EXISTS preferences (
457
468
  id TEXT PRIMARY KEY, kind TEXT NOT NULL, statement TEXT NOT NULL, scope TEXT NOT NULL,
@@ -507,7 +518,9 @@ CREATE TABLE IF NOT EXISTS sessions (
507
518
  );
508
519
  CREATE TABLE IF NOT EXISTS deliveries (
509
520
  id TEXT PRIMARY KEY, matter_id TEXT NOT NULL, conversation_id TEXT NOT NULL,
510
- files TEXT NOT NULL, tool TEXT, title TEXT, validation TEXT, created_at TEXT NOT NULL
521
+ files TEXT NOT NULL, tool TEXT, title TEXT, validation TEXT, created_at TEXT NOT NULL,
522
+ client_id TEXT, project_id TEXT, template_name TEXT, template_version TEXT,
523
+ quote_no TEXT, data_sha256 TEXT
511
524
  );
512
525
  CREATE TABLE IF NOT EXISTS audit (
513
526
  seq INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, actor TEXT NOT NULL,
@@ -541,6 +554,27 @@ CREATE TABLE IF NOT EXISTS calendar_events (
541
554
  all_day INTEGER NOT NULL DEFAULT 0, tzid TEXT, location TEXT, rrule TEXT,
542
555
  source TEXT, imported_at TEXT NOT NULL
543
556
  );
557
+ -- 0.3.0 (schema v21) customer entities. display name + name_norm (application
558
+ -- normalisation: NFKC, zero-width stripped, whitespace folded, lowercase) is
559
+ -- what the partial unique index enforces among active rows, so an archived or
560
+ -- merged client's name can be reused. notes is short operator prose, never a
561
+ -- file path; nothing here is a fourth ledger (see docs/ARCHITECTURE.md).
562
+ CREATE TABLE IF NOT EXISTS clients (
563
+ id TEXT PRIMARY KEY, name TEXT NOT NULL, name_norm TEXT NOT NULL,
564
+ aliases TEXT NOT NULL DEFAULT '[]', status TEXT NOT NULL DEFAULT 'active',
565
+ tags TEXT NOT NULL DEFAULT '[]', secrecy_default INTEGER NOT NULL DEFAULT 0,
566
+ notes TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT
567
+ );
568
+ CREATE TABLE IF NOT EXISTS projects (
569
+ id TEXT PRIMARY KEY, client_id TEXT NOT NULL, name TEXT NOT NULL, name_norm TEXT NOT NULL,
570
+ status TEXT NOT NULL DEFAULT 'active', started_at TEXT, due_at TEXT, default_matter_id TEXT,
571
+ notes TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT
572
+ );
573
+ CREATE TABLE IF NOT EXISTS client_notes (
574
+ id TEXT PRIMARY KEY, client_id TEXT NOT NULL, project_id TEXT, matter_id TEXT,
575
+ kind TEXT NOT NULL, at TEXT NOT NULL, summary TEXT NOT NULL, source TEXT,
576
+ created_at TEXT NOT NULL, deleted_at TEXT
577
+ );
544
578
  CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
545
579
  ${SCHEMA_MIGRATIONS_DDL}`
546
580
 
@@ -627,8 +661,39 @@ CREATE INDEX IF NOT EXISTS idx_facts_identity ON facts(subject, predicate, matte
627
661
  CREATE INDEX IF NOT EXISTS idx_memory_candidates_status ON memory_candidates(status);
628
662
  `
629
663
 
664
+ /**
665
+ * v21 (customer entities) layout: the partial unique indexes are what makes
666
+ * duplicate active client/project names impossible even under a racing writer,
667
+ * while an archived/merged row may keep its old name so it can be reused. The
668
+ * ownership/lineage indexes serve the derived timeline and the client views;
669
+ * like every secondary index they are layout only (IF NOT EXISTS on open) and
670
+ * do not themselves bump the schema version.
671
+ */
672
+ const V21_INDEXES = `
673
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_clients_name_norm_active ON clients(name_norm) WHERE status = 'active' AND deleted_at IS NULL;
674
+ CREATE INDEX IF NOT EXISTS idx_clients_status ON clients(status);
675
+ CREATE INDEX IF NOT EXISTS idx_projects_client_status ON projects(client_id, status);
676
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_projects_client_name_active ON projects(client_id, name_norm) WHERE status = 'active' AND deleted_at IS NULL;
677
+ CREATE INDEX IF NOT EXISTS idx_client_notes_client_at ON client_notes(client_id, at DESC);
678
+ CREATE INDEX IF NOT EXISTS idx_matters_client ON matters(client_id, status);
679
+ CREATE INDEX IF NOT EXISTS idx_matters_project ON matters(project_id, status);
680
+ CREATE INDEX IF NOT EXISTS idx_commitments_matter ON commitments(matter_id);
681
+ CREATE INDEX IF NOT EXISTS idx_deliveries_matter ON deliveries(matter_id, created_at);
682
+ `
683
+ /**
684
+ * 0.3.0 P0-T2 (2026-11-20): two more layout-only indexes for the pet-brief read
685
+ * projection. Both replace a full facts scan + TEMP B-TREE on every pet-brief:
686
+ * - (status, confidence) serves the top-N facts by confidence query
687
+ * (measured 40ms -> 5ms at 200k facts);
688
+ * - (status, deleted_at, expired_at, subject) is covering for the redactor
689
+ * name-candidate scan (measured 69ms -> 34ms).
690
+ * Neither changes the schema version: secondary indexes are layout only and
691
+ * are created IF NOT EXISTS on open, like the 0.2.2 P2-1 indexes below.
692
+ */
630
693
  const INDEXES = `
631
694
  CREATE INDEX IF NOT EXISTS idx_nudges_commitment_at ON nudges(commitment_id, at);
695
+ CREATE INDEX IF NOT EXISTS idx_facts_status_confidence ON facts(status, confidence);
696
+ CREATE INDEX IF NOT EXISTS idx_facts_valid_subject ON facts(status, deleted_at, expired_at, subject);
632
697
  CREATE INDEX IF NOT EXISTS idx_nudges_local_day_level ON nudges(local_day, level);
633
698
  CREATE INDEX IF NOT EXISTS idx_nudges_at ON nudges(at);
634
699
  CREATE INDEX IF NOT EXISTS idx_commitments_status_due ON commitments(status, due_at);
@@ -640,8 +705,26 @@ CREATE INDEX IF NOT EXISTS idx_deliveries_created ON deliveries(created_at);
640
705
  CREATE INDEX IF NOT EXISTS idx_task_runs_created ON task_runs(created_at);
641
706
  CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at);
642
707
  CREATE INDEX IF NOT EXISTS idx_model_calls_created ON model_calls(created_at);
643
- ${V20_INDEXES}`
708
+ ${V20_INDEXES}
709
+ ${V21_INDEXES}`
710
+
644
711
 
712
+ /**
713
+ * Per-version migration steps (schema v20+). Each step must be idempotent
714
+ * (IF NOT EXISTS / INSERT OR REPLACE) because it can be retried after a crash
715
+ * that rolled the transaction back. migrate() runs every step with
716
+ * version > current inside one BEGIN IMMEDIATE, records name/duration/backup
717
+ * in schema_migrations, and only then bumps meta.schema_version.
718
+ */
719
+ /**
720
+ * Idempotent ALTER TABLE ... ADD COLUMN guard shared by the version steps.
721
+ * SQLite has no ADD COLUMN IF NOT EXISTS, and a step must be retryable after a
722
+ * crash rolled its transaction back (the column is then absent again).
723
+ */
724
+ function addColumnIfMissing(db, table, column, type) {
725
+ const columns = db.prepare('PRAGMA table_info(' + table + ')').all().map((row) => row.name)
726
+ if (!columns.includes(column)) db.exec('ALTER TABLE ' + table + ' ADD COLUMN ' + column + ' ' + type)
727
+ }
645
728
 
646
729
  /**
647
730
  * Per-version migration steps (schema v20+). Each step must be idempotent
@@ -659,6 +742,28 @@ const MIGRATIONS = [
659
742
  store.db.exec(V20_INDEXES)
660
743
  },
661
744
  },
745
+ {
746
+ version: 21,
747
+ name: 'client-project-entities-delivery-lineage',
748
+ up(store) {
749
+ // The three new tables are part of SCHEMA and created with IF NOT EXISTS
750
+ // before this step runs (in initializeSchema's transaction), so a fresh
751
+ // database and an upgraded one converge on one layout; CREATE TABLE IF
752
+ // NOT EXISTS cannot add columns to an existing table, so the ownership /
753
+ // lineage columns are added here. All checks are idempotent.
754
+ addColumnIfMissing(store.db, 'matters', 'client_id', 'TEXT')
755
+ addColumnIfMissing(store.db, 'matters', 'project_id', 'TEXT')
756
+ // The derived timeline places a commitment at its creation instant; old
757
+ // rows keep NULL and the derivation reports them as degraded instead of
758
+ // pretending a due date is a historical event.
759
+ addColumnIfMissing(store.db, 'commitments', 'created_at', 'TEXT')
760
+ for (const [column, type] of [
761
+ ['client_id', 'TEXT'], ['project_id', 'TEXT'],
762
+ ['template_name', 'TEXT'], ['template_version', 'TEXT'],
763
+ ['quote_no', 'TEXT'], ['data_sha256', 'TEXT'],
764
+ ]) addColumnIfMissing(store.db, 'deliveries', column, type)
765
+ },
766
+ },
662
767
  ]
663
768
  const json = (v) => JSON.stringify(v ?? [])
664
769
  const parse = (v, fallback = []) => {
@@ -666,6 +771,280 @@ const parse = (v, fallback = []) => {
666
771
  try { return JSON.parse(v) } catch { return fallback }
667
772
  }
668
773
 
774
+ // ---------------------------------------------------------------------------
775
+ // Customer entity helpers (schema v21, 0.3.0).
776
+ //
777
+ // clients/projects/client_notes are SQLite-only rows: they never enter the wire
778
+ // LedgerSnapshot, so the store is the single gate that validates them (bin and
779
+ // every future caller share this path):
780
+ // - a name is stored twice: name (display, verbatim) and name_norm (the
781
+ // duplicate key produced by normalizeClientName());
782
+ // - nothing is hard-deleted: deleted_at is the tombstone and the partial unique
783
+ // indexes only cover active, non-deleted rows, so a name can be reused after
784
+ // an archive/merge;
785
+ // - notes/summaries are short operator prose; a note source id that looks like
786
+ // an absolute path is refused so an exported customer view cannot carry the
787
+ // home directory with it.
788
+ // ---------------------------------------------------------------------------
789
+
790
+ /** Allowed client/project statuses (archived rows are tombstones). */
791
+ export const CLIENT_STATUSES = ['active', 'archived']
792
+ export const PROJECT_STATUSES = ['active', 'archived']
793
+ /** Allowed client_notes kinds. */
794
+ export const CLIENT_NOTE_KINDS = ['note', 'call', 'meeting', 'decision', 'email-summary']
795
+ /** Allowed client note source kinds (lineage only, never a file copy). */
796
+ export const CLIENT_NOTE_SOURCE_KINDS = ['delivery', 'matter', 'manual']
797
+
798
+ /**
799
+ * Tables that a full export --all carries next to the nine-table ledger
800
+ * snapshot. The three v21 customer tables are appended so an export/import
801
+ * round-trip cannot silently drop them; this constant is the single list the
802
+ * CLI should read instead of hard-coding its own (bin wiring is a separate
803
+ * 0.3.0 task).
804
+ */
805
+ export const DATA_TABLES = Object.freeze([
806
+ 'sessions', 'turns', 'session_summaries', 'summary_versions', 'deliveries', 'nudges',
807
+ 'task_runs', 'audit', 'memory_candidates', 'permit_consumed',
808
+ 'clients', 'projects', 'client_notes',
809
+ ])
810
+
811
+ /** A business error with a stable code (message keeps the code for stderr). */
812
+ export function entityError(code, message, hint) {
813
+ const error = new Error(code + ': ' + message + (hint ? ' (hint: ' + hint + ')' : ''))
814
+ error.code = code
815
+ if (hint) error.hint = hint
816
+ return error
817
+ }
818
+
819
+ /**
820
+ * Duplicate-detection key for a client/project display name.
821
+ *
822
+ * NFKC folds compatibility forms (full-width A -> A), zero-width characters are
823
+ * removed, whitespace is folded/trimmed and lowercasing makes Latin matching
824
+ * case-insensitive (CJK is unchanged). Pure and deterministic so the unique
825
+ * index and the CLI agree byte for byte. Deliberately no fuzzy matching: two
826
+ * different spellings are never guessed to be one customer.
827
+ */
828
+ export function normalizeClientName(value) {
829
+ if (typeof value !== 'string') throw new TypeError('name must be a string')
830
+ return value
831
+ .normalize('NFKC')
832
+ .replace(/[\u200B-\u200D\u2060\uFEFF]/g, '')
833
+ .trim()
834
+ .replace(/\s+/gu, ' ')
835
+ .toLowerCase()
836
+ }
837
+
838
+ const ABSOLUTE_PATH_RE = /^(?:[A-Za-z]:[\\/]|\/|\\\\)/
839
+
840
+ function invalidKind(kind) {
841
+ return kind === 'client' ? 'E_CLIENT_INVALID' : kind === 'project' ? 'E_PROJECT_INVALID' : 'E_CLIENT_NOTE_INVALID'
842
+ }
843
+
844
+ function validateDisplayName(kind, value, { max = 200 } = {}) {
845
+ if (typeof value !== 'string') throw entityError(invalidKind(kind), kind + ' name is required')
846
+ const name = value.normalize('NFKC').replace(/[\u200B-\u200D\u2060\uFEFF]/g, '').trim()
847
+ if (!name) throw entityError(invalidKind(kind), kind + ' name is required')
848
+ if (name.length > max) throw entityError(invalidKind(kind), kind + ' name is longer than ' + max + ' characters')
849
+ return name
850
+ }
851
+
852
+ function validateEntityStatus(kind, value) {
853
+ const allowed = kind === 'client' ? CLIENT_STATUSES : PROJECT_STATUSES
854
+ if (value === undefined || value === null) return 'active'
855
+ if (!allowed.includes(value)) {
856
+ throw entityError(invalidKind(kind), 'unknown ' + kind + ' status: ' + String(value), 'use one of ' + allowed.join(', '))
857
+ }
858
+ return value
859
+ }
860
+
861
+ function validateStringList(kind, field, value, { max = 100, itemMax = 200 } = {}) {
862
+ if (value === undefined || value === null) return []
863
+ if (!Array.isArray(value)) throw entityError(invalidKind(kind), field + ' must be an array of strings')
864
+ if (value.length > max) throw entityError(invalidKind(kind), field + ' has more than ' + max + ' entries')
865
+ const seen = new Set()
866
+ const list = []
867
+ for (const entry of value) {
868
+ if (typeof entry !== 'string') throw entityError(invalidKind(kind), field + ' must be an array of strings')
869
+ const text = entry.trim()
870
+ if (!text) throw entityError(invalidKind(kind), field + ' entries must not be empty')
871
+ if (text.length > itemMax) throw entityError(invalidKind(kind), field + ' entries must be at most ' + itemMax + ' characters')
872
+ if (seen.has(text)) continue
873
+ seen.add(text)
874
+ list.push(text)
875
+ }
876
+ return list
877
+ }
878
+
879
+ function validateSecrecy(value) {
880
+ if (value === undefined || value === null) return 0
881
+ const number = Number(value)
882
+ if (!Number.isInteger(number) || number < 0 || number > 3) {
883
+ throw entityError('E_CLIENT_INVALID', 'secrecyDefault must be an integer 0..3')
884
+ }
885
+ return number
886
+ }
887
+
888
+ /** Validate an optional date/date-time field and keep the caller text. */
889
+ function normalizeOptionalDate(kind, field, value) {
890
+ if (value === undefined || value === null) return null
891
+ if (typeof value !== 'string') throw entityError(invalidKind(kind), field + ' must be a YYYY-MM-DD date or an ISO timestamp')
892
+ const text = value.trim()
893
+ if (!text) return null
894
+ if (!/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:\d{2})?)?$/.test(text) || !Number.isFinite(Date.parse(text))) {
895
+ throw entityError(invalidKind(kind), field + ' must be a YYYY-MM-DD date or an ISO timestamp')
896
+ }
897
+ return text
898
+ }
899
+
900
+ /** Validate an optional free-text field (notes) and keep the caller text. */
901
+ function normalizeOptionalText(kind, field, value, max) {
902
+ if (value === undefined || value === null) return null
903
+ if (typeof value !== 'string') throw entityError(invalidKind(kind), field + ' must be a string')
904
+ const text = value.trim()
905
+ if (!text) return null
906
+ if (text.length > max) throw entityError(invalidKind(kind), field + ' must be at most ' + max + ' characters')
907
+ return text
908
+ }
909
+
910
+ /** Clamp a requested row limit into [1, max]. */
911
+ function normalizeRowLimit(value, { def = 100, max = 1000 } = {}) {
912
+ const number = Number(value)
913
+ if (!Number.isFinite(number) || number <= 0) return def
914
+ return Math.min(Math.floor(number), max)
915
+ }
916
+
917
+ /** Client-note event time: normalized to ISO UTC so ordering is unambiguous. */
918
+ function normalizeNoteInstant(value) {
919
+ if (value === undefined || value === null) return new Date().toISOString()
920
+ const text = String(value).trim()
921
+ const ms = text ? Date.parse(text) : Number.NaN
922
+ if (!Number.isFinite(ms)) throw entityError('E_CLIENT_NOTE_INVALID', 'at must be an ISO timestamp')
923
+ return new Date(ms).toISOString()
924
+ }
925
+
926
+ /** Validate the optional lineage JSON of a client note. */
927
+ function validateNoteSource(value) {
928
+ if (value === undefined || value === null) return null
929
+ if (typeof value !== 'object' || Array.isArray(value)) throw entityError('E_CLIENT_NOTE_INVALID', 'source must be an object')
930
+ const source = {}
931
+ if (value.kind !== undefined) {
932
+ if (!CLIENT_NOTE_SOURCE_KINDS.includes(value.kind)) {
933
+ throw entityError('E_CLIENT_NOTE_INVALID', 'unknown note source kind: ' + String(value.kind), 'use one of ' + CLIENT_NOTE_SOURCE_KINDS.join(', '))
934
+ }
935
+ source.kind = value.kind
936
+ }
937
+ if (value.id !== undefined) {
938
+ if (typeof value.id !== 'string' || !value.id.trim() || value.id.length > 200) {
939
+ throw entityError('E_CLIENT_NOTE_INVALID', 'source.id must be a short id string')
940
+ }
941
+ if (ABSOLUTE_PATH_RE.test(value.id.trim())) throw entityError('E_CLIENT_NOTE_INVALID', 'source.id must be an id, not a file path')
942
+ source.id = value.id.trim()
943
+ }
944
+ if (value.quote !== undefined) {
945
+ if (typeof value.quote !== 'string' || value.quote.length > 500) throw entityError('E_CLIENT_NOTE_INVALID', 'source.quote must be a string of at most 500 characters')
946
+ source.quote = value.quote
947
+ }
948
+ if (source.kind !== undefined && source.kind !== 'manual' && !source.id) {
949
+ throw entityError('E_CLIENT_NOTE_INVALID', 'source.id is required for a ' + source.kind + ' source')
950
+ }
951
+ return JSON.stringify(source)
952
+ }
953
+
954
+ /** Validate the optional delivery template lineage columns (v21). */
955
+ function normalizeDeliveryLineage({ clientId, projectId, templateName, templateVersion, quoteNo, dataSha256 } = {}) {
956
+ const shortText = (field, value, max) => {
957
+ if (value === undefined || value === null) return null
958
+ if (typeof value !== 'string') throw entityError('E_DELIVERY_INVALID', field + ' must be a string')
959
+ const text = value.trim()
960
+ if (!text) return null
961
+ if (text.length > max) throw entityError('E_DELIVERY_INVALID', field + ' must be at most ' + max + ' characters')
962
+ if (ABSOLUTE_PATH_RE.test(text)) throw entityError('E_DELIVERY_INVALID', field + ' must not be a file path')
963
+ return text
964
+ }
965
+ const idOf = (field, value) => {
966
+ if (value === undefined || value === null) return null
967
+ if (typeof value !== 'string' || !value.trim() || value.length > 200) throw entityError('E_DELIVERY_INVALID', field + ' must be an id string')
968
+ return value.trim()
969
+ }
970
+ const sha = dataSha256 === undefined || dataSha256 === null ? null : String(dataSha256).trim().toLowerCase()
971
+ if (sha !== null && !/^[0-9a-f]{64}$/.test(sha)) {
972
+ throw entityError('E_DELIVERY_INVALID', 'dataSha256 must be 64 lowercase hex characters', 'pass the SHA-256 of the canonical template data')
973
+ }
974
+ return {
975
+ clientId: idOf('clientId', clientId),
976
+ projectId: idOf('projectId', projectId),
977
+ templateName: shortText('templateName', templateName, 40),
978
+ templateVersion: shortText('templateVersion', templateVersion, 40),
979
+ quoteNo: shortText('quoteNo', quoteNo, 40),
980
+ dataSha256: sha,
981
+ }
982
+ }
983
+
984
+ const mapClientRow = (row) => ({
985
+ id: row.id,
986
+ name: row.name,
987
+ nameNorm: row.name_norm,
988
+ aliases: parse(row.aliases),
989
+ status: row.status,
990
+ tags: parse(row.tags),
991
+ secrecyDefault: Number(row.secrecy_default),
992
+ notes: row.notes ?? undefined,
993
+ createdAt: row.created_at,
994
+ updatedAt: row.updated_at,
995
+ ...(row.deleted_at == null ? {} : { deletedAt: row.deleted_at }),
996
+ })
997
+
998
+ const mapProjectRow = (row) => ({
999
+ id: row.id,
1000
+ clientId: row.client_id,
1001
+ name: row.name,
1002
+ nameNorm: row.name_norm,
1003
+ status: row.status,
1004
+ startedAt: row.started_at ?? undefined,
1005
+ dueAt: row.due_at ?? undefined,
1006
+ defaultMatterId: row.default_matter_id ?? undefined,
1007
+ notes: row.notes ?? undefined,
1008
+ createdAt: row.created_at,
1009
+ updatedAt: row.updated_at,
1010
+ ...(row.deleted_at == null ? {} : { deletedAt: row.deleted_at }),
1011
+ })
1012
+
1013
+ const mapClientNoteRow = (row) => ({
1014
+ id: row.id,
1015
+ clientId: row.client_id,
1016
+ projectId: row.project_id ?? undefined,
1017
+ matterId: row.matter_id ?? undefined,
1018
+ kind: row.kind,
1019
+ at: row.at,
1020
+ summary: row.summary,
1021
+ source: row.source ? parse(row.source, undefined) : undefined,
1022
+ createdAt: row.created_at,
1023
+ ...(row.deleted_at == null ? {} : { deletedAt: row.deleted_at }),
1024
+ })
1025
+
1026
+ /**
1027
+ * Delivery row + template lineage. Rows written before v21 have no lineage
1028
+ * columns, so the new keys are omitted entirely (the pre-v21 JSON shape is
1029
+ * byte-identical for old rows).
1030
+ */
1031
+ const mapDeliveryRow = (row) => ({
1032
+ id: row.id,
1033
+ matterId: row.matter_id,
1034
+ conversationId: row.conversation_id,
1035
+ files: parse(row.files),
1036
+ tool: row.tool ?? undefined,
1037
+ title: row.title ?? undefined,
1038
+ validation: row.validation ?? undefined,
1039
+ createdAt: row.created_at,
1040
+ ...(row.client_id == null ? {} : { clientId: row.client_id }),
1041
+ ...(row.project_id == null ? {} : { projectId: row.project_id }),
1042
+ ...(row.template_name == null ? {} : { templateName: row.template_name }),
1043
+ ...(row.template_version == null ? {} : { templateVersion: row.template_version }),
1044
+ ...(row.quote_no == null ? {} : { quoteNo: row.quote_no }),
1045
+ ...(row.data_sha256 == null ? {} : { dataSha256: row.data_sha256 }),
1046
+ })
1047
+
669
1048
  // ---------------------------------------------------------------------------
670
1049
  // Ledger row mappers + table registry (P1-2, 0.2.2).
671
1050
  //
@@ -681,6 +1060,9 @@ const mapMatterRow = (r) => ({
681
1060
  id: r.id, title: r.title, status: r.status, domain: r.domain, secrecy: r.secrecy,
682
1061
  summary: r.summary ?? undefined, participants: parse(r.participants), deadlines: parse(r.deadlines),
683
1062
  openQuestions: parse(r.open_questions), createdAt: r.created_at, updatedAt: r.updated_at,
1063
+ // v21 ownership is additive: pre-v21 rows (NULL) keep their exact old shape.
1064
+ ...(r.client_id == null ? {} : { clientId: r.client_id }),
1065
+ ...(r.project_id == null ? {} : { projectId: r.project_id }),
684
1066
  })
685
1067
 
686
1068
  const mapFactRow = (r) => ({
@@ -705,6 +1087,8 @@ const mapCommitmentRow = (r) => {
705
1087
  id: r.id, matterId: r.matter_id, debtor: r.debtor, creditor: r.creditor, action: r.action,
706
1088
  dueAt: r.due_at ?? undefined, timezone: r.timezone, status: r.status,
707
1089
  evidence: parse(r.evidence), capability: r.capability, doneAt: r.done_at ?? undefined,
1090
+ // v21: additive (rows written before v21 have NULL here).
1091
+ ...(r.created_at == null ? {} : { createdAt: r.created_at }),
708
1092
  ...(reminderOffsets === undefined ? {} : { reminderOffsets }),
709
1093
  }
710
1094
  }
@@ -795,6 +1179,7 @@ const ENTITY_SPECS = {
795
1179
  secrecy: ['secrecy', 'int'], summary: ['summary', 'text'], participants: ['participants', 'json'],
796
1180
  deadlines: ['deadlines', 'json'], openQuestions: ['open_questions', 'json'],
797
1181
  createdAt: ['created_at', 'text'], updatedAt: ['updated_at', 'text'],
1182
+ clientId: ['client_id', 'text'], projectId: ['project_id', 'text'],
798
1183
  },
799
1184
  },
800
1185
  facts: {
@@ -819,7 +1204,7 @@ const ENTITY_SPECS = {
819
1204
  id: ['id', 'text'], matterId: ['matter_id', 'text'], debtor: ['debtor', 'text'], creditor: ['creditor', 'text'],
820
1205
  action: ['action', 'text'], dueAt: ['due_at', 'text'], timezone: ['timezone', 'text'], status: ['status', 'text'],
821
1206
  evidence: ['evidence', 'json'], capability: ['capability', 'text'], doneAt: ['done_at', 'text'],
822
- reminderOffsets: ['reminder_offsets', 'reminder'],
1207
+ reminderOffsets: ['reminder_offsets', 'reminder'], createdAt: ['created_at', 'text'],
823
1208
  },
824
1209
  },
825
1210
  preferences: {
@@ -841,8 +1226,13 @@ function encodeEntityValue(codec, value) {
841
1226
  return encode(value)
842
1227
  }
843
1228
 
844
- /** Tables whose row counts are sampled to verify a pre-migration backup. */
845
- const BACKUP_SAMPLE_TABLES = ['matters', 'facts', 'commitments', 'preferences', 'audit']
1229
+ /**
1230
+ * Tables whose row counts are sampled to verify a pre-migration backup. The
1231
+ * v21 customer tables are included so a future migration's backup verification
1232
+ * also proves the customer entities were copied (they are absent in older
1233
+ * databases and are then skipped by _sampleTableCounts).
1234
+ */
1235
+ const BACKUP_SAMPLE_TABLES = ['matters', 'facts', 'commitments', 'preferences', 'audit', 'clients', 'projects', 'client_notes']
846
1236
  // ---------------------------------------------------------------------------
847
1237
  // WAL status / recovery (robustness audit 2026-11-17 P1-6).
848
1238
  //
@@ -1846,17 +2236,61 @@ CREATE TABLE IF NOT EXISTS task_runs (
1846
2236
  return r ? { conversationId: r.conversation_id, matterId: r.matter_id, title: r.title, createdAt: r.created_at, updatedAt: r.updated_at } : undefined
1847
2237
  }
1848
2238
 
1849
- addDelivery({ matterId, conversationId, files, tool, title, validation }) {
2239
+ /**
2240
+ * Record one delivery row.
2241
+ *
2242
+ * v21 lineage (0.3.0): the optional client/project/template fields snapshot
2243
+ * WHO and WHICH template a delivery belonged to at generation time, so a
2244
+ * later matter re-link does not rewrite an already-generated receipt. When
2245
+ * the caller omits clientId/projectId they are filled from the matter the
2246
+ * delivery is filed under (the historical CLI path), and explicitly passed
2247
+ * ids are validated against the client/project rows. Every new argument is
2248
+ * optional: the pre-v21 call shape keeps working and old rows stay NULL.
2249
+ */
2250
+ addDelivery({ matterId, conversationId, files, tool, title, validation, clientId, projectId, templateName, templateVersion, quoteNo, dataSha256 } = {}) {
1850
2251
  this._assertWritable('addDelivery')
1851
- const id = `del_${randomUUID().replace(/-/g, '').slice(0, 16)}`
1852
- this.db.prepare('INSERT INTO deliveries(id,matter_id,conversation_id,files,tool,title,validation,created_at) VALUES(?,?,?,?,?,?,?,?)')
1853
- .run(id, matterId, conversationId, JSON.stringify(files ?? []), tool ?? null, title ?? null, validation ?? null, new Date().toISOString())
2252
+ const lineage = normalizeDeliveryLineage({ clientId, projectId, templateName, templateVersion, quoteNo, dataSha256 })
2253
+ let resolvedClientId = lineage.clientId
2254
+ let resolvedProjectId = lineage.projectId
2255
+ if (resolvedProjectId !== null) {
2256
+ const project = this.getProject(resolvedProjectId)
2257
+ if (!project) throw entityError('E_PROJECT_NOT_FOUND', 'unknown project: ' + resolvedProjectId)
2258
+ if (resolvedClientId === null) resolvedClientId = project.clientId
2259
+ else if (project.clientId !== resolvedClientId) throw entityError('E_PROJECT_CLIENT_MISMATCH', 'project ' + resolvedProjectId + ' belongs to client ' + project.clientId)
2260
+ }
2261
+ if (resolvedClientId !== null && !this.getClient(resolvedClientId)) {
2262
+ throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + resolvedClientId)
2263
+ }
2264
+ if ((resolvedClientId === null || resolvedProjectId === null) && matterId) {
2265
+ const matter = this.getMatter(String(matterId))
2266
+ if (matter) {
2267
+ if (resolvedClientId === null) resolvedClientId = matter.clientId ?? null
2268
+ if (resolvedProjectId === null && (matter.clientId ?? null) === resolvedClientId) resolvedProjectId = matter.projectId ?? null
2269
+ }
2270
+ }
2271
+ const id = 'del_' + randomUUID().replace(/-/g, '').slice(0, 16)
2272
+ this.db.prepare('INSERT INTO deliveries(id,matter_id,conversation_id,files,tool,title,validation,created_at,client_id,project_id,template_name,template_version,quote_no,data_sha256) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
2273
+ .run(id, matterId, conversationId, JSON.stringify(files ?? []), tool ?? null, title ?? null, validation ?? null, new Date().toISOString(),
2274
+ resolvedClientId, resolvedProjectId, lineage.templateName, lineage.templateVersion, lineage.quoteNo, lineage.dataSha256)
1854
2275
  return id
1855
2276
  }
1856
2277
 
1857
- listDeliveries(limit = 20) {
1858
- return this.db.prepare('SELECT * FROM deliveries ORDER BY created_at DESC LIMIT ?').all(limit)
1859
- .map((r) => ({ id: r.id, matterId: r.matter_id, conversationId: r.conversation_id, files: parse(r.files), tool: r.tool ?? undefined, title: r.title ?? undefined, validation: r.validation ?? undefined, createdAt: r.created_at }))
2278
+ /**
2279
+ * Newest delivery rows, optionally scoped.
2280
+ *
2281
+ * The second argument is additive: listDeliveries(limit) keeps its historical
2282
+ * result. clientId/projectId filter the generation-time snapshot columns
2283
+ * (receipt scope); matterId filters row ownership. The rowid tie-break keeps
2284
+ * same-millisecond rows in insertion order, as before.
2285
+ */
2286
+ listDeliveries(limit = 20, { clientId, projectId, matterId } = {}) {
2287
+ const where = []
2288
+ const params = []
2289
+ if (clientId !== undefined && clientId !== null) { where.push('client_id = ?'); params.push(clientId) }
2290
+ if (projectId !== undefined && projectId !== null) { where.push('project_id = ?'); params.push(projectId) }
2291
+ if (matterId !== undefined && matterId !== null) { where.push('matter_id = ?'); params.push(matterId) }
2292
+ const sql = 'SELECT * FROM deliveries' + (where.length ? ' WHERE ' + where.join(' AND ') : '') + ' ORDER BY created_at DESC, rowid DESC LIMIT ?'
2293
+ return this.db.prepare(sql).all(...params, limit).map(mapDeliveryRow)
1860
2294
  }
1861
2295
 
1862
2296
  getMeta(key) {
@@ -2512,6 +2946,609 @@ CREATE TABLE IF NOT EXISTS task_runs (
2512
2946
  return { nudges, woke, metaDeleted }
2513
2947
  })
2514
2948
  }
2949
+ // -------------------------------------------------------------------------
2950
+ // Customer / project entities (schema v21, 0.3.0).
2951
+ //
2952
+ // clients/projects/client_notes are SQLite-only rows: they never enter the
2953
+ // wire LedgerSnapshot, so they are written with directed INSERT/UPDATE
2954
+ // statements (a caller that needs an audit row wraps them in mutate(fn,
2955
+ // audit), exactly like the other directed writes) and read back through the
2956
+ // CRUD methods below. A matter keeps the ownership (client_id/project_id) as
2957
+ // the single source of truth; the client timeline is derived from the rows
2958
+ // clientTimelineSources() returns, and there is no event table and no stored
2959
+ // counter that could disagree with them. Nothing is hard-deleted: archiving
2960
+ // sets status='archived' + deleted_at, so past work stays answerable.
2961
+ // -------------------------------------------------------------------------
2962
+
2963
+ /** A live (active, non-deleted) client row for a write, or a stable E_*. */
2964
+ _clientForWrite(clientId, operation = 'client') {
2965
+ const id = typeof clientId === 'string' ? clientId.trim() : ''
2966
+ const row = id ? this.db.prepare('SELECT * FROM clients WHERE id = ?').get(id) : undefined
2967
+ if (!row) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(clientId), 'advisers client add "<name>"')
2968
+ if (row.deleted_at != null || row.status !== 'active') {
2969
+ throw entityError('E_CLIENT_ARCHIVED', 'client is archived: ' + row.id + ' (' + operation + ')', 'advisers client ls')
2970
+ }
2971
+ return row
2972
+ }
2973
+
2974
+ /** Active client identity keys (name + aliases) other than exceptId. */
2975
+ _activeClientIdentities(exceptId = null) {
2976
+ const rows = this.db.prepare("SELECT id, name, aliases FROM clients WHERE status = 'active' AND deleted_at IS NULL").all()
2977
+ const result = []
2978
+ for (const row of rows) {
2979
+ if (exceptId != null && row.id === exceptId) continue
2980
+ const norms = new Map()
2981
+ norms.set(normalizeClientName(row.name), 'name')
2982
+ for (const alias of parse(row.aliases)) {
2983
+ if (typeof alias !== 'string') continue
2984
+ const norm = normalizeClientName(alias)
2985
+ if (norm && !norms.has(norm)) norms.set(norm, 'alias')
2986
+ }
2987
+ result.push({ id: row.id, name: row.name, norms: norms })
2988
+ }
2989
+ return result
2990
+ }
2991
+
2992
+ /**
2993
+ * Refuse a client name/alias that another live client already owns. The
2994
+ * partial unique index enforces the name half even under a racing writer;
2995
+ * aliases are checked here because they live inside a JSON column.
2996
+ */
2997
+ _assertClientIdentityFree({ nameNorm, aliases = [] }, exceptId = null) {
2998
+ const identities = this._activeClientIdentities(exceptId)
2999
+ for (const identity of identities) {
3000
+ if (identity.norms.has(nameNorm)) {
3001
+ throw entityError('E_CLIENT_DUPLICATE', 'an active client named ' + identity.name + ' already exists (' + identity.id + ')', 'advisers client alias add ' + identity.id + ' <alias>')
3002
+ }
3003
+ }
3004
+ for (const alias of aliases) {
3005
+ const norm = normalizeClientName(alias)
3006
+ for (const identity of identities) {
3007
+ if (identity.norms.has(norm)) {
3008
+ throw entityError('E_CLIENT_ALIAS_CONFLICT', 'alias ' + alias + ' is already used by ' + identity.name + ' (' + identity.id + ')', 'advisers client alias add ' + identity.id + ' <alias>')
3009
+ }
3010
+ }
3011
+ }
3012
+ }
3013
+
3014
+ /** Create a client. Same-name active client -> E_CLIENT_DUPLICATE. */
3015
+ addClient({ name, aliases, tags, secrecyDefault, notes, status, id } = {}) {
3016
+ this._assertWritable('addClient')
3017
+ const displayName = validateDisplayName('client', name)
3018
+ const nameNorm = normalizeClientName(displayName)
3019
+ const aliasList = validateStringList('client', 'aliases', aliases)
3020
+ const tagList = validateStringList('client', 'tags', tags, { max: 20, itemMax: 40 })
3021
+ const secrecy = validateSecrecy(secrecyDefault)
3022
+ const clientStatus = validateEntityStatus('client', status)
3023
+ const clientId = id === undefined || id === null ? 'cl_' + randomUUID().replace(/-/g, '').slice(0, 16) : String(id).trim()
3024
+ if (!clientId) throw entityError('E_CLIENT_INVALID', 'client id must not be empty')
3025
+ if (this.getClient(clientId)) throw entityError('E_CLIENT_DUPLICATE', 'client id already exists: ' + clientId)
3026
+ if (clientStatus === 'active') this._assertClientIdentityFree({ nameNorm, aliases: aliasList })
3027
+ const now = new Date().toISOString()
3028
+ try {
3029
+ this.db.prepare('INSERT INTO clients(id,name,name_norm,aliases,status,tags,secrecy_default,notes,created_at,updated_at,deleted_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)')
3030
+ .run(clientId, displayName, nameNorm, json(aliasList), clientStatus, json(tagList), secrecy, normalizeOptionalText('client', 'notes', notes, 4000), now, now, clientStatus === 'archived' ? now : null)
3031
+ } catch (error) {
3032
+ if (/UNIQUE constraint failed/i.test(String(error?.message ?? error))) {
3033
+ throw entityError('E_CLIENT_DUPLICATE', 'an active client with this name already exists', 'advisers client ls')
3034
+ }
3035
+ throw error
3036
+ }
3037
+ return this.getClient(clientId)
3038
+ }
3039
+
3040
+ /** One client by id (archived included; undefined when absent). */
3041
+ getClient(id) {
3042
+ const row = this.db.prepare('SELECT * FROM clients WHERE id = ?').get(String(id))
3043
+ return row ? mapClientRow(row) : undefined
3044
+ }
3045
+
3046
+ /** First live client whose name or alias normalises to the given name. */
3047
+ findClientByName(name) {
3048
+ const nameNorm = normalizeClientName(validateDisplayName('client', name))
3049
+ const rows = this.db.prepare("SELECT * FROM clients WHERE status = 'active' AND deleted_at IS NULL ORDER BY created_at, id").all()
3050
+ for (const row of rows) {
3051
+ if (row.name_norm === nameNorm) return mapClientRow(row)
3052
+ for (const alias of parse(row.aliases)) {
3053
+ if (typeof alias === 'string' && normalizeClientName(alias) === nameNorm) return mapClientRow(row)
3054
+ }
3055
+ }
3056
+ return undefined
3057
+ }
3058
+
3059
+ /**
3060
+ * List clients. Default is the live (active, non-deleted) list; pass
3061
+ * status:'archived' with includeDeleted:true for tombstones, status:'all'
3062
+ * for every status. Ordered by name_norm then id (deterministic).
3063
+ */
3064
+ listClients({ status = 'active', includeDeleted = false, limit = 100 } = {}) {
3065
+ const where = []
3066
+ const params = []
3067
+ if (includeDeleted !== true) where.push('deleted_at IS NULL')
3068
+ if (status !== 'all') {
3069
+ const wanted = validateEntityStatus('client', status)
3070
+ where.push('status = ?')
3071
+ params.push(wanted)
3072
+ }
3073
+ const sql = 'SELECT * FROM clients' + (where.length ? ' WHERE ' + where.join(' AND ') : '') + ' ORDER BY name_norm ASC, id ASC LIMIT ?'
3074
+ return this.db.prepare(sql).all(...params, normalizeRowLimit(limit, { def: 100, max: 1000 })).map(mapClientRow)
3075
+ }
3076
+
3077
+ /**
3078
+ * Update the mutable client fields. Renames re-check the active identity
3079
+ * uniqueness; status:'archived' stamps deleted_at, status:'active' restores
3080
+ * (and fails closed if the name was reused meanwhile).
3081
+ */
3082
+ updateClient(id, patch = {}) {
3083
+ this._assertWritable('updateClient')
3084
+ const current = this.getClient(id)
3085
+ if (!current) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(id))
3086
+ const allowed = ['name', 'aliases', 'tags', 'secrecyDefault', 'notes', 'status']
3087
+ for (const field of Object.keys(patch)) {
3088
+ if (!allowed.includes(field)) throw new Error('unknown client field: ' + field)
3089
+ }
3090
+ const name = patch.name === undefined ? current.name : validateDisplayName('client', patch.name)
3091
+ const nameNorm = normalizeClientName(name)
3092
+ const aliases = patch.aliases === undefined ? current.aliases : validateStringList('client', 'aliases', patch.aliases)
3093
+ const tags = patch.tags === undefined ? current.tags : validateStringList('client', 'tags', patch.tags, { max: 20, itemMax: 40 })
3094
+ const secrecy = patch.secrecyDefault === undefined ? current.secrecyDefault : validateSecrecy(patch.secrecyDefault)
3095
+ const notes = patch.notes === undefined ? (current.notes ?? null) : normalizeOptionalText('client', 'notes', patch.notes, 4000)
3096
+ const status = patch.status === undefined ? current.status : validateEntityStatus('client', patch.status)
3097
+ const now = new Date().toISOString()
3098
+ let deletedAt = current.deletedAt ?? null
3099
+ if (status === 'archived' && deletedAt === null) deletedAt = now
3100
+ if (status === 'active' && deletedAt !== null) deletedAt = null
3101
+ if (status === 'active') this._assertClientIdentityFree({ nameNorm, aliases }, current.id)
3102
+ try {
3103
+ this.db.prepare('UPDATE clients SET name = ?, name_norm = ?, aliases = ?, status = ?, tags = ?, secrecy_default = ?, notes = ?, updated_at = ?, deleted_at = ? WHERE id = ?')
3104
+ .run(name, nameNorm, json(aliases), status, json(tags), secrecy, notes, now, deletedAt, current.id)
3105
+ } catch (error) {
3106
+ if (/UNIQUE constraint failed/i.test(String(error?.message ?? error))) {
3107
+ throw entityError('E_CLIENT_DUPLICATE', 'an active client with this name already exists', 'advisers client ls')
3108
+ }
3109
+ throw error
3110
+ }
3111
+ return this.getClient(current.id)
3112
+ }
3113
+
3114
+ /** Soft-delete one client (status archived + tombstone); idempotent. */
3115
+ archiveClient(id, { now } = {}) {
3116
+ this._assertWritable('archiveClient')
3117
+ const current = this.getClient(id)
3118
+ if (!current) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(id))
3119
+ const at = now === undefined || now === null ? new Date().toISOString() : String(now)
3120
+ this.db.prepare("UPDATE clients SET status = 'archived', deleted_at = COALESCE(deleted_at, ?), updated_at = ? WHERE id = ?").run(at, at, current.id)
3121
+ return this.getClient(current.id)
3122
+ }
3123
+
3124
+ /** Restore an archived client; fails closed when its name was reused. */
3125
+ restoreClient(id) {
3126
+ this._assertWritable('restoreClient')
3127
+ const current = this.getClient(id)
3128
+ if (!current) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(id))
3129
+ this._assertClientIdentityFree({ nameNorm: current.nameNorm, aliases: current.aliases }, current.id)
3130
+ const now = new Date().toISOString()
3131
+ this.db.prepare("UPDATE clients SET status = 'active', deleted_at = NULL, updated_at = ? WHERE id = ?").run(now, current.id)
3132
+ return this.getClient(current.id)
3133
+ }
3134
+
3135
+ /** Append one alias; alias conflicts with another live client are refused. */
3136
+ addClientAlias(id, alias) {
3137
+ this._assertWritable('addClientAlias')
3138
+ const current = this.getClient(id)
3139
+ if (!current) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(id))
3140
+ const text = validateDisplayName('client', alias)
3141
+ const norm = normalizeClientName(text)
3142
+ if (norm === current.nameNorm || current.aliases.some((entry) => typeof entry === 'string' && normalizeClientName(entry) === norm)) return current
3143
+ this._assertClientIdentityFree({ nameNorm: current.nameNorm, aliases: [text] }, current.id)
3144
+ const aliases = [...current.aliases, text]
3145
+ this.db.prepare('UPDATE clients SET aliases = ?, updated_at = ? WHERE id = ?').run(json(aliases), new Date().toISOString(), current.id)
3146
+ return this.getClient(current.id)
3147
+ }
3148
+
3149
+ /** Remove one alias (normalised match); unknown alias -> E_CLIENT_ALIAS_NOT_FOUND. */
3150
+ removeClientAlias(id, alias) {
3151
+ this._assertWritable('removeClientAlias')
3152
+ const current = this.getClient(id)
3153
+ if (!current) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(id))
3154
+ const norm = normalizeClientName(validateDisplayName('client', alias))
3155
+ const aliases = current.aliases.filter((entry) => !(typeof entry === 'string' && normalizeClientName(entry) === norm))
3156
+ if (aliases.length === current.aliases.length) throw entityError('E_CLIENT_ALIAS_NOT_FOUND', 'unknown alias: ' + String(alias))
3157
+ this.db.prepare('UPDATE clients SET aliases = ?, updated_at = ? WHERE id = ?').run(json(aliases), new Date().toISOString(), current.id)
3158
+ return this.getClient(current.id)
3159
+ }
3160
+
3161
+ /**
3162
+ * Merge one client into another (explicit user intent; no fuzzy matching).
3163
+ *
3164
+ * Everything source-owned moves to the target: projects with a name clash are
3165
+ * merged onto the target project, the remaining projects/matters/notes and
3166
+ * delivery snapshots are re-pointed, the source is archived (never deleted),
3167
+ * and its name/aliases become target aliases when no third live client owns
3168
+ * them. One transaction: a merge can never half-happen.
3169
+ */
3170
+ mergeClients(fromId, intoId, { now } = {}) {
3171
+ this._assertWritable('mergeClients')
3172
+ if (String(fromId) === String(intoId)) throw entityError('E_CLIENT_MERGE_SELF', 'cannot merge a client into itself')
3173
+ const source = this.getClient(fromId)
3174
+ if (!source) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(fromId))
3175
+ const target = this._clientForWrite(intoId, 'mergeClients')
3176
+ const targetRow = this.getClient(target.id)
3177
+ const at = now === undefined || now === null ? new Date().toISOString() : String(now)
3178
+ return this._transaction('IMMEDIATE', () => {
3179
+ const sourceProjects = this.db.prepare('SELECT * FROM projects WHERE client_id = ? ORDER BY name_norm, id').all(source.id).map(mapProjectRow)
3180
+ const targetProjects = this.db.prepare("SELECT * FROM projects WHERE client_id = ? AND status = 'active' AND deleted_at IS NULL").all(target.id).map(mapProjectRow)
3181
+ const byName = new Map(targetProjects.map((project) => [project.nameNorm, project]))
3182
+ let movedProjects = 0
3183
+ let mergedProjects = 0
3184
+ for (const project of sourceProjects) {
3185
+ const existing = byName.get(project.nameNorm)
3186
+ if (!existing) {
3187
+ this.db.prepare('UPDATE projects SET client_id = ?, updated_at = ? WHERE id = ?').run(target.id, at, project.id)
3188
+ movedProjects++
3189
+ } else {
3190
+ this.db.prepare('UPDATE matters SET project_id = ? WHERE project_id = ?').run(existing.id, project.id)
3191
+ this.db.prepare('UPDATE client_notes SET project_id = ? WHERE project_id = ?').run(existing.id, project.id)
3192
+ this.db.prepare("UPDATE projects SET status = 'archived', deleted_at = ?, updated_at = ? WHERE id = ?").run(at, at, project.id)
3193
+ mergedProjects++
3194
+ }
3195
+ }
3196
+ const movedMatters = Number(this.db.prepare('UPDATE matters SET client_id = ?, updated_at = ? WHERE client_id = ?').run(target.id, at, source.id).changes)
3197
+ const movedNotes = Number(this.db.prepare('UPDATE client_notes SET client_id = ? WHERE client_id = ?').run(target.id, source.id).changes)
3198
+ const movedDeliveries = Number(this.db.prepare('UPDATE deliveries SET client_id = ? WHERE client_id = ?').run(target.id, source.id).changes)
3199
+ this.db.prepare("UPDATE clients SET status = 'archived', deleted_at = COALESCE(deleted_at, ?), updated_at = ? WHERE id = ?").run(at, at, source.id)
3200
+ const taken = new Set()
3201
+ for (const identity of this._activeClientIdentities(target.id)) for (const norm of identity.norms.keys()) taken.add(norm)
3202
+ const aliases = targetRow.aliases.slice()
3203
+ const seen = new Set(aliases.map((entry) => normalizeClientName(String(entry))))
3204
+ let carriedAliases = 0
3205
+ for (const name of [source.name, ...source.aliases]) {
3206
+ if (typeof name !== 'string') continue
3207
+ const norm = normalizeClientName(name)
3208
+ if (!norm || norm === targetRow.nameNorm || seen.has(norm) || taken.has(norm)) continue
3209
+ aliases.push(name)
3210
+ seen.add(norm)
3211
+ carriedAliases++
3212
+ }
3213
+ if (carriedAliases) this.db.prepare('UPDATE clients SET aliases = ?, updated_at = ? WHERE id = ?').run(json(aliases), at, target.id)
3214
+ return {
3215
+ client: this.getClient(target.id),
3216
+ mergedFrom: source.id,
3217
+ movedMatters,
3218
+ movedProjects,
3219
+ mergedProjects,
3220
+ movedNotes,
3221
+ movedDeliveries,
3222
+ carriedAliases,
3223
+ }
3224
+ })
3225
+ }
3226
+
3227
+ // -------------------------------------------------------------------------
3228
+ // Projects (one client per project; a cross-client job is two projects).
3229
+ // -------------------------------------------------------------------------
3230
+
3231
+ /** Create a project under one live client. */
3232
+ addProject({ clientId, name, startedAt, dueAt, defaultMatterId, notes, status, id } = {}) {
3233
+ this._assertWritable('addProject')
3234
+ const client = this._clientForWrite(clientId, 'addProject')
3235
+ const displayName = validateDisplayName('project', name)
3236
+ const nameNorm = normalizeClientName(displayName)
3237
+ const projectStatus = validateEntityStatus('project', status)
3238
+ const projectId = id === undefined || id === null ? 'prj_' + randomUUID().replace(/-/g, '').slice(0, 16) : String(id).trim()
3239
+ if (!projectId) throw entityError('E_PROJECT_INVALID', 'project id must not be empty')
3240
+ if (this.getProject(projectId)) throw entityError('E_PROJECT_DUPLICATE', 'project id already exists: ' + projectId)
3241
+ let matterId = null
3242
+ if (defaultMatterId !== undefined && defaultMatterId !== null) {
3243
+ const matter = this.getMatter(String(defaultMatterId))
3244
+ if (!matter) throw entityError('E_MATTER_NOT_FOUND', 'unknown matter: ' + String(defaultMatterId), 'advisers matter ls')
3245
+ matterId = matter.id
3246
+ }
3247
+ const starts = normalizeOptionalDate('project', 'startedAt', startedAt)
3248
+ const ends = normalizeOptionalDate('project', 'dueAt', dueAt)
3249
+ const now = new Date().toISOString()
3250
+ try {
3251
+ this.db.prepare('INSERT INTO projects(id,client_id,name,name_norm,status,started_at,due_at,default_matter_id,notes,created_at,updated_at,deleted_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)')
3252
+ .run(projectId, client.id, displayName, nameNorm, projectStatus, starts, ends, matterId, normalizeOptionalText('project', 'notes', notes, 4000), now, now, projectStatus === 'archived' ? now : null)
3253
+ } catch (error) {
3254
+ if (/UNIQUE constraint failed/i.test(String(error?.message ?? error))) {
3255
+ throw entityError('E_PROJECT_DUPLICATE', 'this client already has an active project with this name', 'advisers project ls --client ' + client.id)
3256
+ }
3257
+ throw error
3258
+ }
3259
+ return this.getProject(projectId)
3260
+ }
3261
+
3262
+ /** One project by id (archived included; undefined when absent). */
3263
+ getProject(id) {
3264
+ const row = this.db.prepare('SELECT * FROM projects WHERE id = ?').get(String(id))
3265
+ return row ? mapProjectRow(row) : undefined
3266
+ }
3267
+
3268
+ /** Deterministic name lookup inside one client (active projects only). */
3269
+ findProjectByName(clientId, name) {
3270
+ const nameNorm = normalizeClientName(validateDisplayName('project', name))
3271
+ const row = this.db.prepare("SELECT * FROM projects WHERE client_id = ? AND name_norm = ? AND status = 'active' AND deleted_at IS NULL ORDER BY id LIMIT 1").get(String(clientId), nameNorm)
3272
+ return row ? mapProjectRow(row) : undefined
3273
+ }
3274
+
3275
+ /** List projects, optionally scoped to one client. */
3276
+ listProjects({ clientId, status = 'active', includeDeleted = false, limit = 100 } = {}) {
3277
+ const where = []
3278
+ const params = []
3279
+ if (includeDeleted !== true) where.push('deleted_at IS NULL')
3280
+ if (clientId !== undefined && clientId !== null) { where.push('client_id = ?'); params.push(String(clientId)) }
3281
+ if (status !== 'all') {
3282
+ const wanted = validateEntityStatus('project', status)
3283
+ where.push('status = ?')
3284
+ params.push(wanted)
3285
+ }
3286
+ const sql = 'SELECT * FROM projects' + (where.length ? ' WHERE ' + where.join(' AND ') : '') + ' ORDER BY client_id ASC, name_norm ASC, id ASC LIMIT ?'
3287
+ return this.db.prepare(sql).all(...params, normalizeRowLimit(limit, { def: 100, max: 1000 })).map(mapProjectRow)
3288
+ }
3289
+
3290
+ /** Update mutable project fields (rename re-checks the per-client uniqueness). */
3291
+ updateProject(id, patch = {}) {
3292
+ this._assertWritable('updateProject')
3293
+ const current = this.getProject(id)
3294
+ if (!current) throw entityError('E_PROJECT_NOT_FOUND', 'unknown project: ' + String(id))
3295
+ const allowed = ['name', 'status', 'startedAt', 'dueAt', 'defaultMatterId', 'notes']
3296
+ for (const field of Object.keys(patch)) {
3297
+ if (!allowed.includes(field)) throw new Error('unknown project field: ' + field)
3298
+ }
3299
+ const name = patch.name === undefined ? current.name : validateDisplayName('project', patch.name)
3300
+ const nameNorm = normalizeClientName(name)
3301
+ const status = patch.status === undefined ? current.status : validateEntityStatus('project', patch.status)
3302
+ const starts = patch.startedAt === undefined ? (current.startedAt ?? null) : normalizeOptionalDate('project', 'startedAt', patch.startedAt)
3303
+ const ends = patch.dueAt === undefined ? (current.dueAt ?? null) : normalizeOptionalDate('project', 'dueAt', patch.dueAt)
3304
+ const notes = patch.notes === undefined ? (current.notes ?? null) : normalizeOptionalText('project', 'notes', patch.notes, 4000)
3305
+ let matterId = current.defaultMatterId ?? null
3306
+ if (patch.defaultMatterId !== undefined) {
3307
+ matterId = patch.defaultMatterId === null ? null : String(patch.defaultMatterId)
3308
+ if (matterId !== null && !this.getMatter(matterId)) throw entityError('E_MATTER_NOT_FOUND', 'unknown matter: ' + matterId, 'advisers matter ls')
3309
+ }
3310
+ const now = new Date().toISOString()
3311
+ let deletedAt = current.deletedAt ?? null
3312
+ if (status === 'archived' && deletedAt === null) deletedAt = now
3313
+ if (status === 'active' && deletedAt !== null) deletedAt = null
3314
+ try {
3315
+ this.db.prepare('UPDATE projects SET name = ?, name_norm = ?, status = ?, started_at = ?, due_at = ?, default_matter_id = ?, notes = ?, updated_at = ?, deleted_at = ? WHERE id = ?')
3316
+ .run(name, nameNorm, status, starts, ends, matterId, notes, now, deletedAt, current.id)
3317
+ } catch (error) {
3318
+ if (/UNIQUE constraint failed/i.test(String(error?.message ?? error))) {
3319
+ throw entityError('E_PROJECT_DUPLICATE', 'this client already has an active project with this name', 'advisers project ls --client ' + current.clientId)
3320
+ }
3321
+ throw error
3322
+ }
3323
+ return this.getProject(current.id)
3324
+ }
3325
+
3326
+ /** Soft-delete one project (idempotent). */
3327
+ archiveProject(id, { now } = {}) {
3328
+ this._assertWritable('archiveProject')
3329
+ const current = this.getProject(id)
3330
+ if (!current) throw entityError('E_PROJECT_NOT_FOUND', 'unknown project: ' + String(id))
3331
+ const at = now === undefined || now === null ? new Date().toISOString() : String(now)
3332
+ this.db.prepare("UPDATE projects SET status = 'archived', deleted_at = COALESCE(deleted_at, ?), updated_at = ? WHERE id = ?").run(at, at, current.id)
3333
+ return this.getProject(current.id)
3334
+ }
3335
+
3336
+ // -------------------------------------------------------------------------
3337
+ // Client notes (the manual source of the derived timeline).
3338
+ // -------------------------------------------------------------------------
3339
+
3340
+ /** Resolve a project that must belong to the given client. */
3341
+ _projectForClient(projectId, clientId) {
3342
+ const project = this.getProject(String(projectId))
3343
+ if (!project) throw entityError('E_PROJECT_NOT_FOUND', 'unknown project: ' + String(projectId), 'advisers project ls')
3344
+ if (project.clientId !== clientId) throw entityError('E_PROJECT_CLIENT_MISMATCH', 'project ' + project.id + ' belongs to client ' + project.clientId)
3345
+ return project
3346
+ }
3347
+
3348
+ /**
3349
+ * Record one client note (phone call, meeting, decision, ...). The summary is
3350
+ * operator prose (<= 2000 chars); source is lineage only (kind/id/quote), so a
3351
+ * note can point at a delivery or matter without copying a file or a path.
3352
+ */
3353
+ addClientNote({ clientId, projectId, matterId, kind, at, summary, source, id } = {}) {
3354
+ this._assertWritable('addClientNote')
3355
+ const client = this._clientForWrite(clientId, 'addClientNote')
3356
+ const noteKind = kind === undefined || kind === null ? 'note' : String(kind)
3357
+ if (!CLIENT_NOTE_KINDS.includes(noteKind)) {
3358
+ throw entityError('E_CLIENT_NOTE_INVALID', 'unknown note kind: ' + noteKind, 'use one of ' + CLIENT_NOTE_KINDS.join(', '))
3359
+ }
3360
+ let resolvedProjectId = null
3361
+ if (projectId !== undefined && projectId !== null) resolvedProjectId = this._projectForClient(projectId, client.id).id
3362
+ let resolvedMatterId = null
3363
+ if (matterId !== undefined && matterId !== null) {
3364
+ const matter = this.getMatter(String(matterId))
3365
+ if (!matter) throw entityError('E_MATTER_NOT_FOUND', 'unknown matter: ' + String(matterId), 'advisers matter ls')
3366
+ if (matter.clientId != null && matter.clientId !== client.id) {
3367
+ throw entityError('E_MATTER_CLIENT_MISMATCH', 'matter ' + matter.id + ' belongs to client ' + matter.clientId)
3368
+ }
3369
+ resolvedMatterId = matter.id
3370
+ if (resolvedProjectId === null && matter.projectId != null) resolvedProjectId = matter.projectId
3371
+ }
3372
+ if (typeof summary !== 'string' || !summary.trim()) throw entityError('E_CLIENT_NOTE_INVALID', 'summary is required')
3373
+ const text = summary.trim()
3374
+ if (text.length > 2000) throw entityError('E_CLIENT_NOTE_INVALID', 'summary must be at most 2000 characters')
3375
+ const noteAt = normalizeNoteInstant(at)
3376
+ const noteSource = validateNoteSource(source)
3377
+ const noteId = id === undefined || id === null ? 'note_' + randomUUID().replace(/-/g, '').slice(0, 16) : String(id).trim()
3378
+ if (!noteId) throw entityError('E_CLIENT_NOTE_INVALID', 'note id must not be empty')
3379
+ if (this.getClientNote(noteId)) throw entityError('E_CLIENT_NOTE_INVALID', 'note id already exists: ' + noteId)
3380
+ this.db.prepare('INSERT INTO client_notes(id,client_id,project_id,matter_id,kind,at,summary,source,created_at,deleted_at) VALUES(?,?,?,?,?,?,?,?,?,?)')
3381
+ .run(noteId, client.id, resolvedProjectId, resolvedMatterId, noteKind, noteAt, text, noteSource, new Date().toISOString(), null)
3382
+ return this.getClientNote(noteId)
3383
+ }
3384
+
3385
+ /** One note by id (deleted notes included; undefined when absent). */
3386
+ getClientNote(id) {
3387
+ const row = this.db.prepare('SELECT * FROM client_notes WHERE id = ?').get(String(id))
3388
+ return row ? mapClientNoteRow(row) : undefined
3389
+ }
3390
+
3391
+ /**
3392
+ * Notes of one client, newest event first (at DESC, then rowid DESC so notes
3393
+ * written in one batch keep their order). Soft-deleted notes are hidden by
3394
+ * default.
3395
+ */
3396
+ listClientNotes({ clientId, projectId, matterId, includeDeleted = false, limit = 50 } = {}) {
3397
+ const where = []
3398
+ const params = []
3399
+ if (clientId !== undefined && clientId !== null) { where.push('client_id = ?'); params.push(String(clientId)) }
3400
+ if (projectId !== undefined && projectId !== null) { where.push('project_id = ?'); params.push(String(projectId)) }
3401
+ if (matterId !== undefined && matterId !== null) { where.push('matter_id = ?'); params.push(String(matterId)) }
3402
+ if (includeDeleted !== true) where.push('deleted_at IS NULL')
3403
+ const sql = 'SELECT * FROM client_notes' + (where.length ? ' WHERE ' + where.join(' AND ') : '') + ' ORDER BY at DESC, rowid DESC LIMIT ?'
3404
+ return this.db.prepare(sql).all(...params, normalizeRowLimit(limit, { def: 50, max: 500 })).map(mapClientNoteRow)
3405
+ }
3406
+
3407
+ /** Update one note; the client ownership cannot be changed, the project can. */
3408
+ updateClientNote(id, patch = {}) {
3409
+ this._assertWritable('updateClientNote')
3410
+ const current = this.getClientNote(id)
3411
+ if (!current) throw entityError('E_CLIENT_NOTE_NOT_FOUND', 'unknown note: ' + String(id))
3412
+ const allowed = ['kind', 'at', 'summary', 'projectId', 'matterId']
3413
+ for (const field of Object.keys(patch)) {
3414
+ if (!allowed.includes(field)) throw new Error('unknown client note field: ' + field)
3415
+ }
3416
+ const kind = patch.kind === undefined ? current.kind : String(patch.kind)
3417
+ if (!CLIENT_NOTE_KINDS.includes(kind)) throw entityError('E_CLIENT_NOTE_INVALID', 'unknown note kind: ' + kind, 'use one of ' + CLIENT_NOTE_KINDS.join(', '))
3418
+ const at = patch.at === undefined ? current.at : normalizeNoteInstant(patch.at)
3419
+ let summary = current.summary
3420
+ if (patch.summary !== undefined) {
3421
+ if (typeof patch.summary !== 'string' || !patch.summary.trim()) throw entityError('E_CLIENT_NOTE_INVALID', 'summary is required')
3422
+ summary = patch.summary.trim()
3423
+ if (summary.length > 2000) throw entityError('E_CLIENT_NOTE_INVALID', 'summary must be at most 2000 characters')
3424
+ }
3425
+ let projectId = current.projectId ?? null
3426
+ if (patch.projectId !== undefined) projectId = patch.projectId === null ? null : this._projectForClient(patch.projectId, current.clientId).id
3427
+ let matterId = current.matterId ?? null
3428
+ if (patch.matterId !== undefined) {
3429
+ if (patch.matterId === null) matterId = null
3430
+ else {
3431
+ const matter = this.getMatter(String(patch.matterId))
3432
+ if (!matter) throw entityError('E_MATTER_NOT_FOUND', 'unknown matter: ' + String(patch.matterId), 'advisers matter ls')
3433
+ if (matter.clientId != null && matter.clientId !== current.clientId) throw entityError('E_MATTER_CLIENT_MISMATCH', 'matter ' + matter.id + ' belongs to client ' + matter.clientId)
3434
+ matterId = matter.id
3435
+ }
3436
+ }
3437
+ this.db.prepare('UPDATE client_notes SET kind = ?, at = ?, summary = ?, project_id = ?, matter_id = ? WHERE id = ?').run(kind, at, summary, projectId, matterId, current.id)
3438
+ return this.getClientNote(current.id)
3439
+ }
3440
+
3441
+ /** Soft-delete one note (idempotent; never a hard delete of user data). */
3442
+ deleteClientNote(id, { now } = {}) {
3443
+ this._assertWritable('deleteClientNote')
3444
+ const current = this.getClientNote(id)
3445
+ if (!current) throw entityError('E_CLIENT_NOTE_NOT_FOUND', 'unknown note: ' + String(id))
3446
+ if (current.deletedAt) return current
3447
+ const at = now === undefined || now === null ? new Date().toISOString() : String(now)
3448
+ this.db.prepare('UPDATE client_notes SET deleted_at = ? WHERE id = ?').run(at, current.id)
3449
+ return this.getClientNote(current.id)
3450
+ }
3451
+
3452
+ // -------------------------------------------------------------------------
3453
+ // Matter ownership (client/project) + the derived timeline sources.
3454
+ // -------------------------------------------------------------------------
3455
+
3456
+ /**
3457
+ * Point one matter at a client (and optionally one of that client's
3458
+ * projects), or unlink it with both null. Only this column pair is written:
3459
+ * commitments/facts stay matter-scoped, so re-linking can never leave two
3460
+ * copies of the truth behind.
3461
+ */
3462
+ setMatterClient(matterId, { clientId, projectId } = {}) {
3463
+ this._assertWritable('setMatterClient')
3464
+ const matter = this.getMatter(String(matterId))
3465
+ if (!matter) throw entityError('E_MATTER_NOT_FOUND', 'unknown matter: ' + String(matterId), 'advisers matter ls')
3466
+ let resolvedClientId = clientId === undefined || clientId === null ? null : clientId
3467
+ let resolvedProjectId = projectId === undefined || projectId === null ? null : projectId
3468
+ if (resolvedClientId === null && resolvedProjectId !== null) {
3469
+ throw entityError('E_PROJECT_CLIENT_MISMATCH', 'projectId requires clientId; a project belongs to exactly one client')
3470
+ }
3471
+ if (resolvedClientId !== null) {
3472
+ const client = this._clientForWrite(resolvedClientId, 'setMatterClient')
3473
+ resolvedClientId = client.id
3474
+ if (resolvedProjectId !== null) {
3475
+ const project = this._projectForClient(resolvedProjectId, resolvedClientId)
3476
+ if (project.status !== 'active' || project.deletedAt) throw entityError('E_PROJECT_ARCHIVED', 'project is archived: ' + project.id, 'advisers project ls')
3477
+ resolvedProjectId = project.id
3478
+ }
3479
+ }
3480
+ this.db.prepare('UPDATE matters SET client_id = ?, project_id = ?, updated_at = ? WHERE id = ?')
3481
+ .run(resolvedClientId, resolvedProjectId, new Date().toISOString(), matter.id)
3482
+ return this.getMatter(matter.id)
3483
+ }
3484
+
3485
+ /** Every matter owned by one client, in insertion order (archived included). */
3486
+ listMattersByClient(clientId, { status } = {}) {
3487
+ const where = ['client_id = ?']
3488
+ const params = [String(clientId)]
3489
+ if (status !== undefined && status !== null) { where.push('status = ?'); params.push(String(status)) }
3490
+ return this.db.prepare('SELECT * FROM matters WHERE ' + where.join(' AND ') + ' ORDER BY rowid').all(...params).map(mapMatterRow)
3491
+ }
3492
+
3493
+ /** Every matter owned by one project, in insertion order. */
3494
+ listMattersByProject(projectId, { status } = {}) {
3495
+ const where = ['project_id = ?']
3496
+ const params = [String(projectId)]
3497
+ if (status !== undefined && status !== null) { where.push('status = ?'); params.push(String(status)) }
3498
+ return this.db.prepare('SELECT * FROM matters WHERE ' + where.join(' AND ') + ' ORDER BY rowid').all(...params).map(mapMatterRow)
3499
+ }
3500
+
3501
+ /** Matters that are not linked to any client (the honest "unclassified" view). */
3502
+ listUnclassifiedMatters({ limit = 100 } = {}) {
3503
+ return this.db.prepare('SELECT * FROM matters WHERE client_id IS NULL ORDER BY rowid LIMIT ?').all(normalizeRowLimit(limit, { def: 100, max: 1000 })).map(mapMatterRow)
3504
+ }
3505
+
3506
+ /**
3507
+ * One read snapshot of everything a customer timeline is derived from.
3508
+ *
3509
+ * The caller merges these rows with packages/core/src/customer.ts
3510
+ * (deriveClientTimeline). Every query is scoped by the client's own matters,
3511
+ * so two clients can never see each other's rows: no full-table read followed
3512
+ * by an in-memory filter happens in this path. Limits bound each source (the
3513
+ * derivation applies the display limit afterwards).
3514
+ */
3515
+ clientTimelineSources(clientId, { limit = 200 } = {}) {
3516
+ const client = this.getClient(String(clientId))
3517
+ if (!client) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + String(clientId), 'advisers client ls')
3518
+ const rowLimit = normalizeRowLimit(limit, { def: 200, max: 500 })
3519
+ const matters = this.db.prepare('SELECT * FROM matters WHERE client_id = ? ORDER BY rowid').all(client.id).map(mapMatterRow)
3520
+ const projects = this.db.prepare('SELECT * FROM projects WHERE client_id = ? ORDER BY name_norm ASC, id ASC').all(client.id).map(mapProjectRow)
3521
+ const matterIds = matters.map((matter) => matter.id)
3522
+ let commitments = []
3523
+ let deliveries = []
3524
+ if (matterIds.length) {
3525
+ const placeholders = matterIds.map(() => '?').join(',')
3526
+ commitments = this.db.prepare('SELECT * FROM commitments WHERE matter_id IN (' + placeholders + ') ORDER BY rowid DESC LIMIT ?')
3527
+ .all(...matterIds, rowLimit).map(mapCommitmentRow)
3528
+ deliveries = this.db.prepare('SELECT * FROM deliveries WHERE matter_id IN (' + placeholders + ') ORDER BY created_at DESC, rowid DESC LIMIT ?')
3529
+ .all(...matterIds, rowLimit).map(mapDeliveryRow)
3530
+ }
3531
+ const notes = this.db.prepare('SELECT * FROM client_notes WHERE client_id = ? AND deleted_at IS NULL ORDER BY at DESC, rowid DESC LIMIT ?')
3532
+ .all(client.id, rowLimit).map(mapClientNoteRow)
3533
+ return { client: client, projects: projects, matters: matters, commitments: commitments, deliveries: deliveries, notes: notes, limit: rowLimit }
3534
+ }
3535
+
3536
+ /**
3537
+ * Raw rows of the SQLite-only tables carried next to a ledger export.
3538
+ *
3539
+ * The snake_case raw row shape matches what export --all has always written,
3540
+ * and DATA_TABLES is the single list of tables so an export/import helper
3541
+ * cannot silently drop the v21 customer entities.
3542
+ */
3543
+ exportDataTables(tables = DATA_TABLES) {
3544
+ const data = {}
3545
+ for (const table of tables) {
3546
+ if (!DATA_TABLES.includes(table)) throw new Error('unknown export table: ' + table)
3547
+ data[table] = this.db.prepare('SELECT * FROM ' + table).all()
3548
+ }
3549
+ return data
3550
+ }
3551
+
2515
3552
  // -------------------------------------------------------------------------
2516
3553
  // Partial loading (P1-2, 0.2.2)
2517
3554
  //
@@ -2578,27 +3615,180 @@ CREATE TABLE IF NOT EXISTS task_runs (
2578
3615
  return matters
2579
3616
  }
2580
3617
 
2581
- loadFacts({ status, matterId, includeDeleted } = {}) {
3618
+ /**
3619
+ * Load one ledger table's rows.
3620
+ *
3621
+ * 0.3.0 P0-T1: two optional knobs keep the hot read paths off the TEMP
3622
+ * B-TREE. The v20 status-leading indexes (`idx_facts_status_deleted`,
3623
+ * `idx_commitments_status_due`) cannot satisfy `ORDER BY rowid` for a
3624
+ * status predicate, so SQLite sorted every matching row into a TEMP B-TREE
3625
+ * and spilled it to disk (pet-brief wrote 29 MB per run, today 5.6 MB).
3626
+ *
3627
+ * @param {object} [options]
3628
+ * @param {boolean} [options.validOnly] facts only: `expired_at IS NULL AND
3629
+ * deleted_at IS NULL`. With `status` also set this is an index key prefix,
3630
+ * so rowid order comes from the index and no sort/spill happens.
3631
+ * @param {'rowid'|'natural'|'table'} [options.order='rowid'] commitments only:
3632
+ * 'rowid' keeps the historical ORDER BY rowid (may sort); 'natural' leaves
3633
+ * the order to the plan (index order, no sort); 'table' reads the table
3634
+ * without an index (rowid order, no sort) -- the cheapest way to keep
3635
+ * insertion order when a predicate matches a large fraction of the table.
3636
+ */
3637
+ loadFacts({ status, matterId, includeDeleted, validOnly } = {}) {
2582
3638
  const where = []
2583
3639
  const params = []
2584
3640
  if (status !== undefined) { where.push('status = ?'); params.push(status) }
2585
3641
  if (matterId !== undefined) { where.push('matter_id = ?'); params.push(matterId) }
2586
3642
  if (includeDeleted === false) where.push('deleted_at IS NULL')
3643
+ if (validOnly === true) {
3644
+ where.push('expired_at IS NULL')
3645
+ if (includeDeleted !== true) where.push('deleted_at IS NULL')
3646
+ }
2587
3647
  const facts = this._selectRows('facts', where, params, ' ORDER BY rowid').map(mapFactRow)
2588
3648
  this._markLoadedRows('facts', facts)
2589
3649
  return facts
2590
3650
  }
2591
3651
 
2592
- loadCommitments({ status, matterId } = {}) {
3652
+ loadCommitments({ status, matterId, order = 'rowid' } = {}) {
2593
3653
  const where = []
2594
3654
  const params = []
2595
3655
  if (status !== undefined) { where.push('status = ?'); params.push(status) }
2596
3656
  if (matterId !== undefined) { where.push('matter_id = ?'); params.push(matterId) }
2597
- const commitments = this._selectRows('commitments', where, params, ' ORDER BY rowid').map(mapCommitmentRow)
3657
+ const table = order === 'table' ? 'commitments NOT INDEXED' : 'commitments'
3658
+ const suffix = order === 'natural' || order === 'table' ? '' : ' ORDER BY rowid'
3659
+ const commitments = this._selectRows(table, where, params, suffix).map(mapCommitmentRow)
2598
3660
  this._markLoadedRows('commitments', commitments)
2599
3661
  return commitments
2600
3662
  }
2601
3663
 
3664
+ // -------------------------------------------------------------------------
3665
+ // 0.3.0 P0-T2: narrow read projections (2026-11-20).
3666
+ //
3667
+ // The 0.2.x views paid two costs these projections remove: mapping whole
3668
+ // entities (JSON.parse of evidence / reminder_offsets) for rows a view only
3669
+ // counts, and ORDER BY rowid after a status predicate (TEMP B-TREE spill,
3670
+ // see P0-T1 above). Each projection returns exactly the columns its view
3671
+ // reads, in table-scan order (= rowid order): a NOT INDEXED scan is
3672
+ // sequential, so it keeps the historical array order without a sort and is
3673
+ // faster than 66k index -> table lookups at 200k rows (40 ms vs 100-120 ms).
3674
+ //
3675
+ // Only status predicates are pushed to SQL. Every due-date comparison stays
3676
+ // in JS: due_at is TEXT with mixed formats (date-only / no zone / Z /
3677
+ // offsets) and JS Date.parse semantics differ from SQLite julianday() for
3678
+ // the no-zone forms, so SQL-side date filtering would change behaviour.
3679
+ // These helpers are read-only and never feed save().
3680
+ // -------------------------------------------------------------------------
3681
+
3682
+ /**
3683
+ * Run a read-only projection and map rows positionally.
3684
+ * setReturnArrays skips building one object per row inside node:sqlite
3685
+ * (~25% faster at 66k rows) and the view maps only the columns it needs.
3686
+ */
3687
+ _project(sql, params, map) {
3688
+ const statement = this.db.prepare(sql)
3689
+ if (typeof statement.setReturnArrays === 'function') statement.setReturnArrays(true)
3690
+ return statement.all(...params).map(map)
3691
+ }
3692
+
3693
+ /** today (human view): same minimal open-commitment rows as before. */
3694
+ projectOpenCommitmentsForToday() {
3695
+ return this._project(
3696
+ "SELECT id, debtor, creditor, action, due_at FROM commitments NOT INDEXED WHERE status = 'open'",
3697
+ [],
3698
+ (row) => ({ id: row[0], debtor: row[1], creditor: row[2], action: row[3], dueAt: row[4] ?? undefined }),
3699
+ )
3700
+ }
3701
+
3702
+ /**
3703
+ * remind / tui: every row buildReminders can turn into a reminder (not
3704
+ * done/dropped, has a due_at). The due-date test itself stays in JS.
3705
+ */
3706
+ projectCommitmentsForReminders({ includeUndated = false } = {}) {
3707
+ return this._project(
3708
+ includeUndated
3709
+ ? "SELECT id, status, creditor, action, due_at, reminder_offsets FROM commitments NOT INDEXED WHERE status NOT IN ('done','dropped')"
3710
+ : "SELECT id, status, creditor, action, due_at, reminder_offsets FROM commitments NOT INDEXED WHERE status NOT IN ('done','dropped') AND due_at IS NOT NULL",
3711
+ [],
3712
+ (row) => {
3713
+ const offsets = row[5] == null ? null : parse(row[5], null)
3714
+ return {
3715
+ id: row[0], status: row[1], creditor: row[2], action: row[3], dueAt: row[4],
3716
+ ...(Array.isArray(offsets) ? { reminderOffsets: offsets } : {}),
3717
+ }
3718
+ },
3719
+ )
3720
+ }
3721
+
3722
+ /** digest: the two statuses buildDigest reads, in rowid order. */
3723
+ projectCommitmentsForDigest() {
3724
+ return this._project(
3725
+ "SELECT status, action, due_at, done_at FROM commitments NOT INDEXED WHERE status IN ('open','done')",
3726
+ [],
3727
+ (row) => ({ status: row[0], action: row[1], dueAt: row[2] ?? undefined, doneAt: row[3] ?? undefined }),
3728
+ )
3729
+ }
3730
+
3731
+ /**
3732
+ * pet-brief: open commitments, with hasEvidence computed in SQL.
3733
+ *
3734
+ * confidenceOfCommitment() only asks whether the parsed evidence array is
3735
+ * non-empty, so the projection answers it without shipping 66k evidence
3736
+ * JSON strings to JS. The CASE mirrors mapCommitmentRow's JSON.parse +
3737
+ * Array.isArray semantics exactly, including corrupt JSON (json_valid=0 ->
3738
+ * parse falls back to [] -> no evidence).
3739
+ */
3740
+ projectCommitmentsForPetBrief() {
3741
+ return this._project(
3742
+ "SELECT id, matter_id, creditor, action, due_at, CASE WHEN json_valid(evidence) THEN (CASE WHEN json_type(evidence) = 'array' AND json_array_length(evidence) > 0 THEN 1 ELSE 0 END) ELSE 0 END FROM commitments NOT INDEXED WHERE status = 'open'",
3743
+ [],
3744
+ (row) => ({
3745
+ id: row[0], matterId: row[1], creditor: row[2], action: row[3],
3746
+ dueAt: row[4] ?? undefined, status: 'open', hasEvidence: row[5] === 1,
3747
+ }),
3748
+ )
3749
+ }
3750
+
3751
+ /**
3752
+ * pet-brief facts: the top-N confirmed facts by confidence that buildPetBrief
3753
+ * would sort and slice to. matterIds restricts to the public matters (a
3754
+ * matter-less fact is always public, matching buildPetBrief).
3755
+ */
3756
+ projectFactsForPetBrief({ limit = 10, minConfidence = 0.7, matterIds = null } = {}) {
3757
+ // listFacts() semantics: confirmed + not expired + not deleted. buildPetBrief
3758
+ // only ever sees those rows, so the projection must filter them in SQL or an
3759
+ // expired fact could displace a live one in the top-N.
3760
+ const where = ["status = 'confirmed'", 'expired_at IS NULL', 'deleted_at IS NULL', 'confidence >= ?']
3761
+ const params = [minConfidence]
3762
+ if (Array.isArray(matterIds)) {
3763
+ if (matterIds.length) {
3764
+ where.push('(matter_id IS NULL OR matter_id IN (' + matterIds.map(() => '?').join(',') + '))')
3765
+ params.push(...matterIds)
3766
+ } else {
3767
+ where.push('matter_id IS NULL')
3768
+ }
3769
+ }
3770
+ params.push(Math.max(1, Math.trunc(limit)))
3771
+ return this._project(
3772
+ 'SELECT id, matter_id, subject, predicate, object, confidence FROM facts WHERE ' + where.join(' AND ') + ' ORDER BY confidence DESC, id LIMIT ?',
3773
+ params,
3774
+ (row) => ({ id: row[0], matterId: row[1] ?? undefined, subject: row[2], predicate: row[3], object: row[4], confidence: row[5] }),
3775
+ )
3776
+ }
3777
+
3778
+ /** pet-brief redactor candidates: subjects of every fact listFacts() returns. */
3779
+ projectFactSubjectCandidates() {
3780
+ return this._project(
3781
+ "SELECT subject FROM facts NOT INDEXED WHERE status = 'confirmed' AND expired_at IS NULL AND deleted_at IS NULL",
3782
+ [],
3783
+ (row) => row[0],
3784
+ )
3785
+ }
3786
+
3787
+ /** pet-brief redactor candidates: every commitment's creditor, all statuses. */
3788
+ projectCommitmentCreditorCandidates() {
3789
+ return this._project('SELECT DISTINCT creditor FROM commitments', [], (row) => row[0])
3790
+ }
3791
+
2602
3792
  loadPreferences({ status, kind } = {}) {
2603
3793
  const where = []
2604
3794
  const params = []
@@ -2767,22 +3957,22 @@ CREATE TABLE IF NOT EXISTS task_runs (
2767
3957
  // direct library use (e.g. importing or seeding a ledger).
2768
3958
  for (const [table] of LEDGER_TABLES) db.exec(`DELETE FROM ${table}`)
2769
3959
  }
2770
- const m = db.prepare('INSERT OR REPLACE INTO matters VALUES (?,?,?,?,?,?,?,?,?,?,?)')
3960
+ const m = db.prepare('INSERT OR REPLACE INTO matters(id,title,status,domain,secrecy,summary,participants,deadlines,open_questions,created_at,updated_at,client_id,project_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)')
2771
3961
  for (const x of snapshot.matters ?? []) {
2772
- m.run(x.id, x.title, x.status, x.domain, x.secrecy, x.summary ?? null, json(x.participants), json(x.deadlines), json(x.openQuestions), x.createdAt, x.updatedAt)
3962
+ m.run(x.id, x.title, x.status, x.domain, x.secrecy, x.summary ?? null, json(x.participants), json(x.deadlines), json(x.openQuestions), x.createdAt, x.updatedAt, x.clientId ?? null, x.projectId ?? null)
2773
3963
  }
2774
3964
  const f = db.prepare(`INSERT OR REPLACE INTO facts(id,matter_id,subject,predicate,object,recorded_at,expired_at,authority,confidence,source,evidence,status,valid_from,valid_to,supersedes,superseded_by,shadowed_by,last_seen_at,deleted_at,deleted_reason)
2775
3965
  VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`)
2776
3966
  for (const x of snapshot.facts ?? []) {
2777
3967
  f.run(x.id, x.matterId ?? null, x.subject, x.predicate, x.object, x.recordedAt, x.expiredAt ?? null, x.authority, x.confidence, x.source ? json(x.source) : null, x.evidence ? json(x.evidence) : null, x.status, x.validFrom ?? null, x.validTo ?? null, x.supersedes ?? null, x.supersededBy ?? null, x.shadowedBy ?? null, x.lastSeenAt ?? null, x.deletedAt ?? null, x.deletedReason ?? null)
2778
3968
  }
2779
- const c = db.prepare(`INSERT OR REPLACE INTO commitments(id,matter_id,debtor,creditor,action,due_at,timezone,status,evidence,capability,done_at,reminder_offsets)
2780
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`)
3969
+ const c = db.prepare(`INSERT OR REPLACE INTO commitments(id,matter_id,debtor,creditor,action,due_at,timezone,status,evidence,capability,done_at,reminder_offsets,created_at)
3970
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`)
2781
3971
  for (const x of snapshot.commitments ?? []) {
2782
3972
  // A missing/undefined list stays NULL so a round-trip keeps the pre-0.2.0
2783
3973
  // "no field" shape; an explicit [] is preserved as its own value.
2784
3974
  const reminderOffsets = Array.isArray(x.reminderOffsets) ? JSON.stringify(x.reminderOffsets) : null
2785
- c.run(x.id, x.matterId, x.debtor, x.creditor, x.action, x.dueAt ?? null, x.timezone, x.status, json(x.evidence), x.capability, x.doneAt ?? null, reminderOffsets)
3975
+ c.run(x.id, x.matterId, x.debtor, x.creditor, x.action, x.dueAt ?? null, x.timezone, x.status, json(x.evidence), x.capability, x.doneAt ?? null, reminderOffsets, x.createdAt ?? null)
2786
3976
  }
2787
3977
  const p = db.prepare('INSERT OR REPLACE INTO preferences VALUES (?,?,?,?,?,?,?,?,?,?,?,?)')
2788
3978
  for (const x of snapshot.preferences ?? []) {