@chenhw7/dsh-memory 0.9.1 → 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 +246 -26
  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,9 +249,13 @@ 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.
223
259
  // The imported rows are now memory.db's rows, so the medium's data
224
260
  // tables clear before the marker lands. Left in place they would make
225
261
  // the next sqlite boot trip the both-sides guard on its own leftovers
@@ -233,14 +269,18 @@ export async function apply(ctx, config = { storage: 'host-medium', entriesCap:
233
269
  await audit.delete(key);
234
270
  for (const key of [...suggestions.keys()])
235
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);
236
276
  await meta.put(SQLITE_MIGRATION_MARKER, { key: 'medium', value: new Date().toISOString(), updatedAt: Date.now() });
237
277
  ctx.logger.warn(`dsh-memory: imported ${String(mediumEntries.length)} entries from memory.json into ${dbPath} and cleared the medium`);
238
278
  }
239
- else if (migrated !== undefined && mediumEntries.length > 0) {
279
+ else if (migrated !== undefined && (mediumEntries.length > 0 || mediumIdentity.length > 0)) {
240
280
  // Both sides hold data: the medium was written after the migration —
241
281
  // a second writer (the migrating boot itself leaves the medium's data
242
282
  // tables empty). Failing loud is the only safe answer.
243
- 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.');
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.');
244
284
  }
245
285
  ctx.effect(() => async () => { sqlite.close(); });
246
286
  ctx.provide('memory', sqlite);
@@ -266,7 +306,7 @@ export async function apply(ctx, config = { storage: 'host-medium', entriesCap:
266
306
  const own = currentBootOwner();
267
307
  const mediumReader = resolveMediumReader(ctx);
268
308
  const mediumGoodbye = resolveMediumGoodbye(ctx, own.bootId);
269
- 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 });
270
310
  const guard = new CrossProcessGuard(own, mediumReader, owner => domain.global.set(owner), (site, error) => store.reportFailure(site, error), undefined, mediumGoodbye);
271
311
  try {
272
312
  // Startup judgment + claim: judge the open-time global (loaded from the
@@ -361,6 +401,16 @@ function entryIndexTokens(entry) {
361
401
  ? contentTokens
362
402
  : [...contentTokens, ...tokenizeForSearch(entry.summary)];
363
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
+ }
364
414
  /**
365
415
  * MemoryStore implementation backed by a storage-domain KV table. Reads are
366
416
  * synchronous from memory; writes serialize on the domain chain. Every
@@ -372,6 +422,8 @@ export class DomainMemoryStore extends MemoryStore {
372
422
  audit;
373
423
  suggestions;
374
424
  meta;
425
+ identity;
426
+ identityHistory;
375
427
  auditCap;
376
428
  suggestionCap;
377
429
  entriesCap;
@@ -381,12 +433,14 @@ export class DomainMemoryStore extends MemoryStore {
381
433
  failureCounts = new Map();
382
434
  /** Last audit `seq` handed out; lazily initialized from the medium on first append. */
383
435
  auditSeq;
384
- 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) {
385
437
  super();
386
438
  this.entries = entries;
387
439
  this.audit = audit;
388
440
  this.suggestions = suggestions;
389
441
  this.meta = meta;
442
+ this.identity = identity?.identity;
443
+ this.identityHistory = identity?.identityHistory;
390
444
  this.auditCap = auditCap;
391
445
  this.suggestionCap = suggestionCap;
392
446
  this.entriesCap = entriesCap;
@@ -479,7 +533,7 @@ export class DomainMemoryStore extends MemoryStore {
479
533
  createdAt: now,
480
534
  updatedAt: now,
481
535
  ...clampImportance(input.importance),
482
- ...input.anchors !== undefined ? { anchors: input.anchors } : {},
536
+ ...input.anchors !== undefined ? { anchors: filterAnchors(input.anchors) } : {},
483
537
  };
484
538
  await this.entries.put(id, entry);
485
539
  await this.appendAudit('add', id, entry, input.source, input.sessionId);
@@ -528,8 +582,9 @@ export class DomainMemoryStore extends MemoryStore {
528
582
  // Only rewrite the field when the caller supplies one; `undefined`
529
583
  // keeps the stored importance (add-time assessment stands).
530
584
  ...clampImportance(input.importance),
531
- // Same absent-means-keep semantics for anchors.
532
- ...(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) } : {}),
533
588
  };
534
589
  const updated = input.summary === ''
535
590
  ? (() => { const { summary: _c, ...rest } = base; return rest; })()
@@ -612,9 +667,10 @@ export class DomainMemoryStore extends MemoryStore {
612
667
  // Fire-and-forget: stamp the returned entries with a recall timestamp
613
668
  // so the janitor can decay entries that have not been recalled recently.
614
669
  // Read-only consumers (management UI) opt out via recordRecall: false —
615
- // 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.
616
672
  if (query.recordRecall !== false)
617
- void this.stampRecalled(all.map(entry => entry.id));
673
+ void this.stampRecalled(all.map(entry => entry.id), 'tool');
618
674
  return { entries: all, total };
619
675
  }
