@dsh-ray/personal-memory 0.0.1-seed.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +187 -1
  3. package/cordis.patch.yml +18 -0
  4. package/lib/evidence-filesystem.d.ts +25 -0
  5. package/lib/evidence-filesystem.d.ts.map +1 -0
  6. package/lib/evidence-filesystem.js +178 -0
  7. package/lib/evidence-filesystem.js.map +1 -0
  8. package/lib/evidence-ledger.d.ts +33 -0
  9. package/lib/evidence-ledger.d.ts.map +1 -0
  10. package/lib/evidence-ledger.js +216 -0
  11. package/lib/evidence-ledger.js.map +1 -0
  12. package/lib/evidence-runtime.d.ts +28 -0
  13. package/lib/evidence-runtime.d.ts.map +1 -0
  14. package/lib/evidence-runtime.js +114 -0
  15. package/lib/evidence-runtime.js.map +1 -0
  16. package/lib/evidence-service.d.ts +50 -0
  17. package/lib/evidence-service.d.ts.map +1 -0
  18. package/lib/evidence-service.js +212 -0
  19. package/lib/evidence-service.js.map +1 -0
  20. package/lib/index.d.ts +10 -0
  21. package/lib/index.d.ts.map +1 -0
  22. package/lib/index.js +11 -0
  23. package/lib/index.js.map +1 -0
  24. package/lib/knowledge.d.ts +6 -0
  25. package/lib/knowledge.d.ts.map +1 -0
  26. package/lib/knowledge.js +55 -0
  27. package/lib/knowledge.js.map +1 -0
  28. package/lib/learning-adoptions.d.ts +102 -0
  29. package/lib/learning-adoptions.d.ts.map +1 -0
  30. package/lib/learning-adoptions.js +92 -0
  31. package/lib/learning-adoptions.js.map +1 -0
  32. package/lib/learning-service.d.ts +38 -0
  33. package/lib/learning-service.d.ts.map +1 -0
  34. package/lib/learning-service.js +329 -0
  35. package/lib/learning-service.js.map +1 -0
  36. package/lib/promotion.d.ts +24 -0
  37. package/lib/promotion.d.ts.map +1 -0
  38. package/lib/promotion.js +147 -0
  39. package/lib/promotion.js.map +1 -0
  40. package/lib/proposals.d.ts +42 -0
  41. package/lib/proposals.d.ts.map +1 -0
  42. package/lib/proposals.js +386 -0
  43. package/lib/proposals.js.map +1 -0
  44. package/lib/service.d.ts +193 -0
  45. package/lib/service.d.ts.map +1 -0
  46. package/lib/service.js +900 -0
  47. package/lib/service.js.map +1 -0
  48. package/lib/sqlite.d.ts +9 -0
  49. package/lib/sqlite.d.ts.map +1 -0
  50. package/lib/sqlite.js +565 -0
  51. package/lib/sqlite.js.map +1 -0
  52. package/lib/store.d.ts +161 -0
  53. package/lib/store.d.ts.map +1 -0
  54. package/lib/store.js +2125 -0
  55. package/lib/store.js.map +1 -0
  56. package/lib/tokenize.d.ts +2 -0
  57. package/lib/tokenize.d.ts.map +1 -0
  58. package/lib/tokenize.js +22 -0
  59. package/lib/tokenize.js.map +1 -0
  60. package/lib/tools.d.ts +4 -0
  61. package/lib/tools.d.ts.map +1 -0
  62. package/lib/tools.js +313 -0
  63. package/lib/tools.js.map +1 -0
  64. package/lib/types.d.ts +256 -0
  65. package/lib/types.d.ts.map +1 -0
  66. package/lib/types.js +2 -0
  67. package/lib/types.js.map +1 -0
  68. package/lib/version.d.ts +2 -0
  69. package/lib/version.d.ts.map +1 -0
  70. package/lib/version.js +2 -0
  71. package/lib/version.js.map +1 -0
  72. package/package.json +114 -4
