@chenhw7/dsh-memory 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +70 -20
  3. package/README.zh.md +70 -20
  4. package/cordis.patch.yml +11 -4
  5. package/lib/benchmark/index.d.ts +1 -1
  6. package/lib/benchmark/index.d.ts.map +1 -1
  7. package/lib/client/index.js +388 -58
  8. package/lib/context/index.d.ts +93 -18
  9. package/lib/context/index.d.ts.map +1 -1
  10. package/lib/context/index.js +331 -71
  11. package/lib/context/index.js.map +1 -1
  12. package/lib/context/policy.d.ts +72 -11
  13. package/lib/context/policy.d.ts.map +1 -1
  14. package/lib/context/policy.js +250 -16
  15. package/lib/context/policy.js.map +1 -1
  16. package/lib/identity/index.d.ts +74 -0
  17. package/lib/identity/index.d.ts.map +1 -0
  18. package/lib/identity/index.js +150 -0
  19. package/lib/identity/index.js.map +1 -0
  20. package/lib/identity/seeds.d.ts +52 -0
  21. package/lib/identity/seeds.d.ts.map +1 -0
  22. package/lib/identity/seeds.js +130 -0
  23. package/lib/identity/seeds.js.map +1 -0
  24. package/lib/identity/settings.d.ts +32 -0
  25. package/lib/identity/settings.d.ts.map +1 -0
  26. package/lib/identity/settings.js +33 -0
  27. package/lib/identity/settings.js.map +1 -0
  28. package/lib/index.d.ts +53 -3
  29. package/lib/index.d.ts.map +1 -1
  30. package/lib/index.js +62 -1
  31. package/lib/index.js.map +1 -1
  32. package/lib/notes/index.d.ts +5 -2
  33. package/lib/notes/index.d.ts.map +1 -1
  34. package/lib/notes/index.js +26 -14
  35. package/lib/notes/index.js.map +1 -1
  36. package/lib/notes/render.d.ts +15 -3
  37. package/lib/notes/render.d.ts.map +1 -1
  38. package/lib/notes/render.js +110 -27
  39. package/lib/notes/render.js.map +1 -1
  40. package/lib/notes/settings.d.ts +27 -14
  41. package/lib/notes/settings.d.ts.map +1 -1
  42. package/lib/notes/settings.js +42 -13
  43. package/lib/notes/settings.js.map +1 -1
  44. package/lib/remote/index.d.ts +83 -1
  45. package/lib/remote/index.d.ts.map +1 -1
  46. package/lib/remote/index.js +93 -2
  47. package/lib/remote/index.js.map +1 -1
  48. package/lib/remote/typert.remote-client.d.ts +29 -1
  49. package/lib/remote/typert.remote-client.js +19 -0
  50. package/lib/remote/types.d.ts +1 -1
  51. package/lib/remote/types.d.ts.map +1 -1
  52. package/lib/review/extract.d.ts +12 -1
  53. package/lib/review/extract.d.ts.map +1 -1
  54. package/lib/review/extract.js +72 -2
  55. package/lib/review/extract.js.map +1 -1
  56. package/lib/store/identity-util.d.ts +12 -0
  57. package/lib/store/identity-util.d.ts.map +1 -0
  58. package/lib/store/identity-util.js +19 -0
  59. package/lib/store/identity-util.js.map +1 -0
  60. package/lib/store/index.d.ts +64 -13
  61. package/lib/store/index.d.ts.map +1 -1
  62. package/lib/store/index.js +262 -28
  63. package/lib/store/index.js.map +1 -1
  64. package/lib/store/sqlite.d.ts +24 -7
  65. package/lib/store/sqlite.d.ts.map +1 -1
  66. package/lib/store/sqlite.js +181 -13
  67. package/lib/store/sqlite.js.map +1 -1
  68. package/lib/tool/index.d.ts +4 -11
  69. package/lib/tool/index.d.ts.map +1 -1
  70. package/lib/tool/index.js +117 -3
  71. package/lib/tool/index.js.map +1 -1
  72. package/lib/types.d.ts +90 -2
  73. package/lib/types.d.ts.map +1 -1
  74. package/package.json +5 -1
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * storage-domain provider for the long-term memory store. Opens a `memory`
3
- * domain with four tables (`entries` keyed by `MemoryId`, `audit`, and
4
- * `suggestions` for the review queue, `meta` for subsystem state rows) and
5
- * implements the {@link MemoryStore} abstract service against them. Reads are
3
+ * domain with six tables (`entries` keyed by `MemoryId`, `audit`, and
4
+ * `suggestions` for the review queue, `meta` for subsystem state rows,
5
+ * `identity` and `identityHistory` for the identity layer's self-documents)
6
+ * and implements the {@link MemoryStore} abstract service against them. Reads are
6
7
  * synchronous from
7
8
  * the domain's authoritative in-memory state; writes serialize on the domain's
8
9
  * write chain and reach the backend before updating memory.
@@ -17,6 +18,7 @@ import z from '@deepseek-ai/schemastery';
17
18
  import { z as zod } from 'zod';
18
19
  import { MemoryStore, MemoryId, AuditId, SuggestionId, scanContent, validateProjectScope, validateContent } from '../index.js';
19
20
  import { Bm25Index, tokenizeForSearch, buildCorpusStats, buildCorpusStatsFromTokens, uniqueTokens, weightedOverlapSimilarity } from './bm25.js';
21
+ import { nextIdentityRecord } from './identity-util.js';
20
22
  import { SqliteMemoryStore, SQLITE_MIGRATION_MARKER } from './sqlite.js';
21
23
  import { CrossProcessGuard, DEFAULT_CROSS_PROCESS_PROBE_MS, EMPTY_OWNER, currentBootOwner, mediumOwnerReader, mediumGoodbyeWriter, ownerStampSchema, } from './cross-process.js';
22
24
  /** Zod schema for one memory entry record on the durable medium. */
@@ -61,6 +63,7 @@ const suggestionSchema = zod.object({
61
63
  content: zod.string(),
62
64
  summary: zod.string().optional(),
63
65
  projectName: zod.string().optional(),
66
+ identityKind: zod.enum(['soul', 'user']).optional(),
64
67
  hits: zod.number(),
65
68
  firstSeenAt: zod.number(),
66
69
  lastSeenAt: zod.number(),
@@ -80,17 +83,35 @@ const metaRecordSchema = zod.looseObject({
80
83
  value: zod.string().optional(),
81
84
  updatedAt: zod.number().optional(),
82
85
  });
86
+ /** Zod schema for the current record of one identity document. */
87
+ const identityRecordSchema = zod.object({
88
+ kind: zod.enum(['soul', 'user']),
89
+ content: zod.string(),
90
+ version: zod.number(),
91
+ updatedAt: zod.number(),
92
+ seedVersion: zod.number(),
93
+ });
94
+ /** Zod schema for one identity-document version snapshot (the identity audit surface). */
95
+ const identityHistorySchema = zod.object({
96
+ kind: zod.enum(['soul', 'user']),
97
+ version: zod.number(),
98
+ content: zod.string(),
99
+ ts: zod.number(),
100
+ source: zod.enum(['seed', 'tool', 'ui']),
101
+ sessionId: zod.string().optional(),
102
+ });
83
103
  /**
84
104
  * The memory domain spec: `entries` (memory records keyed by id) plus `audit`
85
105
  * (mutation audit trail) plus `suggestions` (P1-1 pending-review queue) plus
86
106
  * `meta` (subsystem state rows: consolidation progress, migration markers),
87
- * plus a global singleton carrying the single-writer owner stamp (P3
88
- * cross-process detection). Domain version stays at 0 — all four later
89
- * additions are forward-compatible: storage-json reads only declared tables
90
- * and initializes any absent table as an empty map, and a medium whose global
91
- * slot was never written reads as `null`, which the domain replaces with the
92
- * spec's `initial` without materializing it, so existing v0 media reopen
93
- * without migration.
107
+ * plus `identity`/`identityHistory` (the identity layer's self-documents and
108
+ * their version snapshots), plus a global singleton carrying the single-writer
109
+ * owner stamp (P3 cross-process detection). Domain version stays at 0 — all
110
+ * later additions are forward-compatible: storage-json reads only declared
111
+ * tables and initializes any absent table as an empty map, and a medium whose
112
+ * global slot was never written reads as `null`, which the domain replaces
113
+ * with the spec's `initial` without materializing it, so existing v0 media
114
+ * reopen without migration.
94
115
  *
95
116
  * The stamp and meta-record schemas accept extra keys on purpose
96
117
  * (`looseObject`): the medium holds both as opaque JSON, and a future
@@ -109,6 +130,8 @@ export const memoryDomainSpec = defineDomain({
109
130
  audit: domainTable(auditEntrySchema),
110
131
  suggestions: domainTable(suggestionSchema),
111
132
  meta: domainTable(metaRecordSchema),
133
+ identity: domainTable(identityRecordSchema),
134
+ identity_history: domainTable(identityHistorySchema),
112
135
  },
113
136
  });
114
137
  /**
@@ -139,6 +162,13 @@ const DEFAULT_ENTRIES_CAP = 500;
139
162
  * lowest-signal rows first: fewest hits, then oldest `lastSeenAt`.
140
163
  */
141
164
  const DEFAULT_SUGGESTION_CAP = 200;
165
+ /**
166
+ * Maximum identity-history snapshots retained per document kind. Overflow
167
+ * evicts the oldest versions first; reverts therefore can only restore within
168
+ * this window. Bounded payload: one snapshot is at most the document budget
169
+ * (a few thousand chars), so 20 kinds' worth of history stays a small table.
170
+ */
171
+ const IDENTITY_HISTORY_CAP = 20;
142
172
  /**
143
173
  * IDF-weighted overlap above which two same-scope proposals count as the
144
174
  * same suggestion (re-observation, not a new row). Sits below the entry-dedup
@@ -197,6 +227,8 @@ export async function apply(ctx, config = { storage: 'host-medium', entriesCap:
197
227
  const audit = domain.table('audit');
198
228
  const suggestions = domain.table('suggestions');
199
229
  const meta = domain.table('meta');
230
+ const identity = domain.table('identity');
231
+ const identityHistory = domain.table('identity_history');
200
232
  // Backend selection (write-path rework Step 3.2): `sqlite` mounts the
201
233
  // plugin-owned memory.db instead of the domain store. The medium's
202
234
  // migration marker guards both directions — a sqlite boot over a
@@ -217,16 +249,38 @@ export async function apply(ctx, config = { storage: 'host-medium', entriesCap:
217
249
  // progress, not the migration record.
218
250
  const migrated = meta.get(SQLITE_MIGRATION_MARKER);
219
251
  const mediumEntries = [...entries.entries()].map(([, entry]) => entry);
220
- if (migrated === undefined && mediumEntries.length > 0) {
252
+ const mediumIdentity = [...identity.entries()].map(([, record]) => record);
253
+ if (migrated === undefined && (mediumEntries.length > 0 || mediumIdentity.length > 0)) {
221
254
  // One-time import: the medium holds data this database has never seen.
222
- sqlite.importFromDomain(mediumEntries, [...audit.entries()].map(([, record]) => record), [...suggestions.entries()].map(([, row]) => row));
255
+ sqlite.importFromDomain(mediumEntries, [...audit.entries()].map(([, record]) => record), [...suggestions.entries()].map(([, row]) => row), mediumIdentity, [...identityHistory.entries()].map(([, record]) => record));
256
+ // If a crash occurs after importFromDomain completes but before the medium is
257
+ // cleared, the next boot re-imports; this is safe because importFromDomain uses
258
+ // stable primary keys with INSERT OR REPLACE, making re-import idempotent.
259
+ // The imported rows are now memory.db's rows, so the medium's data
260
+ // tables clear before the marker lands. Left in place they would make
261
+ // the next sqlite boot trip the both-sides guard on its own leftovers
262
+ // — the clear-first order keeps every crash window benign: a boot
263
+ // between the two steps sees an empty, unmarked medium (no import to
264
+ // redo, no guard to refuse), while marker-first would strand data the
265
+ // guard must reject.
266
+ for (const key of [...entries.keys()])
267
+ await entries.delete(key);
268
+ for (const key of [...audit.keys()])
269
+ await audit.delete(key);
270
+ for (const key of [...suggestions.keys()])
271
+ await suggestions.delete(key);
272
+ for (const key of [...identity.keys()])
273
+ await identity.delete(key);
274
+ for (const key of [...identityHistory.keys()])
275
+ await identityHistory.delete(key);
223
276
  await meta.put(SQLITE_MIGRATION_MARKER, { key: 'medium', value: new Date().toISOString(), updatedAt: Date.now() });
224
- ctx.logger.warn(`dsh-memory: imported ${String(mediumEntries.length)} entries from memory.json into ${dbPath}`);
277
+ ctx.logger.warn(`dsh-memory: imported ${String(mediumEntries.length)} entries from memory.json into ${dbPath} and cleared the medium`);
225
278
  }
226
- else if (migrated !== undefined && mediumEntries.length > 0) {
279
+ else if (migrated !== undefined && (mediumEntries.length > 0 || mediumIdentity.length > 0)) {
227
280
  // Both sides hold data: the medium was written after the migration —
228
- // a second writer. Failing loud is the only safe answer.
229
- throw new Error('dsh-memory: storage: sqlite — the host medium holds entries but carries a migratedToSqlite marker; a host-medium process wrote memory.json after the migration. Reconcile the two stores by hand and remove the stale writes before restarting.');
281
+ // a second writer (the migrating boot itself leaves the medium's data
282
+ // tables empty). Failing loud is the only safe answer.
283
+ throw new Error('dsh-memory: storage: sqlite — the host medium holds data but carries a migratedToSqlite marker; a host-medium process wrote memory.json after the migration. Reconcile the two stores by hand and remove the stale writes before restarting.');
230
284
  }
231
285
  ctx.effect(() => async () => { sqlite.close(); });
232
286
  ctx.provide('memory', sqlite);
@@ -252,7 +306,7 @@ export async function apply(ctx, config = { storage: 'host-medium', entriesCap:
252
306
  const own = currentBootOwner();
253
307
  const mediumReader = resolveMediumReader(ctx);
254
308
  const mediumGoodbye = resolveMediumGoodbye(ctx, own.bootId);
255
- const store = new DomainMemoryStore(entries, audit, suggestions, meta, DEFAULT_AUDIT_CAP, DEFAULT_SUGGESTION_CAP, ctx.logger, config.entriesCap);
309
+ const store = new DomainMemoryStore(entries, audit, suggestions, meta, DEFAULT_AUDIT_CAP, DEFAULT_SUGGESTION_CAP, ctx.logger, config.entriesCap, { identity, identityHistory });
256
310
  const guard = new CrossProcessGuard(own, mediumReader, owner => domain.global.set(owner), (site, error) => store.reportFailure(site, error), undefined, mediumGoodbye);
257
311
  try {
258
312
  // Startup judgment + claim: judge the open-time global (loaded from the
@@ -347,6 +401,16 @@ function entryIndexTokens(entry) {
347
401
  ? contentTokens
348
402
  : [...contentTokens, ...tokenizeForSearch(entry.summary)];
349
403
  }
404
+ /**
405
+ * Filter one anchor list for storage: anchors first became a prompt surface
406
+ * (the digest's topic words), so each one passes the write-time scanner;
407
+ * violating (or empty) anchors drop silently — they are derived tokens, not
408
+ * the entry body, and losing one costs a topic word, never content. The
409
+ * load-time counterpart is `redactBlocked` in the digest builder.
410
+ */
411
+ function filterAnchors(anchors) {
412
+ return anchors.filter(anchor => anchor.length > 0 && scanContent(anchor).allowed);
413
+ }
350
414
  /**
351
415
  * MemoryStore implementation backed by a storage-domain KV table. Reads are
352
416
  * synchronous from memory; writes serialize on the domain chain. Every
@@ -358,6 +422,8 @@ export class DomainMemoryStore extends MemoryStore {
358
422
  audit;
359
423
  suggestions;
360
424
  meta;
425
+ identity;
426
+ identityHistory;
361
427
  auditCap;
362
428
  suggestionCap;
363
429
  entriesCap;
@@ -367,12 +433,14 @@ export class DomainMemoryStore extends MemoryStore {
367
433
  failureCounts = new Map();
368
434
  /** Last audit `seq` handed out; lazily initialized from the medium on first append. */
369
435
  auditSeq;
370
- constructor(entries, audit, suggestions, meta, auditCap = DEFAULT_AUDIT_CAP, suggestionCap = DEFAULT_SUGGESTION_CAP, failureLogger, entriesCap = DEFAULT_ENTRIES_CAP) {
436
+ constructor(entries, audit, suggestions, meta, auditCap = DEFAULT_AUDIT_CAP, suggestionCap = DEFAULT_SUGGESTION_CAP, failureLogger, entriesCap = DEFAULT_ENTRIES_CAP, identity) {
371
437
  super();
372
438
  this.entries = entries;
373
439
  this.audit = audit;
374
440
  this.suggestions = suggestions;
375
441
  this.meta = meta;
442
+ this.identity = identity?.identity;
443
+ this.identityHistory = identity?.identityHistory;
376
444
  this.auditCap = auditCap;
377
445
  this.suggestionCap = suggestionCap;
378
446
  this.entriesCap = entriesCap;
@@ -465,7 +533,7 @@ export class DomainMemoryStore extends MemoryStore {
465
533
  createdAt: now,
466
534
  updatedAt: now,
467
535
  ...clampImportance(input.importance),
468
- ...input.anchors !== undefined ? { anchors: input.anchors } : {},
536
+ ...input.anchors !== undefined ? { anchors: filterAnchors(input.anchors) } : {},
469
537
  };
470
538
  await this.entries.put(id, entry);
471
539
  await this.appendAudit('add', id, entry, input.source, input.sessionId);
@@ -514,8 +582,9 @@ export class DomainMemoryStore extends MemoryStore {
514
582
  // Only rewrite the field when the caller supplies one; `undefined`
515
583
  // keeps the stored importance (add-time assessment stands).
516
584
  ...clampImportance(input.importance),
517
- // Same absent-means-keep semantics for anchors.
518
- ...(input.anchors !== undefined ? { anchors: input.anchors } : {}),
585
+ // Same absent-means-keep semantics for anchors; supplied anchors are
586
+ // scanner-filtered (they are prompt-surface tokens, like at add time).
587
+ ...(input.anchors !== undefined ? { anchors: filterAnchors(input.anchors) } : {}),
519
588
  };
520
589
  const updated = input.summary === ''
521
590
  ? (() => { const { summary: _c, ...rest } = base; return rest; })()
@@ -598,9 +667,10 @@ export class DomainMemoryStore extends MemoryStore {
598
667
  // Fire-and-forget: stamp the returned entries with a recall timestamp
599
668
  // so the janitor can decay entries that have not been recalled recently.
600
669
  // Read-only consumers (management UI) opt out via recordRecall: false —
601
- // merely viewing entries must not rewrite their recall metadata.
670
+ // merely viewing entries must not rewrite their recall metadata. The
671
+ // auto-recall fence also opts out and stamps its own lightweight tier.
602
672
  if (query.recordRecall !== false)
603
- void this.stampRecalled(all.map(entry => entry.id));
673
+ void this.stampRecalled(all.map(entry => entry.id), 'tool');
604
674
  return { entries: all, total };
605
675
  }
606
676
  /**
@@ -612,9 +682,15 @@ export class DomainMemoryStore extends MemoryStore {
612
682
  * changed entry; entries already carrying this pass's timestamp and no
613
683
  * decay stamp are skipped without touching the chain. `updatedAt` is
614
684
  * intentionally left untouched: recalling is not mutating.
685
+ *
686
+ * The tier follows {@link RecallSource}: `'tool'` bumps `accessCount` (the
687
+ * deliberate-read signal eviction and ranking consume); `'fence'` stamps
688
+ * `lastRecalledAt` only — a BM25 query match is presentation, not use.
615
689
  * @param ids - the ids of the entries the caller surfaced to the model.
690
+ * @param source - the recall surface selecting the stamping tier.
616
691
  */
617
- async stampRecalled(ids) {
692
+ async stampRecalled(ids, source) {
693
+ const bumpAccess = source !== 'fence';
618
694
  const now = Date.now();
619
695
  for (const id of ids) {
620
696
  // Cheap pre-check on the synchronous snapshot: a stamp pass that would
@@ -632,7 +708,7 @@ export class DomainMemoryStore extends MemoryStore {
632
708
  return {
633
709
  ...rest,
634
710
  lastRecalledAt: now,
635
- accessCount: (rest.accessCount ?? 0) + 1,
711
+ ...(bumpAccess ? { accessCount: (rest.accessCount ?? 0) + 1 } : {}),
636
712
  };
637
713
  });
638
714
  }
@@ -651,11 +727,14 @@ export class DomainMemoryStore extends MemoryStore {
651
727
  * (e.g. `memory_get` / `memory_list` tool results). Fire-and-forget; never
652
728
  * throws into the caller. The base-class default is a no-op so providers
653
729
  * without recall tracking stay contract-conformant.
730
+ * @param ids - the ids of the entries surfaced.
731
+ * @param source - the recall surface selecting the stamping tier (see
732
+ * {@link stampRecalled}); defaults to the full `'tool'` stamp.
654
733
  */
655
- markRecalled(ids) {
734
+ markRecalled(ids, source = 'tool') {
656
735
  if (ids.length === 0)
657
736
  return;
658
- void this.stampRecalled(ids.filter(id => this.entries.get(id) !== undefined));
737
+ void this.stampRecalled(ids.filter(id => this.entries.get(id) !== undefined), source);
659
738
  }
660
739
  /**
661
740
  * Record usage hits on the given entries (write-path rework Step 2):
@@ -710,6 +789,11 @@ export class DomainMemoryStore extends MemoryStore {
710
789
  * @throws when the proposed content or summary fails validation or the scanner.
711
790
  */
712
791
  async observeSuggestion(input) {
792
+ // Identity proposals (confirm-mode identity_update) take their own queue
793
+ // path: dedup by document kind, not by scope/content overlap.
794
+ if (input.identityKind !== undefined) {
795
+ return this.observeIdentitySuggestion(input);
796
+ }
713
797
  validateProjectScope({ ...input, projectName: input.projectName ?? (input.targetEntryId !== undefined ? this.entries.get(input.targetEntryId)?.projectName : undefined) });
714
798
  validateContent(input.content);
715
799
  const scan = scanContent(input.content);
@@ -724,6 +808,7 @@ export class DomainMemoryStore extends MemoryStore {
724
808
  // Match against existing proposals: same target entry wins outright;
725
809
  // otherwise nearest-content in the same scope above the dup threshold.
726
810
  let matched;
811
+ const inputTokens = uniqueTokens(input.content);
727
812
  for (const [, suggestion] of this.suggestions.entries()) {
728
813
  if (input.targetEntryId !== undefined) {
729
814
  if (suggestion.targetEntryId === input.targetEntryId) {
@@ -732,13 +817,17 @@ export class DomainMemoryStore extends MemoryStore {
732
817
  }
733
818
  continue;
734
819
  }
820
+ // Identity rows never match entry proposals: their dedup dimension is
821
+ // the document kind, not scope/content overlap.
822
+ if (suggestion.identityKind !== undefined)
823
+ continue;
735
824
  if (suggestion.scope !== input.scope)
736
825
  continue;
737
826
  // The live queue is the corpus: at queue scale (≤ cap rows) rebuilding
738
827
  // the df table per row would be wasteful, but the queue is tiny — and
739
828
  // the table only needs building once per observe call, not per row.
740
829
  const stats = buildCorpusStats([input.content, suggestion.content]);
741
- const similarity = weightedOverlapSimilarity(stats, uniqueTokens(input.content), uniqueTokens(suggestion.content));
830
+ const similarity = weightedOverlapSimilarity(stats, inputTokens, uniqueTokens(suggestion.content));
742
831
  if (similarity > SUGGESTION_DUP_THRESHOLD) {
743
832
  matched = suggestion;
744
833
  break;
@@ -776,6 +865,51 @@ export class DomainMemoryStore extends MemoryStore {
776
865
  await this.trimSuggestions();
777
866
  return suggestion;
778
867
  }
868
+ /**
869
+ * The identity-proposal queue path (confirm-mode `identity_update`): the
870
+ * same scanner gates, dedup by document kind — one row per identity
871
+ * document, a repeated proposal bumps `hits` — and `scope` fixed at
872
+ * `'global'` (the identity layer is per-user global; the field exists for
873
+ * the durable row shape).
874
+ */
875
+ async observeIdentitySuggestion(input) {
876
+ validateContent(input.content);
877
+ const scan = scanContent(input.content);
878
+ if (!scan.allowed) {
879
+ throw new Error(`suggestion content rejected by scanner: ${scan.reasons.join('; ')}`);
880
+ }
881
+ const now = Date.now();
882
+ // Identity proposals dedup by kind alone (not content similarity like entry
883
+ // proposals): each identity kind has exactly one living document, so the
884
+ // latest proposal per kind always supersedes earlier ones.
885
+ for (const [, suggestion] of this.suggestions.entries()) {
886
+ if (suggestion.identityKind !== input.identityKind)
887
+ continue;
888
+ const improved = input.content.length > suggestion.content.length && input.content.includes(suggestion.content);
889
+ const updated = {
890
+ ...suggestion,
891
+ content: improved ? input.content : suggestion.content,
892
+ hits: suggestion.hits + 1,
893
+ lastSeenAt: now,
894
+ };
895
+ await this.suggestions.put(suggestion.id, updated);
896
+ return updated;
897
+ }
898
+ const suggestion = {
899
+ id: SuggestionId(),
900
+ scope: 'global',
901
+ content: input.content,
902
+ hits: 1,
903
+ firstSeenAt: now,
904
+ lastSeenAt: now,
905
+ source: input.source,
906
+ identityKind: input.identityKind,
907
+ ...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
908
+ };
909
+ await this.suggestions.put(suggestion.id, suggestion);
910
+ await this.trimSuggestions();
911
+ return suggestion;
912
+ }
779
913
  /**
780
914
  * List pending suggestions for the review UI: highest `hits` first (the
781
915
  * repeatedly-re-proposed signals float up), then most recently seen.
@@ -817,6 +951,14 @@ export class DomainMemoryStore extends MemoryStore {
817
951
  const summary = override?.summary !== undefined
818
952
  ? (override.summary.length > 0 ? override.summary : undefined)
819
953
  : suggestion.summary;
954
+ // Identity proposal: the human's yes rewrites the document through the
955
+ // identity write path (source 'ui' — the governance adoption). No memory
956
+ // entry is created, so the caller sees `undefined` on success.
957
+ if (suggestion.identityKind !== undefined) {
958
+ await this.updateIdentity(suggestion.identityKind, content, { source: 'ui' });
959
+ await this.suggestions.delete(id);
960
+ return undefined;
961
+ }
820
962
  let entry;
821
963
  if (suggestion.targetEntryId !== undefined && this.entries.get(suggestion.targetEntryId) !== undefined) {
822
964
  entry = await this.update(suggestion.targetEntryId, {
@@ -974,6 +1116,98 @@ export class DomainMemoryStore extends MemoryStore {
974
1116
  await this.appendAudit('update', id, updated, 'janitor', undefined);
975
1117
  return updated;
976
1118
  }
1119
+ // ─── Identity documents (the identity layer) ────────────────────────────────
1120
+ /** The identity tables, or a loud refusal — identity writes never silently no-op. */
1121
+ requireIdentityTables() {
1122
+ if (this.identity === undefined || this.identityHistory === undefined) {
1123
+ throw new Error('this store was mounted without identity tables');
1124
+ }
1125
+ return { identity: this.identity, identityHistory: this.identityHistory };
1126
+ }
1127
+ getIdentity(kind) {
1128
+ return this.identity?.get(kind);
1129
+ }
1130
+ async updateIdentity(kind, content, input) {
1131
+ return this.writeIdentity(kind, content, input);
1132
+ }
1133
+ listIdentityHistory(kind) {
1134
+ if (this.identityHistory === undefined)
1135
+ return [];
1136
+ const all = [];
1137
+ for (const [key, record] of this.identityHistory.entries()) {
1138
+ if (!key.startsWith(`${kind}#`))
1139
+ continue;
1140
+ all.push(record);
1141
+ }
1142
+ all.sort((a, b) => b.version - a.version);
1143
+ return all;
1144
+ }
1145
+ async revertIdentity(kind, version) {
1146
+ const { identityHistory } = this.requireIdentityTables();
1147
+ const snapshot = identityHistory.get(`${kind}#${version}`);
1148
+ if (snapshot === undefined) {
1149
+ throw new Error(`identity history has no version ${String(version)} for '${kind}'`);
1150
+ }
1151
+ return this.writeIdentity(kind, snapshot.content, { source: 'ui' });
1152
+ }
1153
+ /**
1154
+ * The shared write path behind update/revert: scanner gate, next version
1155
+ * through the table's atomic read-modify-write, history snapshot, history
1156
+ * trim. Character budgets are NOT enforced here — they are settings, and
1157
+ * the identity service (read side) and the tool (write side) own them.
1158
+ */
1159
+ async writeIdentity(kind, content, input) {
1160
+ const { identity, identityHistory } = this.requireIdentityTables();
1161
+ validateContent(content);
1162
+ const scan = scanContent(content);
1163
+ if (!scan.allowed) {
1164
+ throw new Error(`identity content rejected by scanner: ${scan.reasons.join('; ')}`);
1165
+ }
1166
+ const now = Date.now();
1167
+ let record;
1168
+ try {
1169
+ // Atomic read-modify-write: the next version re-reads the record
1170
+ // current at this write-chain slot, so two racing rewrites never mint
1171
+ // the same version — the later write lands as the next version instead
1172
+ // of overwriting the winner.
1173
+ record = await identity.update(kind, current => nextIdentityRecord(current, kind, content, input, now));
1174
+ }
1175
+ catch (error) {
1176
+ // First-ever write: no record to read-modify-write. The seed path is
1177
+ // once-per-process guarded by the identity service and the domain's
1178
+ // single-writer guard excludes cross-process racers, so the residual
1179
+ // window is a same-process race between two simultaneous first writes.
1180
+ // Fragile: the fallback to put() relies on error-message text from the host's
1181
+ // KvTable.update; if the host changes its wording this branch may stop firing.
1182
+ // Ideally the host would expose a typed MissingRecordError; until then, keep
1183
+ // the string set narrow and update it when the host is bumped.
1184
+ if (!(error instanceof Error) || !(error.message.includes('missing-key') || error.message.includes('no record')))
1185
+ throw error;
1186
+ record = nextIdentityRecord(undefined, kind, content, input, now);
1187
+ await identity.put(kind, record);
1188
+ }
1189
+ await identityHistory.put(`${kind}#${record.version}`, {
1190
+ kind,
1191
+ version: record.version,
1192
+ content,
1193
+ ts: now,
1194
+ source: input.source,
1195
+ ...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
1196
+ });
1197
+ await this.trimIdentityHistory(kind);
1198
+ return record;
1199
+ }
1200
+ /** Trim one document's history to the cap, deleting the oldest versions. */
1201
+ async trimIdentityHistory(kind) {
1202
+ if (this.identityHistory === undefined)
1203
+ return;
1204
+ const all = this.listIdentityHistory(kind);
1205
+ const excess = all.length - IDENTITY_HISTORY_CAP;
1206
+ for (let i = 0; i < excess; i++) {
1207
+ const oldest = all[all.length - 1 - i];
1208
+ await this.identityHistory.delete(`${kind}#${oldest.version}`);
1209
+ }
1210
+ }
977
1211
  /**
978
1212
  * Run the janitor pass with the lifecycle's two-tier policy:
979
1213
  * - `project` entries overdue by `decayDays` (pinned exempt) are REMOVED