620
676
  /**
@@ -626,9 +682,15 @@ export class DomainMemoryStore extends MemoryStore {
626
682
  * changed entry; entries already carrying this pass's timestamp and no
627
683
  * decay stamp are skipped without touching the chain. `updatedAt` is
628
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.
629
689
  * @param ids - the ids of the entries the caller surfaced to the model.
690
+ * @param source - the recall surface selecting the stamping tier.
630
691
  */
631
- async stampRecalled(ids) {
692
+ async stampRecalled(ids, source) {
693
+ const bumpAccess = source !== 'fence';
632
694
  const now = Date.now();
633
695
  for (const id of ids) {
634
696
  // Cheap pre-check on the synchronous snapshot: a stamp pass that would
@@ -646,7 +708,7 @@ export class DomainMemoryStore extends MemoryStore {
646
708
  return {
647
709
  ...rest,
648
710
  lastRecalledAt: now,
649
- accessCount: (rest.accessCount ?? 0) + 1,
711
+ ...(bumpAccess ? { accessCount: (rest.accessCount ?? 0) + 1 } : {}),
650
712
  };
651
713
  });
652
714
  }
@@ -665,11 +727,14 @@ export class DomainMemoryStore extends MemoryStore {
665
727
  * (e.g. `memory_get` / `memory_list` tool results). Fire-and-forget; never
666
728
  * throws into the caller. The base-class default is a no-op so providers
667
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.
668
733
  */
669
- markRecalled(ids) {
734
+ markRecalled(ids, source = 'tool') {
670
735
  if (ids.length === 0)
671
736
  return;
672
- void this.stampRecalled(ids.filter(id => this.entries.get(id) !== undefined));
737
+ void this.stampRecalled(ids.filter(id => this.entries.get(id) !== undefined), source);
673
738
  }
674
739
  /**
675
740
  * Record usage hits on the given entries (write-path rework Step 2):
@@ -724,6 +789,11 @@ export class DomainMemoryStore extends MemoryStore {
724
789
  * @throws when the proposed content or summary fails validation or the scanner.
725
790
  */
726
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
+ }
727
797
  validateProjectScope({ ...input, projectName: input.projectName ?? (input.targetEntryId !== undefined ? this.entries.get(input.targetEntryId)?.projectName : undefined) });
728
798
  validateContent(input.content);
729
799
  const scan = scanContent(input.content);
@@ -738,6 +808,7 @@ export class DomainMemoryStore extends MemoryStore {
738
808
  // Match against existing proposals: same target entry wins outright;
739
809
  // otherwise nearest-content in the same scope above the dup threshold.
740
810
  let matched;
811
+ const inputTokens = uniqueTokens(input.content);
741
812
  for (const [, suggestion] of this.suggestions.entries()) {
742
813
  if (input.targetEntryId !== undefined) {
743
814
  if (suggestion.targetEntryId === input.targetEntryId) {
@@ -746,13 +817,17 @@ export class DomainMemoryStore extends MemoryStore {
746
817
  }
747
818
  continue;
748
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;
749
824
  if (suggestion.scope !== input.scope)
750
825
  continue;
751
826
  // The live queue is the corpus: at queue scale (≤ cap rows) rebuilding
752
827
  // the df table per row would be wasteful, but the queue is tiny — and
753
828
  // the table only needs building once per observe call, not per row.
754
829
  const stats = buildCorpusStats([input.content, suggestion.content]);
755
- const similarity = weightedOverlapSimilarity(stats, uniqueTokens(input.content), uniqueTokens(suggestion.content));
830
+ const similarity = weightedOverlapSimilarity(stats, inputTokens, uniqueTokens(suggestion.content));
756
831
  if (similarity > SUGGESTION_DUP_THRESHOLD) {
757
832
  matched = suggestion;
758
833
  break;
@@ -790,6 +865,51 @@ export class DomainMemoryStore extends MemoryStore {
790
865
  await this.trimSuggestions();
791
866
  return suggestion;
792
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
+ }
793
913
  /**
794
914
  * List pending suggestions for the review UI: highest `hits` first (the
795
915
  * repeatedly-re-proposed signals float up), then most recently seen.
@@ -831,6 +951,14 @@ export class DomainMemoryStore extends MemoryStore {
831
951
  const summary = override?.summary !== undefined
832
952
  ? (override.summary.length > 0 ? override.summary : undefined)
833
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
+ }
834
962
  let entry;
835
963
  if (suggestion.targetEntryId !== undefined && this.entries.get(suggestion.targetEntryId) !== undefined) {
836
964
  entry = await this.update(suggestion.targetEntryId, {
@@ -988,6 +1116,98 @@ export class DomainMemoryStore extends MemoryStore {
988
1116
  await this.appendAudit('update', id, updated, 'janitor', undefined);
989
1117
  return updated;
990
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
+ }
991
1211
  /**
992
1212
  * Run the janitor pass with the lifecycle's two-tier policy:
993
1213
  * - `project` entries overdue by `decayDays` (pinned exempt) are REMOVED