package/lib/service.js ADDED
@@ -0,0 +1,900 @@
1
+ import { isAbsolute } from 'node:path';
2
+ import { Context, Service } from '@deepseek-ai/cordis';
3
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
4
+ import Schema from '@deepseek-ai/schemastery';
5
+ import { REVALIDATABLE_READ_TOOLS, revalidateFileEvidence } from './evidence-filesystem.js';
6
+ import { MemoryPromotionCancelledError, MemoryProposalManager } from './proposals.js';
7
+ import { MemoryLearningService } from './learning-service.js';
8
+ import { validateMemoryLearningAdoptionGrant } from './learning-adoptions.js';
9
+ import { memoryPrincipalDigest, MemoryStore, } from './store.js';
10
+ import { PreferenceMemoryPromotionBridge, preferencePromotionMutation, preferencePromotionNamespace, } from './promotion.js';
11
+ import { registerMemoryTools } from './tools.js';
12
+ import { SessionEvidenceBridge } from './evidence-service.js';
13
+ import { withPreferenceMemoryPromotionSubmissionDigest, } from '@dsh-ray/assistant-growth-contract';
14
+ export class PersonalMemoryError extends Error {
15
+ code;
16
+ constructor(code, message) {
17
+ super(message);
18
+ this.code = code;
19
+ this.name = 'PersonalMemoryError';
20
+ }
21
+ }
22
+ const baseConfigSchema = Schema.object({
23
+ databasePath: Schema.string().required(),
24
+ automaticLearning: Schema.transform(Schema.any(), (value, options) => {
25
+ if (value === undefined || value === true)
26
+ return true;
27
+ if (value === false)
28
+ return false;
29
+ try {
30
+ return validateMemoryLearningAdoptionGrant(value);
31
+ }
32
+ catch (error) {
33
+ throw new Schema.ValidationError(String(error), options ?? { path: ['automaticLearning'] });
34
+ }
35
+ }).default(true),
36
+ approvalMode: Schema.union(['delivery-or-headless', 'delivery-required'])
37
+ .default('delivery-required'),
38
+ maxContentBytes: Schema.number().step(1).min(1).default(4_096),
39
+ maxRecordsPerIdentity: Schema.number().step(1).min(1).default(1_000),
40
+ searchLimit: Schema.number().step(1).min(1).max(100).default(20),
41
+ snapshotLimit: Schema.number().step(1).min(1).max(100).default(20),
42
+ snapshotMaxBytes: Schema.number().step(1).min(1).default(8_192),
43
+ snapshotMaxTokens: Schema.number().step(1).min(1).default(2_048),
44
+ toolEvidence: Schema.boolean().default(true),
45
+ evidenceMaxSourceBytes: Schema.number().step(1).min(1).max(4_194_304).default(1_048_576),
46
+ evidenceManifestMaxBytes: Schema.number().step(1).min(1).max(8_192).default(2_048),
47
+ evidenceManifestLimit: Schema.number().step(1).min(1).max(20).default(8),
48
+ defaultProposalTtlMs: Schema.number().step(1).min(1).default(900_000),
49
+ maxImportRecords: Schema.number().step(1).min(1).max(1_000).default(100),
50
+ reconcileIntervalMs: Schema.number()
51
+ .step(1)
52
+ .min(0)
53
+ .max(2_147_483_647)
54
+ .default(15_000),
55
+ reconcileLimit: Schema.number().step(1).min(1).max(1_000).default(50),
56
+ });
57
+ const configSchema = Schema.transform(Schema.any(), (value, options) => {
58
+ if (value && typeof value === 'object' && !Array.isArray(value)
59
+ && Object.hasOwn(value, 'automaticLearning')
60
+ && value.automaticLearning === null) {
61
+ throw new Schema.ValidationError('personal-memory: automaticLearning cannot be null', options ?? { path: ['automaticLearning'] });
62
+ }
63
+ return baseConfigSchema(value);
64
+ });
65
+ export const Config = configSchema;
66
+ function decisionError(decision) {
67
+ return new PersonalMemoryError('policy-denied', `personal-memory policy denied operation: ${decision.reasonCode}`);
68
+ }
69
+ const APPROVAL_SOURCE_ID = 'dsh-ray-personal-memory';
70
+ export class PersonalMemoryService extends Service {
71
+ static Config = configSchema;
72
+ static inject = ['assistantPolicy'];
73
+ memoryStore;
74
+ evidenceBridge;
75
+ proposals;
76
+ policy;
77
+ delivery;
78
+ promotionBridge;
79
+ learning;
80
+ headlessNamespaces = new WeakMap();
81
+ config;
82
+ sessionSnapshots = new WeakMap();
83
+ toolsCtx;
84
+ active = true;
85
+ constructor(ctx, input) {
86
+ super(ctx, 'personalMemory');
87
+ let config;
88
+ try {
89
+ config = PersonalMemoryService.Config(input);
90
+ }
91
+ catch (error) {
92
+ throw new Error(`personal-memory: invalid configuration: ${String(error)}`, { cause: error });
93
+ }
94
+ const policy = ctx.get('assistantPolicy');
95
+ if (policy === undefined)
96
+ throw new Error('personal-memory: assistantPolicy service is required');
97
+ this.config = config;
98
+ this.policy = policy;
99
+ this.delivery = ctx.get('assistantDelivery');
100
+ this.memoryStore = new MemoryStore({
101
+ path: config.databasePath,
102
+ maxContentBytes: config.maxContentBytes,
103
+ maxRecordsPerIdentity: config.maxRecordsPerIdentity,
104
+ });
105
+ try {
106
+ this.learning = typeof config.automaticLearning === 'object' && config.automaticLearning !== null
107
+ ? new MemoryLearningService(ctx, this.memoryStore, config.automaticLearning)
108
+ : undefined;
109
+ }
110
+ catch (error) {
111
+ this.memoryStore.close();
112
+ throw error;
113
+ }
114
+ this.evidenceBridge = config.toolEvidence ? new SessionEvidenceBridge(ctx, this.memoryStore.evidence, {
115
+ maxSourceBytes: config.evidenceMaxSourceBytes,
116
+ manifestMaxBytes: config.evidenceManifestMaxBytes,
117
+ manifestLimit: Math.min(config.evidenceManifestLimit, config.maxRecordsPerIdentity),
118
+ scope: (agent, action) => this.evidenceScope(agent, action),
119
+ allowTool: (agent, name) => REVALIDATABLE_READ_TOOLS.has(name) && this.ctx.get('tools', false)?.get(name, agent) !== undefined
120
+ && this.policy.authorizeAgent(agent, 'execute', { kind: 'tool', id: name }).effect === 'allow',
121
+ revalidate: (exec, source, anchor) => this.toolsCtx === undefined
122
+ ? Promise.resolve(false)
123
+ : revalidateFileEvidence(this.toolsCtx, this.policy, exec, source, anchor),
124
+ }) : undefined;
125
+ this.proposals = new MemoryProposalManager(this.memoryStore, policy, proposal => this.validatePromotionOwner(proposal));
126
+ this.promotionBridge = new PreferenceMemoryPromotionBridge({
127
+ submit: request => this.submitPreferencePromotion(request),
128
+ cancel: request => this.cancelPreferencePromotion(request),
129
+ list: limit => this.listPromotionResults(limit),
130
+ acknowledge: ack => this.acknowledgePromotionResult(ack),
131
+ });
132
+ ctx.inject(['assistantDelivery'], (deliveryCtx) => {
133
+ const delivery = deliveryCtx.get('assistantDelivery');
134
+ this.delivery = delivery;
135
+ return () => {
136
+ if (this.delivery === delivery)
137
+ this.delivery = undefined;
138
+ };
139
+ });
140
+ const currentPreference = ctx.get('assistantPreferenceLearning');
141
+ this.promotionBridge.bind(currentPreference);
142
+ ctx.inject(['assistantPreferenceLearning'], preferenceCtx => {
143
+ const producer = preferenceCtx.get('assistantPreferenceLearning');
144
+ if (producer === currentPreference)
145
+ return;
146
+ return this.promotionBridge.bind(producer);
147
+ });
148
+ ctx.effect(() => () => {
149
+ this.active = false;
150
+ this.promotionBridge.dispose();
151
+ this.memoryStore.close();
152
+ }, 'personal-memory.database');
153
+ if (config.reconcileIntervalMs > 0) {
154
+ ctx.effect(() => {
155
+ const timer = setInterval(() => {
156
+ // A reconcile pass must never take the service down; the next tick retries.
157
+ try {
158
+ this.reconcileProposals();
159
+ }
160
+ catch {
161
+ // Intentionally ignored: the authoritative state stays in the ledger.
162
+ }
163
+ }, config.reconcileIntervalMs);
164
+ timer.unref?.();
165
+ return () => clearInterval(timer);
166
+ }, 'personal-memory.reconcile');
167
+ }
168
+ ctx.on('agent/created', ({ agent }) => {
169
+ if (ctx.get('systemPrompt') !== undefined)
170
+ return;
171
+ this.injectSessionSnapshot(agent);
172
+ });
173
+ ctx.inject(['systemPrompt'], promptCtx => promptCtx.systemPrompt.context({
174
+ name: 'personal-memory:task-context',
175
+ order: 240,
176
+ text: ({ agent }) => this.taskSnapshot(agent),
177
+ }));
178
+ ctx.inject(['systemPrompt'], promptCtx => promptCtx.systemPrompt.context({
179
+ name: 'personal-memory:tool-evidence', order: 241,
180
+ text: ({ agent }) => this.evidenceBridge?.snapshot(agent) ?? '',
181
+ }));
182
+ ctx.inject(['tools'], (toolsCtx) => {
183
+ this.toolsCtx = toolsCtx;
184
+ registerMemoryTools(toolsCtx, this);
185
+ return () => {
186
+ if (this.toolsCtx === toolsCtx)
187
+ this.toolsCtx = undefined;
188
+ };
189
+ });
190
+ }
191
+ search(agent, request) {
192
+ this.assertActive();
193
+ this.agentScope(agent);
194
+ const authorizationOptions = request.authorizationIdempotencyKey === undefined
195
+ ? {}
196
+ : { idempotencyKey: request.authorizationIdempotencyKey };
197
+ const decision = this.policy.authorizeAgent(agent, 'search', { kind: 'memory', id: 'visible' }, authorizationOptions);
198
+ if (decision.effect !== 'allow')
199
+ throw decisionError(decision);
200
+ const context = this.agentContext(agent);
201
+ return this.withLearningVisibility(context, () => this.memoryStore.search({
202
+ context,
203
+ query: request.query,
204
+ limit: request.limit ?? this.config.searchLimit,
205
+ }));
206
+ }
207
+ automaticLearningStatus() {
208
+ this.assertActive();
209
+ const automaticLearning = this.config.automaticLearning;
210
+ if (typeof automaticLearning === 'object' && automaticLearning !== null) {
211
+ return Object.freeze({ enabled: true, mode: 'signed-grant', configured: true });
212
+ }
213
+ if (automaticLearning === false) {
214
+ return Object.freeze({ enabled: false, mode: 'disabled', configured: false });
215
+ }
216
+ return Object.freeze({ enabled: true, mode: 'default-pending-grant', configured: false });
217
+ }
218
+ learningUnavailableError() {
219
+ return this.config.automaticLearning === false
220
+ ? new Error('personal-memory: automatic learning is disabled')
221
+ : new Error('personal-memory: automatic learning is enabled by default and requires an owner-signed adoption grant');
222
+ }
223
+ /** Host-only: candidates never provide approval flags, namespace, trust or a grant. */
224
+ adoptReviewedLearning(input) {
225
+ this.assertActive();
226
+ if (!this.learning)
227
+ throw this.learningUnavailableError();
228
+ return this.learning.adopt(input.request);
229
+ }
230
+ lookupLearningAdoption(input) {
231
+ this.assertActive();
232
+ if (!this.learning)
233
+ throw this.learningUnavailableError();
234
+ return this.learning.lookup(input.request);
235
+ }
236
+ inspectLearningTarget(input) {
237
+ this.assertActive();
238
+ return this.learning?.inspectTarget(input);
239
+ }
240
+ /** Host-only current managed facts and experiences, suitable for replacement proposals. */
241
+ listLearningTargets(input) {
242
+ this.assertActive();
243
+ if (!this.learning)
244
+ throw this.learningUnavailableError();
245
+ return this.learning.listTargets(input);
246
+ }
247
+ /** Host-only read of the current adoption grant and its remaining budget. */
248
+ inspectLearningAdoptionAvailability(input) {
249
+ this.assertActive();
250
+ if (!this.learning)
251
+ throw this.learningUnavailableError();
252
+ return this.learning.inspectAvailability(input);
253
+ }
254
+ withLearningVisibility(context, callback) {
255
+ return this.learning ? this.learning.withVisible(context, callback) : callback();
256
+ }
257
+ readEvidence(exec, request) {
258
+ this.assertActive();
259
+ if (this.evidenceBridge === undefined)
260
+ throw new PersonalMemoryError('not-found', 'tool evidence is disabled');
261
+ return this.evidenceBridge.read(exec, request);
262
+ }
263
+ evidenceScope(agent, action) {
264
+ this.assertActive();
265
+ if (agent === undefined || this.ctx.get('agents', false)?.get(agent.id) !== agent
266
+ || this.ctx.get('sessions', false)?.get(agent.session.id) !== agent.session
267
+ || agent.status !== 'running')
268
+ throw new PersonalMemoryError('missing-identity', 'tool evidence requires the exact running agent and session');
269
+ const context = this.agentContext(agent);
270
+ const decision = this.policy.authorizeAgent(agent, action, { kind: 'memory', id: 'tool-evidence' });
271
+ if (decision.effect !== 'allow')
272
+ throw decisionError(decision);
273
+ return { ...context, sessionId: String(agent.session.id) };
274
+ }
275
+ /**
276
+ * Narrow background-review seam. Its trust/kind/sensitivity filters are
277
+ * service-owned so a maintenance Agent cannot widen them through tool args.
278
+ */
279
+ searchConfirmedGuidance(agent, request) {
280
+ this.assertActive();
281
+ const context = this.agentContext(agent);
282
+ const authorizationOptions = request.authorizationIdempotencyKey === undefined
283
+ ? {}
284
+ : { idempotencyKey: request.authorizationIdempotencyKey };
285
+ const decision = this.policy.authorizeAgent(agent, 'search', { kind: 'memory', id: 'visible' }, authorizationOptions);
286
+ if (decision.effect !== 'allow')
287
+ throw decisionError(decision);
288
+ return this.withLearningVisibility(context, () => this.memoryStore.search({
289
+ context,
290
+ query: request.query,
291
+ limit: request.limit ?? this.config.searchLimit,
292
+ kinds: ['instruction', 'preference'],
293
+ trusts: ['user-confirmed'],
294
+ sensitivities: ['private'],
295
+ }));
296
+ }
297
+ read(agent, request) {
298
+ this.assertActive();
299
+ const context = this.agentContext(agent);
300
+ const decision = this.policy.authorizeAgent(agent, 'read', { kind: 'memory', id: 'selected' }, {
301
+ idempotencyKey: `memory-read:${request.ids.join(':')}`,
302
+ });
303
+ if (decision.effect !== 'allow')
304
+ throw decisionError(decision);
305
+ try {
306
+ return this.withLearningVisibility(context, () => this.memoryStore.read(context, request.ids));
307
+ }
308
+ catch (error) {
309
+ if (error instanceof Error && 'code' in error && error.code === 'not-found') {
310
+ throw new PersonalMemoryError('not-found', error.message);
311
+ }
312
+ throw error;
313
+ }
314
+ }
315
+ propose(agent, input) {
316
+ this.assertActive();
317
+ const scope = this.agentScope(agent);
318
+ const approval = this.resolveApprovalRoute(agent, scope, input.principal);
319
+ const context = { ...scope, namespace: approval.namespace };
320
+ this.assertMutationIdentity(context, input.mutation);
321
+ const decision = this.policy.authorizeAgent(agent, 'propose', {
322
+ kind: 'memory', id: input.mutation.op,
323
+ }, { idempotencyKey: `memory-propose:${input.idempotencyKey}` });
324
+ if (decision.effect !== 'allow')
325
+ throw decisionError(decision);
326
+ const ttlMs = input.ttlMs ?? this.config.defaultProposalTtlMs;
327
+ return this.proposals.propose({
328
+ idempotencyKey: input.idempotencyKey,
329
+ requester: `agent:${context.agentPreset}`,
330
+ principal: approval.principal,
331
+ namespace: context.namespace,
332
+ ...(approval.dispatch === undefined ? {} : { dispatch: approval.dispatch }),
333
+ ttlMs,
334
+ mutation: input.mutation,
335
+ });
336
+ }
337
+ /** Model tool entry: only a live owner call can enter Policy's bounded review. */
338
+ async proposeFromTool(exec, input) {
339
+ if (exec.signal.aborted)
340
+ throw new PersonalMemoryError('policy-denied', 'memory tool execution was cancelled');
341
+ if (exec.name !== 'memory_manage' || exec.agent === undefined
342
+ || exec.arguments === null || typeof exec.arguments !== 'object') {
343
+ return this.propose(exec.agent, input);
344
+ }
345
+ const args = exec.arguments;
346
+ if (args.operation !== input.mutation.op || args.idempotency_key !== input.idempotencyKey
347
+ || (input.mutation.op !== 'add' && input.mutation.op !== 'replace')
348
+ || input.mutation.entry.sensitivity !== 'private') {
349
+ return this.propose(exec.agent, input);
350
+ }
351
+ const frozenInput = structuredClone(input);
352
+ const inputJson = JSON.stringify(input);
353
+ const argsJson = JSON.stringify(exec.arguments);
354
+ const policy = this.policy;
355
+ if (typeof policy.runOwnerRequestedChange !== 'function')
356
+ return this.propose(exec.agent, frozenInput);
357
+ this.assertActive();
358
+ const scope = this.agentScope(exec.agent);
359
+ const approval = this.resolveApprovalRoute(exec.agent, scope, input.principal);
360
+ this.assertMutationIdentity({ ...scope, namespace: approval.namespace }, input.mutation);
361
+ const replacement = input.mutation.op === 'replace'
362
+ ? this.memoryStore.get(approval.namespace, input.mutation.identity, input.mutation.id)
363
+ : undefined;
364
+ const replacementMutation = input.mutation.op === 'replace' ? input.mutation : undefined;
365
+ if (input.mutation.op === 'replace'
366
+ && (replacement?.sensitivity !== 'private' || replacement.version !== input.mutation.expectedVersion)) {
367
+ return this.propose(exec.agent, frozenInput);
368
+ }
369
+ const decision = this.policy.authorizeAgent(exec.agent, 'propose', {
370
+ kind: 'memory', id: input.mutation.op,
371
+ }, { idempotencyKey: `memory-propose:${input.idempotencyKey}` });
372
+ if (decision.effect !== 'allow')
373
+ throw decisionError(decision);
374
+ const result = await policy.runOwnerRequestedChange({
375
+ execution: exec,
376
+ resourceKind: 'memory',
377
+ operation: input.mutation.op,
378
+ policyIdempotencyKey: `personal-memory:${input.idempotencyKey}`,
379
+ resolveOwnerRequest: () => this.delivery?.inspectOwnerRequestedChange?.(exec, { sourceId: APPROVAL_SOURCE_ID }),
380
+ ...(replacementMutation === undefined ? {} : { resolveCurrentTarget: () => {
381
+ const current = this.memoryStore.get(approval.namespace, replacementMutation.identity, replacementMutation.id);
382
+ if (current === undefined || current.version !== replacementMutation.expectedVersion
383
+ || current.sensitivity !== 'private')
384
+ return undefined;
385
+ return current;
386
+ } }),
387
+ }, () => {
388
+ if (exec.signal.aborted || JSON.stringify(input) !== inputJson
389
+ || JSON.stringify(exec.arguments) !== argsJson) {
390
+ throw new PersonalMemoryError('policy-denied', 'memory tool request changed during owner review');
391
+ }
392
+ if (input.mutation.op === 'replace') {
393
+ const current = this.memoryStore.get(approval.namespace, input.mutation.identity, input.mutation.id);
394
+ if (current?.sensitivity !== 'private' || current.version !== replacement?.version) {
395
+ throw new PersonalMemoryError('policy-denied', 'memory replacement target changed during owner review');
396
+ }
397
+ }
398
+ return this.propose(exec.agent, frozenInput);
399
+ });
400
+ if (result.status !== 'approved' || result.record !== undefined)
401
+ return result;
402
+ const stored = this.memoryStore.getProposal(result.proposalId);
403
+ const record = stored?.resultMemoryId === undefined ? undefined
404
+ : this.memoryStore.get(stored.namespace, stored.mutation.identity, stored.resultMemoryId);
405
+ return record === undefined ? result : Object.freeze({ ...result, record });
406
+ }
407
+ hasCurrentOwnerToolProof(exec) {
408
+ const args = exec.arguments;
409
+ const eligible = typeof this.policy.runOwnerRequestedChange === 'function'
410
+ && args !== null && typeof args === 'object'
411
+ && (args.operation === 'add' || args.operation === 'replace')
412
+ && args.entry?.sensitivity === 'private'
413
+ && this.delivery?.inspectOwnerRequestedChange?.(exec, { sourceId: APPROVAL_SOURCE_ID }) !== undefined;
414
+ if (!eligible || args?.operation !== 'replace')
415
+ return eligible;
416
+ if (exec.agent === undefined || (args.owner !== 'agent' && args.owner !== 'user')
417
+ || (args.scope !== 'workspace' && args.scope !== 'user-global')
418
+ || typeof args.memory_id !== 'string' || typeof args.expected_version !== 'number')
419
+ return false;
420
+ try {
421
+ const scope = this.agentScope(exec.agent);
422
+ const approval = this.resolveApprovalRoute(exec.agent, scope, undefined);
423
+ const identity = { owner: args.owner, scope: args.scope,
424
+ ...(args.scope === 'workspace' ? { workspace: scope.workspace } : {}),
425
+ ...(args.owner === 'agent' ? { agentPreset: scope.agentPreset } : {}) };
426
+ const target = this.memoryStore.get(approval.namespace, identity, args.memory_id);
427
+ return target?.sensitivity === 'private' && target.version === args.expected_version;
428
+ }
429
+ catch {
430
+ return false;
431
+ }
432
+ }
433
+ decideProposal(input) {
434
+ this.assertActive();
435
+ return this.proposals.decide(input);
436
+ }
437
+ /**
438
+ * Commit proposals whose policy decision settled after the originating turn.
439
+ * Without this, an approval granted on a chat card would leave the memory
440
+ * proposal pending forever. Safe to call repeatedly.
441
+ */
442
+ reconcileProposals(limit) {
443
+ this.assertActive();
444
+ return this.proposals.reconcile(limit ?? this.config.reconcileLimit);
445
+ }
446
+ exportJson(agent) {
447
+ this.assertActive();
448
+ const context = this.agentContext(agent);
449
+ const decision = this.policy.authorizeAgent(agent, 'export', { kind: 'memory', id: 'visible' }, {
450
+ idempotencyKey: `memory-export:${String(agent?.id)}`,
451
+ });
452
+ if (decision.effect !== 'allow')
453
+ throw decisionError(decision);
454
+ return this.withLearningVisibility(context, () => JSON.stringify(this.memoryStore.exportDocument(context), null, 2));
455
+ }
456
+ proposeImport(agent, input) {
457
+ this.assertActive();
458
+ const scope = this.agentScope(agent);
459
+ let decoded;
460
+ try {
461
+ decoded = JSON.parse(input.json);
462
+ }
463
+ catch (error) {
464
+ throw new PersonalMemoryError('invalid-import', `memory import is not valid JSON: ${String(error)}`);
465
+ }
466
+ const document = decoded;
467
+ if (typeof document !== 'object' || document === null
468
+ || document.format !== 'dsh-personal-memory'
469
+ || (document.version !== 1 && document.version !== 2)
470
+ || !Array.isArray(document.records)
471
+ || document.records.length > this.config.maxImportRecords) {
472
+ throw new PersonalMemoryError('invalid-import', 'memory import format, version, or record count is invalid');
473
+ }
474
+ const approval = this.resolveApprovalRoute(agent, scope, input.principal);
475
+ const context = { ...scope, namespace: approval.namespace };
476
+ let mutations;
477
+ try {
478
+ mutations = document.records.map((value) => {
479
+ if (typeof value !== 'object' || value === null)
480
+ throw new Error('record must be an object');
481
+ const record = value;
482
+ const mutation = this.memoryStore.normalizeMutation({
483
+ op: 'add',
484
+ identity: record.identity,
485
+ entry: record.entry,
486
+ }, { namespace: context.namespace });
487
+ this.assertMutationIdentity(context, mutation);
488
+ return mutation;
489
+ });
490
+ }
491
+ catch (error) {
492
+ throw new PersonalMemoryError('invalid-import', `memory import record is invalid: ${String(error)}`);
493
+ }
494
+ const proposals = mutations.map((mutation, index) => this.propose(agent, {
495
+ idempotencyKey: `${input.idempotencyKey}:${index}`,
496
+ ...(input.principal === undefined ? {} : { principal: input.principal }),
497
+ ...(input.ttlMs === undefined ? {} : { ttlMs: input.ttlMs }),
498
+ mutation,
499
+ }));
500
+ return Object.freeze({ proposals: Object.freeze(proposals) });
501
+ }
502
+ getProposal(proposalId, principal) {
503
+ this.assertActive();
504
+ const proposal = this.proposals.getProposal(proposalId);
505
+ if (proposal === undefined)
506
+ return undefined;
507
+ const stored = this.memoryStore.getProposal(proposalId);
508
+ if (stored?.principal !== principal) {
509
+ throw new PersonalMemoryError('unauthorized-principal', 'memory proposal is bound to another principal');
510
+ }
511
+ return proposal;
512
+ }
513
+ health() {
514
+ this.assertActive();
515
+ return this.memoryStore.health();
516
+ }
517
+ /** Host-only post-commit mutation/withdrawal notification; never exposed as a model tool. */
518
+ onRecordChange(listener) {
519
+ this.assertActive();
520
+ return this.memoryStore.onRecordChange(listener);
521
+ }
522
+ /** Host-only startup backfill of active private records; never exposed as a model tool. */
523
+ listActiveRecordsForAssociationSync(context, options) {
524
+ this.assertActive();
525
+ return this.withLearningVisibility(context, () => this.memoryStore.listActivePrivateRecordsForSync(context, options));
526
+ }
527
+ /** Trusted producer registration hook; intentionally not exposed as a model tool. */
528
+ bindPreferencePromotionProducer(producer) {
529
+ this.assertActive();
530
+ return this.promotionBridge.bind(producer);
531
+ }
532
+ submitPreferencePromotion(request) {
533
+ this.assertActive();
534
+ const namespace = preferencePromotionNamespace(request, memoryPrincipalDigest(request.principalId));
535
+ const mutation = preferencePromotionMutation(request);
536
+ const now = Date.now();
537
+ const ttlMs = Math.max(1, request.deadlineAt - Math.min(request.observedAt, now));
538
+ const promotion = Object.freeze({
539
+ promotionId: request.promotionId,
540
+ promotionGeneration: request.promotionGeneration,
541
+ requestDigest: request.requestDigest,
542
+ scope: request.scope,
543
+ ownerGeneration: request.ownerGeneration,
544
+ });
545
+ const base = {
546
+ idempotencyKey: request.idempotencyKey,
547
+ requester: 'preference-learning',
548
+ principal: request.principalId,
549
+ namespace,
550
+ ttlMs,
551
+ notAfter: request.deadlineAt,
552
+ promotion,
553
+ mutation,
554
+ };
555
+ let proposal;
556
+ try {
557
+ if (request.deadlineAt <= now) {
558
+ proposal = this.proposals.rejectPromotionBeforePolicy({
559
+ ...base,
560
+ promotion: { ...promotion, prePolicyStatus: 'expired' },
561
+ }, 'expired');
562
+ }
563
+ else {
564
+ const route = this.delivery?.prepareOwnerApprovalForPreference({
565
+ sourceId: APPROVAL_SOURCE_ID,
566
+ scope: request.scope,
567
+ principalId: request.principalId,
568
+ principalLineage: request.principalLineage,
569
+ ownerGeneration: request.ownerGeneration,
570
+ });
571
+ if (route === undefined) {
572
+ throw new PersonalMemoryError('missing-approval-route', 'Preference promotion requires the trusted Delivery owner-route resolver');
573
+ }
574
+ if ('kind' in route) {
575
+ proposal = this.proposals.rejectPromotionBeforePolicy({
576
+ ...base,
577
+ promotion: { ...promotion, prePolicyStatus: 'stale-owner' },
578
+ }, 'stale-owner');
579
+ }
580
+ else {
581
+ if (!this.routeMatchesPromotion(route, request)) {
582
+ throw new PersonalMemoryError('unauthorized-principal', 'Preference promotion Delivery route changed its frozen owner authority');
583
+ }
584
+ proposal = this.proposals.propose({ ...base, dispatch: route });
585
+ }
586
+ }
587
+ }
588
+ catch (error) {
589
+ if (error instanceof MemoryPromotionCancelledError) {
590
+ throw Object.assign(new Error('Preference promotion was durably cancelled'), {
591
+ code: 'promotion-cancelled', receipt: error.receipt,
592
+ });
593
+ }
594
+ throw error;
595
+ }
596
+ return withPreferenceMemoryPromotionSubmissionDigest({
597
+ contractVersion: 1,
598
+ promotionId: request.promotionId,
599
+ promotionGeneration: request.promotionGeneration,
600
+ requestDigest: request.requestDigest,
601
+ outcome: proposal.replayed ? 'replayed' : 'accepted',
602
+ memoryProposalId: proposal.proposalId,
603
+ });
604
+ }
605
+ cancelPreferencePromotion(request) {
606
+ this.assertActive();
607
+ return this.memoryStore.cancelPromotionBeforeOrAfterSubmit(request).receipt;
608
+ }
609
+ listPromotionResults(limit) {
610
+ this.assertActive();
611
+ return this.memoryStore.listPendingPromotionResults(limit).map(result => {
612
+ const common = {
613
+ contractVersion: 1,
614
+ promotionId: result.promotionId,
615
+ promotionGeneration: result.promotionGeneration,
616
+ requestDigest: result.requestDigest,
617
+ resultVersion: result.resultVersion,
618
+ occurredAt: result.occurredAt,
619
+ receiptDigest: result.receiptDigest,
620
+ };
621
+ if (result.status === 'stale-owner')
622
+ return Object.freeze({ ...common, status: result.status });
623
+ if (result.status === 'rejected') {
624
+ return Object.freeze({
625
+ ...common, status: result.status, rejectionKind: 'owner-explicit',
626
+ memoryProposalId: result.memoryProposalId,
627
+ memoryProposalVersion: result.memoryProposalVersion,
628
+ });
629
+ }
630
+ if (result.status === 'confirmed') {
631
+ if (result.memoryRecordId === undefined || result.memoryRecordVersion === undefined
632
+ || result.memoryRecordDigest === undefined) {
633
+ throw new PersonalMemoryError('not-found', 'confirmed promotion result lost its Memory record');
634
+ }
635
+ return Object.freeze({
636
+ ...common, status: result.status,
637
+ memoryProposalId: result.memoryProposalId,
638
+ memoryProposalVersion: result.memoryProposalVersion,
639
+ memoryRecordId: result.memoryRecordId,
640
+ memoryRecordVersion: result.memoryRecordVersion,
641
+ memoryRecordDigest: result.memoryRecordDigest,
642
+ });
643
+ }
644
+ return Object.freeze({
645
+ ...common, status: result.status,
646
+ memoryProposalId: result.memoryProposalId,
647
+ memoryProposalVersion: result.memoryProposalVersion,
648
+ });
649
+ });
650
+ }
651
+ acknowledgePromotionResult(ack) {
652
+ this.assertActive();
653
+ const result = this.memoryStore.getPromotionResult(ack.promotionId, ack.promotionGeneration, ack.resultVersion);
654
+ if (result === undefined || result.receiptDigest !== ack.receiptDigest) {
655
+ throw new PersonalMemoryError('not-found', 'Preference promotion result acknowledgement changed identity');
656
+ }
657
+ this.memoryStore.completePromotionResult(result);
658
+ }
659
+ validatePromotionOwner(proposal) {
660
+ if (proposal.promotion === undefined || proposal.namespace.mode !== 'delivery')
661
+ return 'current';
662
+ const result = this.delivery?.prepareOwnerApprovalForPreference({
663
+ sourceId: APPROVAL_SOURCE_ID,
664
+ scope: proposal.promotion.scope,
665
+ principalId: proposal.principal,
666
+ principalLineage: {
667
+ principalRecordId: proposal.namespace.principalRecordId,
668
+ principalVersion: proposal.namespace.principalVersion,
669
+ },
670
+ ownerGeneration: proposal.promotion.ownerGeneration,
671
+ });
672
+ if (result === undefined) {
673
+ throw new PersonalMemoryError('missing-approval-route', 'Preference promotion owner resolver is unavailable');
674
+ }
675
+ if ('kind' in result)
676
+ return 'stale-owner';
677
+ return this.routeMatchesProposal(result, proposal) ? 'current' : 'stale-owner';
678
+ }
679
+ injectSessionSnapshot(agent) {
680
+ if (this.sessionSnapshots.has(agent))
681
+ return;
682
+ let context;
683
+ try {
684
+ context = this.agentContext(agent);
685
+ }
686
+ catch (error) {
687
+ if (error instanceof PersonalMemoryError && error.code === 'missing-identity')
688
+ return;
689
+ throw error;
690
+ }
691
+ const decision = this.policy.authorizeAgent(agent, 'snapshot', { kind: 'memory', id: 'visible' }, {
692
+ idempotencyKey: `memory-snapshot:${agent.id}`,
693
+ });
694
+ if (decision.effect !== 'allow')
695
+ return;
696
+ // Permanent session-start injection deliberately uses the default view,
697
+ // which excludes automatic records requiring a fresh source check.
698
+ const snapshot = this.memoryStore.snapshot({
699
+ context,
700
+ limit: this.config.snapshotLimit,
701
+ maxBytes: this.config.snapshotMaxBytes,
702
+ maxTokens: this.config.snapshotMaxTokens,
703
+ });
704
+ this.sessionSnapshots.set(agent, snapshot);
705
+ if (snapshot.text === '')
706
+ return;
707
+ agent.inject(createUserMessage({
708
+ content: [{ type: 'text', text: snapshot.text }],
709
+ source: { kind: 'personal-memory' },
710
+ }));
711
+ }
712
+ /** Fresh data at every model step; the Host persists superseding snapshots. */
713
+ taskSnapshot(agent) {
714
+ if (!this.active || agent === undefined)
715
+ return '';
716
+ try {
717
+ const context = this.agentContext(agent);
718
+ const decision = this.policy.authorizeAgent(agent, 'snapshot', { kind: 'memory', id: 'visible' });
719
+ if (decision.effect !== 'allow')
720
+ return '';
721
+ // Read the current surface, so replaced/compacted messages cannot become
722
+ // the active task again. Tool results and our own snapshots are not tasks.
723
+ const messages = agent.session.deriveMessages();
724
+ const humanTask = messages.findLast(message => {
725
+ if (message.role !== 'user' || !message.content.some(block => block.type === 'text'))
726
+ return false;
727
+ const kind = message.source?.kind;
728
+ return kind === 'user' || kind === 'delivery'
729
+ || kind === 'assistant-automations' || kind === 'plugin:@dsh-ray/assistant-automations';
730
+ });
731
+ let query = '';
732
+ for (const block of humanTask?.content ?? []) {
733
+ if (block.type !== 'text')
734
+ continue;
735
+ query += `${query === '' ? '' : '\n'}${block.text}`.slice(0, 2_048 - query.length);
736
+ if (query.length >= 2_048)
737
+ break;
738
+ }
739
+ let task;
740
+ try {
741
+ const goals = this.ctx.get('assistantGoals', false);
742
+ const goal = typeof goals?.taskContext === 'function' ? goals.taskContext(agent) : undefined;
743
+ if (goal?.protocol === 'goal-task-context/v1' && goal.active === true
744
+ && context.namespace.mode === 'delivery'
745
+ && goal.scope.workspace === context.workspace && goal.scope.preset === context.agentPreset
746
+ && goal.scope.principalRecordId === context.namespace.principalRecordId
747
+ && goal.scope.principalVersion === context.namespace.principalVersion
748
+ && memoryPrincipalDigest(goal.scope.principalId) === context.namespace.principalDigest) {
749
+ task = { objective: goal.goal.objective.slice(0, 2_048), nextStep: goal.checkpoint.nextStep.slice(0, 2_048), query };
750
+ }
751
+ }
752
+ catch { /* An absent, older, or invalid optional Goals service cannot suppress owner memory. */ }
753
+ const assoc = this.ctx.get('assistantAssociation', false);
754
+ let standingOnly = false;
755
+ try {
756
+ standingOnly = assoc?.shouldSuppressMemoryKeywordHits?.(agent) === true;
757
+ }
758
+ catch {
759
+ standingOnly = false;
760
+ }
761
+ const snapshot = () => this.memoryStore.snapshot({
762
+ context, query, ...(task === undefined ? {} : { task }),
763
+ ...(standingOnly ? { standingOnly: true } : {}),
764
+ limit: this.config.snapshotLimit,
765
+ maxBytes: this.config.snapshotMaxBytes,
766
+ maxTokens: this.config.snapshotMaxTokens,
767
+ }).text;
768
+ // Automatic facts/experiences need a current task, including for claim
769
+ // partners; the no-query fallback uses only the default manual view.
770
+ return standingOnly || query.trim() || task?.objective.trim() || task?.nextStep.trim()
771
+ ? this.withLearningVisibility(context, snapshot) : snapshot();
772
+ }
773
+ catch {
774
+ // Missing/revoked owner scope must clear the contribution, not retain an
775
+ // earlier owner's data or interrupt unrelated task execution.
776
+ return '';
777
+ }
778
+ }
779
+ assertMutationIdentity(context, mutation) {
780
+ const identity = mutation.identity;
781
+ if (identity.scope === 'workspace' && identity.workspace !== context.workspace) {
782
+ throw new PersonalMemoryError('identity-mismatch', 'workspace memory must target the current workspace');
783
+ }
784
+ if (identity.owner === 'agent' && identity.agentPreset !== context.agentPreset) {
785
+ throw new PersonalMemoryError('identity-mismatch', 'agent memory must target the current agent preset');
786
+ }
787
+ }
788
+ resolveApprovalRoute(agent, context, explicitPrincipal) {
789
+ if (this.delivery === undefined) {
790
+ if (this.config.approvalMode === 'delivery-required') {
791
+ throw new PersonalMemoryError('missing-approval-route', 'memory proposal requires an authenticated Delivery owner route');
792
+ }
793
+ if (explicitPrincipal === undefined || explicitPrincipal.trim() === '') {
794
+ throw new PersonalMemoryError('missing-approval-route', 'memory proposal requires an authenticated Delivery route or an explicit trusted headless principal');
795
+ }
796
+ const principalDigest = memoryPrincipalDigest(explicitPrincipal);
797
+ const namespace = Object.freeze({
798
+ mode: 'headless',
799
+ principalDigest,
800
+ lineageId: `headless:${principalDigest}`,
801
+ lineageVersion: 1,
802
+ });
803
+ if (agent !== undefined)
804
+ this.headlessNamespaces.set(agent, namespace);
805
+ return { principal: explicitPrincipal, namespace };
806
+ }
807
+ const dispatch = this.delivery.prepareAgentApproval(agent, {
808
+ sourceId: APPROVAL_SOURCE_ID,
809
+ });
810
+ if (dispatch.routeVersion !== 2
811
+ || dispatch.sourceId !== APPROVAL_SOURCE_ID
812
+ || dispatch.workspace !== context.workspace
813
+ || dispatch.bindingId.trim() === ''
814
+ || dispatch.principal.trim() === '') {
815
+ throw new PersonalMemoryError('missing-approval-route', 'memory proposal Delivery route does not match the current agent workspace');
816
+ }
817
+ if (explicitPrincipal !== undefined && explicitPrincipal !== dispatch.principal) {
818
+ throw new PersonalMemoryError('unauthorized-principal', 'memory proposal principal does not match the authenticated Delivery owner');
819
+ }
820
+ const namespace = Object.freeze({
821
+ mode: 'delivery',
822
+ principalDigest: memoryPrincipalDigest(dispatch.principal),
823
+ principalRecordId: dispatch.principalRecordId,
824
+ principalVersion: dispatch.principalVersion,
825
+ });
826
+ return { principal: dispatch.principal, namespace, dispatch };
827
+ }
828
+ agentContext(agent, explicitHeadlessPrincipal) {
829
+ const scope = this.agentScope(agent);
830
+ const attestation = agent !== undefined
831
+ && typeof this.delivery?.preferencePrincipalForAgent === 'function'
832
+ ? this.delivery.preferencePrincipalForAgent(agent)
833
+ : undefined;
834
+ if (attestation !== undefined
835
+ && attestation.scope.workspace === scope.workspace
836
+ && attestation.scope.preset === scope.agentPreset) {
837
+ return {
838
+ ...scope,
839
+ namespace: {
840
+ mode: 'delivery',
841
+ principalDigest: memoryPrincipalDigest(attestation.principalId),
842
+ principalRecordId: attestation.principalLineage.principalRecordId,
843
+ principalVersion: attestation.principalLineage.principalVersion,
844
+ },
845
+ };
846
+ }
847
+ const headless = agent === undefined ? undefined : this.headlessNamespaces.get(agent);
848
+ if (this.delivery === undefined && headless !== undefined)
849
+ return { ...scope, namespace: headless };
850
+ if (this.delivery === undefined && this.config.approvalMode === 'delivery-or-headless'
851
+ && explicitHeadlessPrincipal !== undefined && explicitHeadlessPrincipal.trim() !== '') {
852
+ const principalDigest = memoryPrincipalDigest(explicitHeadlessPrincipal);
853
+ const namespace = Object.freeze({
854
+ mode: 'headless',
855
+ principalDigest,
856
+ lineageId: `headless:${principalDigest}`,
857
+ lineageVersion: 1,
858
+ });
859
+ if (agent !== undefined)
860
+ this.headlessNamespaces.set(agent, namespace);
861
+ return { ...scope, namespace };
862
+ }
863
+ throw new PersonalMemoryError('missing-identity', 'memory operation requires a current authenticated owner namespace');
864
+ }
865
+ agentScope(agent) {
866
+ if (agent === undefined)
867
+ throw new PersonalMemoryError('missing-identity', 'memory operation requires an agent');
868
+ const workspace = agent.session.header.cwd;
869
+ const agentPreset = agent.session.header.agentPreset;
870
+ if (workspace === undefined || !isAbsolute(workspace) || agentPreset === undefined || agentPreset === '') {
871
+ throw new PersonalMemoryError('missing-identity', 'memory operation requires an absolute workspace and agent preset');
872
+ }
873
+ return { workspace, agentPreset };
874
+ }
875
+ routeMatchesPromotion(route, request) {
876
+ return route.routeVersion === 2
877
+ && route.sourceId === APPROVAL_SOURCE_ID
878
+ && route.workspace === request.scope.workspace
879
+ && route.principal === request.principalId
880
+ && route.principalRecordId === request.principalLineage.principalRecordId
881
+ && route.principalVersion === request.principalLineage.principalVersion
882
+ && route.bindingGeneration === request.ownerGeneration;
883
+ }
884
+ routeMatchesProposal(route, proposal) {
885
+ if (proposal.namespace.mode !== 'delivery' || proposal.promotion === undefined)
886
+ return false;
887
+ return route.routeVersion === 2
888
+ && route.sourceId === APPROVAL_SOURCE_ID
889
+ && route.workspace === proposal.promotion.scope.workspace
890
+ && route.principal === proposal.principal
891
+ && route.principalRecordId === proposal.namespace.principalRecordId
892
+ && route.principalVersion === proposal.namespace.principalVersion
893
+ && route.bindingGeneration === proposal.promotion.ownerGeneration;
894
+ }
895
+ assertActive() {
896
+ if (!this.active)
897
+ throw new PersonalMemoryError('disposed', 'personal-memory service is disposed');
898
+ }
899
+ }
900
+ //# sourceMappingURL=service.js.map