@steerable/agent-shell 0.12.7 → 0.13.1

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 (68) hide show
  1. package/dist/auth/credentials.d.ts +83 -0
  2. package/dist/auth/credentials.js +426 -0
  3. package/dist/auth/index.d.ts +33 -9
  4. package/dist/auth/index.js +85 -0
  5. package/dist/host/external-pack-loader.d.ts +40 -0
  6. package/dist/host/external-pack-loader.js +247 -0
  7. package/dist/host/http-routes.d.ts +6 -2
  8. package/dist/host/http-routes.js +5 -2
  9. package/dist/host/pack-assembly.d.ts +9 -1
  10. package/dist/host/runtime.js +54 -1
  11. package/dist/local-backend/coreloop-stream.d.ts +4 -0
  12. package/dist/local-backend/coreloop-stream.js +4 -0
  13. package/dist/local-backend/fact-chain.d.ts +38 -0
  14. package/dist/local-backend/fact-chain.js +145 -0
  15. package/dist/local-backend/router.d.ts +3 -1
  16. package/dist/local-backend/router.js +329 -35
  17. package/dist/local-backend/state-reconcile.d.ts +42 -0
  18. package/dist/local-backend/state-reconcile.js +81 -0
  19. package/dist/local-backend/title-refresh.d.ts +39 -0
  20. package/dist/local-backend/title-refresh.js +80 -0
  21. package/dist/local-backend/turn-security-context.d.ts +42 -0
  22. package/dist/local-backend/turn-security-context.js +62 -0
  23. package/dist/local-backend/ui-surface.d.ts +75 -0
  24. package/dist/local-backend/ui-surface.js +368 -0
  25. package/dist/local-executor.d.ts +3 -0
  26. package/dist/local-executor.js +40 -1
  27. package/dist/memory/authoring-candidates.d.ts +26 -0
  28. package/dist/memory/authoring-candidates.js +73 -0
  29. package/dist/memory/injector.d.ts +34 -0
  30. package/dist/memory/injector.js +111 -0
  31. package/dist/memory/routes.d.ts +16 -0
  32. package/dist/memory/routes.js +146 -0
  33. package/dist/memory/store.d.ts +176 -0
  34. package/dist/memory/store.js +623 -0
  35. package/dist/memory/tools.d.ts +83 -0
  36. package/dist/memory/tools.js +143 -0
  37. package/dist/present-files.d.ts +25 -1
  38. package/dist/present-files.js +170 -2
  39. package/dist/scenario/applications.d.ts +52 -0
  40. package/dist/scenario/applications.js +143 -0
  41. package/dist/scenario/pack.d.ts +1 -1
  42. package/dist/security/policy-digest.d.ts +28 -0
  43. package/dist/security/policy-digest.js +104 -0
  44. package/dist/server/http-server.js +23 -6
  45. package/dist/sidecar/boot.d.ts +1 -0
  46. package/dist/sidecar/boot.js +2 -0
  47. package/dist/sidecar/rejected-before-effect.d.ts +22 -0
  48. package/dist/sidecar/rejected-before-effect.js +63 -0
  49. package/dist/sidecar/reverse-approval.d.ts +2 -0
  50. package/dist/sidecar/reverse-approval.js +28 -5
  51. package/dist/sidecar/reverse-tools.d.ts +3 -0
  52. package/dist/sidecar/reverse-tools.js +129 -17
  53. package/dist/sidecar/types.d.ts +6 -0
  54. package/dist/storage/fde-fallback.d.ts +4 -0
  55. package/dist/storage/fde-fallback.js +354 -0
  56. package/dist/storage/fde-types.d.ts +215 -0
  57. package/dist/storage/fde-types.js +1 -0
  58. package/dist/storage/index.d.ts +113 -1
  59. package/dist/storage/index.js +797 -0
  60. package/dist/storage/insights-redact.d.ts +4 -1
  61. package/dist/storage/insights-redact.js +6 -1
  62. package/dist/storage/process-locks.d.ts +1 -1
  63. package/dist/storage/process-locks.js +1 -1
  64. package/dist/storage/scoped-store.d.ts +3 -1
  65. package/dist/tool-presentation.js +20 -0
  66. package/dist/tool-router.d.ts +20 -1
  67. package/dist/tool-router.js +76 -12
  68. package/package.json +5 -5
@@ -0,0 +1,623 @@
1
+ /**
2
+ * Dual-Layer Memory (`MEMORY.md` + `topics/*.md`) & Zero-Trust RSI store (Phase 9 R8).
3
+ *
4
+ * Storage & security invariants:
5
+ * 1. Never stored inside the workspace git tree: local desktop mirrors live under
6
+ * `<userDataDir>/memory/`, which is blocked from shell/file tools (`PRIVATE_DENY`).
7
+ * 2. Multi-tenant `ScopedStore` isolation across `user | workspace | tenant`:
8
+ * - `user`: strictly scoped to `principal.id`;
9
+ * - `workspace`: scoped to canonical workspace/project identifier;
10
+ * - `tenant`: readable by all members of `principal.tenantId`, writable ONLY by `principal.isAdmin`.
11
+ * 3. Capacity overflow throws `RejectedBeforeEffectError` (`MEMORY_CONSOLIDATION_REQUIRED`,
12
+ * `effect: 'none'`) — never silently truncates or FIFO-evicts user rules.
13
+ */
14
+ import { createHash, randomBytes } from 'node:crypto';
15
+ import fs from 'node:fs/promises';
16
+ import path from 'node:path';
17
+ import { LOCAL_DEFAULT_PRINCIPAL } from '../auth/index.js';
18
+ import { getUserDataDir } from '../runtime.js';
19
+ import { RejectedBeforeEffectError } from '../sidecar/rejected-before-effect.js';
20
+ import { ensurePhase9Store } from '../storage/fde-fallback.js';
21
+ export const MAX_MEMORY_INDEX_BYTES = 16 * 1024;
22
+ export const MAX_MEMORY_INDEX_LINES = 200;
23
+ export const MAX_MEMORY_TOPIC_BYTES = 32 * 1024;
24
+ export const MAX_MEMORY_TOTAL_BYTES = 256 * 1024;
25
+ export const TENANT_INJECT_BUDGET_BYTES = 2 * 1024;
26
+ export const WORKSPACE_INJECT_BUDGET_BYTES = 6 * 1024;
27
+ export const USER_INJECT_BUDGET_BYTES = 2 * 1024;
28
+ export const RSI_TTL_MS = 30 * 24 * 60 * 60 * 1000;
29
+ export const MEMORY_PERMISSION_SETTING_KEY = 'memory_permission_mode';
30
+ const META_SETTING_PREFIX = 'memory_rsi_meta:';
31
+ const REVOKED_SETTING_PREFIX = 'memory_revoked_set:';
32
+ const TOPICS_SETTING_PREFIX = 'memory_topics:';
33
+ const CONFLICTS_SETTING_PREFIX = 'memory_conflicts:';
34
+ export class MemoryAccessDeniedError extends Error {
35
+ status = 403;
36
+ code = 'memory_access_denied';
37
+ constructor(message) {
38
+ super(message);
39
+ this.name = 'MemoryAccessDeniedError';
40
+ }
41
+ }
42
+ export class MemoryBaseHashConflictError extends Error {
43
+ status = 409;
44
+ code = 'MEMORY_BASE_HASH_CONFLICT';
45
+ currentHash;
46
+ constructor(currentHash) {
47
+ super('Memory document changed concurrently (baseHash mismatch). Reload before saving.');
48
+ this.name = 'MemoryBaseHashConflictError';
49
+ this.currentHash = currentHash;
50
+ }
51
+ }
52
+ export function getHostMemoryRootDir() {
53
+ return path.join(getUserDataDir(), 'memory');
54
+ }
55
+ export function hashWorkspaceScopeId(workspacePathOrId) {
56
+ const trimmed = workspacePathOrId.trim();
57
+ if (!trimmed)
58
+ return 'default';
59
+ return createHash('sha256').update(trimmed, 'utf8').digest('hex').slice(0, 24);
60
+ }
61
+ export function sha256Text(text) {
62
+ return createHash('sha256').update(text, 'utf8').digest('hex');
63
+ }
64
+ export function normalizeMemoryParagraphHash(raw) {
65
+ const stripped = raw
66
+ .replace(/<!--\s*\/?refinement:[a-zA-Z0-9_-]+\s*-->/g, '')
67
+ .trim()
68
+ .replace(/\s+/g, ' ');
69
+ return sha256Text(stripped);
70
+ }
71
+ const REFINEMENT_BLOCK_RE = /<!--\s*refinement:([a-zA-Z0-9_-]+)\s*-->([\s\S]*?)<!--\s*\/refinement:\1\s*-->/g;
72
+ export function extractRefinementBlocks(markdown) {
73
+ const out = new Map();
74
+ REFINEMENT_BLOCK_RE.lastIndex = 0;
75
+ let match;
76
+ while ((match = REFINEMENT_BLOCK_RE.exec(markdown)) !== null) {
77
+ out.set(match[1], match[2].trim());
78
+ }
79
+ return out;
80
+ }
81
+ function containsWorkspaceSpecificPath(text) {
82
+ return /(?:^|\s)(?:\/[A-Za-z0-9._-]+){2,}|[A-Za-z]:\\[A-Za-z0-9._\\-]+/.test(text);
83
+ }
84
+ function resolveAuthoritativeScopeId(scope, requestedScopeId, principal) {
85
+ if (scope === 'user') {
86
+ if (requestedScopeId &&
87
+ requestedScopeId !== principal.id &&
88
+ requestedScopeId !== 'self') {
89
+ throw new MemoryAccessDeniedError(`Principal "${principal.id}" cannot access user memory belonging to "${requestedScopeId}".`);
90
+ }
91
+ return principal.id;
92
+ }
93
+ if (scope === 'tenant') {
94
+ const targetTenant = requestedScopeId?.trim() || principal.tenantId;
95
+ if (targetTenant !== principal.tenantId) {
96
+ throw new MemoryAccessDeniedError(`Principal "${principal.id}" cannot access tenant memory "${targetTenant}".`);
97
+ }
98
+ return principal.tenantId;
99
+ }
100
+ return requestedScopeId?.trim() || 'default';
101
+ }
102
+ function assertWritePermission(scope, principal) {
103
+ if (scope === 'tenant' && !principal.isAdmin) {
104
+ throw new MemoryAccessDeniedError('Only tenant administrators can modify tenant-wide shared memory.');
105
+ }
106
+ }
107
+ function enforceIndexCapacity(markdown) {
108
+ const bytes = Buffer.byteLength(markdown, 'utf8');
109
+ const lines = markdown.length === 0 ? 0 : markdown.split('\n').length;
110
+ if (bytes > MAX_MEMORY_INDEX_BYTES || lines > MAX_MEMORY_INDEX_LINES) {
111
+ throw RejectedBeforeEffectError.create('MEMORY_CONSOLIDATION_REQUIRED', `MEMORY.md exceeds capacity (${bytes}/${MAX_MEMORY_INDEX_BYTES} bytes, ${lines}/${MAX_MEMORY_INDEX_LINES} lines). Consolidate or move detailed notes to topics/*.md instead of evicting existing rules.`, true);
112
+ }
113
+ return { bytes, lines };
114
+ }
115
+ export class MemoryStore {
116
+ store;
117
+ constructor(store) {
118
+ this.store = store;
119
+ }
120
+ get p9() {
121
+ return ensurePhase9Store(this.store);
122
+ }
123
+ async getPermissionMode() {
124
+ const raw = await this.p9.getCustomSetting(MEMORY_PERMISSION_SETTING_KEY);
125
+ if (raw === 'off' || raw === 'ask' || raw === 'auto')
126
+ return raw;
127
+ return 'ask';
128
+ }
129
+ async setPermissionMode(mode) {
130
+ await this.p9.setCustomSetting(MEMORY_PERMISSION_SETTING_KEY, mode);
131
+ }
132
+ metaKey(scope, scopeId) {
133
+ return `${META_SETTING_PREFIX}${scope}:${scopeId}`;
134
+ }
135
+ revokedKey(scope, scopeId) {
136
+ return `${REVOKED_SETTING_PREFIX}${scope}:${scopeId}`;
137
+ }
138
+ topicsKey(scope, scopeId) {
139
+ return `${TOPICS_SETTING_PREFIX}${scope}:${scopeId}`;
140
+ }
141
+ conflictsKey(scope, scopeId) {
142
+ return `${CONFLICTS_SETTING_PREFIX}${scope}:${scopeId}`;
143
+ }
144
+ async loadMetaList(scope, scopeId) {
145
+ const raw = await this.p9.getCustomSetting(this.metaKey(scope, scopeId));
146
+ if (!raw)
147
+ return [];
148
+ try {
149
+ const parsed = JSON.parse(raw);
150
+ return Array.isArray(parsed) ? parsed : [];
151
+ }
152
+ catch {
153
+ return [];
154
+ }
155
+ }
156
+ async saveMetaList(scope, scopeId, items) {
157
+ await this.p9.setCustomSetting(this.metaKey(scope, scopeId), JSON.stringify(items));
158
+ }
159
+ async loadRevokedSet(scope, scopeId) {
160
+ const raw = await this.p9.getCustomSetting(this.revokedKey(scope, scopeId));
161
+ if (!raw)
162
+ return new Set();
163
+ try {
164
+ const parsed = JSON.parse(raw);
165
+ return Array.isArray(parsed)
166
+ ? new Set(parsed.filter((x) => typeof x === 'string'))
167
+ : new Set();
168
+ }
169
+ catch {
170
+ return new Set();
171
+ }
172
+ }
173
+ async saveRevokedSet(scope, scopeId, hashes) {
174
+ await this.p9.setCustomSetting(this.revokedKey(scope, scopeId), JSON.stringify([...hashes]));
175
+ }
176
+ async loadTopicsMap(scope, scopeId) {
177
+ const raw = await this.p9.getCustomSetting(this.topicsKey(scope, scopeId));
178
+ if (!raw)
179
+ return {};
180
+ try {
181
+ const parsed = JSON.parse(raw);
182
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
183
+ ? parsed
184
+ : {};
185
+ }
186
+ catch {
187
+ return {};
188
+ }
189
+ }
190
+ async saveTopicsMap(scope, scopeId, topics) {
191
+ await this.p9.setCustomSetting(this.topicsKey(scope, scopeId), JSON.stringify(topics));
192
+ }
193
+ async listConflicts(scope, requestedScopeId, principal = LOCAL_DEFAULT_PRINCIPAL) {
194
+ const scopeId = resolveAuthoritativeScopeId(scope, requestedScopeId, principal);
195
+ const raw = await this.p9.getCustomSetting(this.conflictsKey(scope, scopeId));
196
+ if (!raw)
197
+ return [];
198
+ try {
199
+ const parsed = JSON.parse(raw);
200
+ return Array.isArray(parsed) ? parsed : [];
201
+ }
202
+ catch {
203
+ return [];
204
+ }
205
+ }
206
+ async appendConflict(scope, scopeId, draft) {
207
+ const existing = await this.listConflicts(scope, scopeId, {
208
+ ...LOCAL_DEFAULT_PRINCIPAL,
209
+ id: scope === 'user' ? scopeId : LOCAL_DEFAULT_PRINCIPAL.id,
210
+ tenantId: scope === 'tenant' ? scopeId : LOCAL_DEFAULT_PRINCIPAL.tenantId,
211
+ isAdmin: true,
212
+ });
213
+ await this.p9.setCustomSetting(this.conflictsKey(scope, scopeId), JSON.stringify([...existing, draft]));
214
+ }
215
+ async mirrorToHostPrivateDisk(scope, scopeId, contentMarkdown) {
216
+ const root = getHostMemoryRootDir();
217
+ const dir = scope === 'workspace'
218
+ ? path.join(root, 'workspaces', hashWorkspaceScopeId(scopeId))
219
+ : path.join(root, scope, hashWorkspaceScopeId(scopeId));
220
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
221
+ await fs.writeFile(path.join(dir, 'MEMORY.md'), contentMarkdown, {
222
+ encoding: 'utf8',
223
+ mode: 0o600,
224
+ });
225
+ }
226
+ async readDocument(options) {
227
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
228
+ const scopeId = resolveAuthoritativeScopeId(options.scope, options.scopeId, principal);
229
+ const doc = await this.p9.getMemoryDocument(options.scope, scopeId);
230
+ const contentMarkdown = doc?.contentMarkdown ?? '';
231
+ const contentSha256 = doc?.contentSha256 ?? sha256Text('');
232
+ const bytesUsed = Buffer.byteLength(contentMarkdown, 'utf8');
233
+ const linesUsed = contentMarkdown.length === 0 ? 0 : contentMarkdown.split('\n').length;
234
+ const refinements = await this.loadMetaList(options.scope, scopeId);
235
+ const revoked = await this.loadRevokedSet(options.scope, scopeId);
236
+ const topicsMap = await this.loadTopicsMap(options.scope, scopeId);
237
+ const conflicts = await this.listConflicts(options.scope, scopeId, principal);
238
+ return {
239
+ scope: options.scope,
240
+ scopeId,
241
+ contentMarkdown,
242
+ contentSha256,
243
+ bytesUsed,
244
+ maxBytes: MAX_MEMORY_INDEX_BYTES,
245
+ linesUsed,
246
+ maxLines: MAX_MEMORY_INDEX_LINES,
247
+ refinements,
248
+ revokedHashes: [...revoked],
249
+ topics: Object.keys(topicsMap).sort(),
250
+ conflicts,
251
+ };
252
+ }
253
+ async writeDocument(options) {
254
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
255
+ const scopeId = resolveAuthoritativeScopeId(options.scope, options.scopeId, principal);
256
+ assertWritePermission(options.scope, principal);
257
+ const current = await this.p9.getMemoryDocument(options.scope, scopeId);
258
+ const currentHash = current?.contentSha256 ?? sha256Text('');
259
+ if (options.baseHash !== undefined &&
260
+ options.baseHash !== currentHash &&
261
+ !(current === null && options.baseHash === '')) {
262
+ throw new MemoryBaseHashConflictError(currentHash);
263
+ }
264
+ const { bytes, lines } = enforceIndexCapacity(options.contentMarkdown);
265
+ // Track human edits & manual deletions of <!-- refinement:<id> --> blocks
266
+ if (options.isHumanEdit) {
267
+ const metas = await this.loadMetaList(options.scope, scopeId);
268
+ if (metas.length > 0) {
269
+ const blocksAfter = extractRefinementBlocks(options.contentMarkdown);
270
+ const revoked = await this.loadRevokedSet(options.scope, scopeId);
271
+ const nextMetas = [];
272
+ for (const meta of metas) {
273
+ if (meta.status !== 'active') {
274
+ nextMetas.push(meta);
275
+ continue;
276
+ }
277
+ const updatedText = blocksAfter.get(meta.id);
278
+ if (updatedText === undefined) {
279
+ // Human manually deleted block -> mark withdrawn + permanently revoke hash
280
+ revoked.add(meta.normalizedHash);
281
+ nextMetas.push({ ...meta, status: 'withdrawn' });
282
+ }
283
+ else {
284
+ const newNorm = normalizeMemoryParagraphHash(updatedText);
285
+ if (newNorm !== meta.normalizedHash) {
286
+ nextMetas.push({
287
+ ...meta,
288
+ content: updatedText,
289
+ normalizedHash: newNorm,
290
+ humanEdited: true,
291
+ });
292
+ }
293
+ else {
294
+ nextMetas.push(meta);
295
+ }
296
+ }
297
+ }
298
+ await this.saveMetaList(options.scope, scopeId, nextMetas);
299
+ await this.saveRevokedSet(options.scope, scopeId, revoked);
300
+ }
301
+ }
302
+ const contentSha256 = sha256Text(options.contentMarkdown);
303
+ await this.p9.putMemoryDocument({
304
+ scopeKind: options.scope,
305
+ scopeId,
306
+ contentMarkdown: options.contentMarkdown,
307
+ contentSha256,
308
+ updatedBy: principal.id,
309
+ sourceChatId: options.sourceChatId ?? null,
310
+ });
311
+ await this.mirrorToHostPrivateDisk(options.scope, scopeId, options.contentMarkdown);
312
+ return {
313
+ contentMarkdown: options.contentMarkdown,
314
+ contentSha256,
315
+ bytesUsed: bytes,
316
+ linesUsed: lines,
317
+ };
318
+ }
319
+ async writeTopic(options) {
320
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
321
+ const scopeId = resolveAuthoritativeScopeId(options.scope, options.scopeId, principal);
322
+ assertWritePermission(options.scope, principal);
323
+ const cleanTopic = options.topicName.replace(/[^a-zA-Z0-9._-]/g, '_');
324
+ const topicBytes = Buffer.byteLength(options.contentMarkdown, 'utf8');
325
+ if (topicBytes > MAX_MEMORY_TOPIC_BYTES) {
326
+ throw RejectedBeforeEffectError.create('MEMORY_CONSOLIDATION_REQUIRED', `Topic "${cleanTopic}" exceeds ${MAX_MEMORY_TOPIC_BYTES} bytes.`, true);
327
+ }
328
+ const topics = await this.loadTopicsMap(options.scope, scopeId);
329
+ const nextTopics = { ...topics, [cleanTopic]: options.contentMarkdown };
330
+ const doc = await this.p9.getMemoryDocument(options.scope, scopeId);
331
+ const totalBytes = Buffer.byteLength(doc?.contentMarkdown ?? '', 'utf8') +
332
+ Object.values(nextTopics).reduce((acc, t) => acc + Buffer.byteLength(t, 'utf8'), 0);
333
+ if (totalBytes > MAX_MEMORY_TOTAL_BYTES) {
334
+ throw RejectedBeforeEffectError.create('MEMORY_CONSOLIDATION_REQUIRED', `Total memory usage (${totalBytes} bytes) exceeds ${MAX_MEMORY_TOTAL_BYTES} bytes.`, true);
335
+ }
336
+ await this.saveTopicsMap(options.scope, scopeId, nextTopics);
337
+ }
338
+ async readTopic(options) {
339
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
340
+ const scopeId = resolveAuthoritativeScopeId(options.scope, options.scopeId, principal);
341
+ const topics = await this.loadTopicsMap(options.scope, options.scopeId ? scopeId : scopeId);
342
+ const cleanTopic = options.topicName.replace(/[^a-zA-Z0-9._-]/g, '_');
343
+ return topics[cleanTopic] ?? null;
344
+ }
345
+ async search(options) {
346
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
347
+ const q = options.query.trim().toLowerCase();
348
+ if (!q)
349
+ return [];
350
+ const terms = q.split(/\s+/).filter(Boolean);
351
+ const scopes = [
352
+ { scope: 'tenant', scopeId: principal.tenantId },
353
+ { scope: 'workspace', scopeId: options.workspaceId || 'default' },
354
+ { scope: 'user', scopeId: principal.id },
355
+ ];
356
+ const hits = [];
357
+ for (const { scope, scopeId } of scopes) {
358
+ const doc = await this.p9.getMemoryDocument(scope, scopeId);
359
+ const sources = [['MEMORY.md', doc?.contentMarkdown ?? '']];
360
+ const topics = await this.loadTopicsMap(scope, scopeId);
361
+ for (const [k, v] of Object.entries(topics)) {
362
+ sources.push([`topics/${k}.md`, v]);
363
+ }
364
+ for (const [sourceName, body] of sources) {
365
+ if (!body)
366
+ continue;
367
+ for (const para of body.split(/\n{2,}/)) {
368
+ const lower = para.toLowerCase();
369
+ const score = terms.reduce((acc, term) => (lower.includes(term) ? acc + 1 : acc), 0);
370
+ if (score > 0) {
371
+ hits.push({
372
+ scope,
373
+ source: sourceName,
374
+ snippet: para.trim().slice(0, 300),
375
+ score,
376
+ });
377
+ }
378
+ }
379
+ }
380
+ }
381
+ return hits
382
+ .sort((a, b) => b.score - a.score)
383
+ .slice(0, 10)
384
+ .map(({ scope, source, snippet }) => ({ scope, source, snippet }));
385
+ }
386
+ async proposeRefinement(options) {
387
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
388
+ const scopeId = resolveAuthoritativeScopeId(options.scope, options.scopeId, principal);
389
+ assertWritePermission(options.scope, principal);
390
+ if (!options.evidence.chatId || (!options.evidence.turnId && !options.evidence.toolCallId)) {
391
+ throw RejectedBeforeEffectError.create('missing_refinement_evidence', 'RSI refinement requires an authoritative chatId and turnId/toolCallId.', false);
392
+ }
393
+ if (options.scope === 'user' && containsWorkspaceSpecificPath(options.content)) {
394
+ throw RejectedBeforeEffectError.create('cross_project_path_forbidden', 'Workspace-specific file paths cannot be promoted into cross-project user memory.', false);
395
+ }
396
+ const trimmed = options.content.trim();
397
+ const normHash = normalizeMemoryParagraphHash(trimmed);
398
+ const revoked = await this.loadRevokedSet(options.scope, scopeId);
399
+ const dbRevoked = await this.p9.isMemoryHashRevoked(options.scope, scopeId, normHash);
400
+ if (revoked.has(normHash) || dbRevoked) {
401
+ return { accepted: false, reason: 'user_revoked' };
402
+ }
403
+ const metas = await this.loadMetaList(options.scope, scopeId);
404
+ if (options.id) {
405
+ const existingById = metas.find((m) => m.id === options.id);
406
+ if (existingById?.humanEdited) {
407
+ const draft = {
408
+ id: `conflict_${randomBytes(4).toString('hex')}`,
409
+ targetRefinementId: existingById.id,
410
+ proposedContent: trimmed,
411
+ createdAt: new Date(options.nowMs ?? Date.now()).toISOString(),
412
+ };
413
+ await this.appendConflict(options.scope, scopeId, draft);
414
+ return {
415
+ accepted: false,
416
+ reason: 'human_edited_conflict',
417
+ conflictDraft: draft,
418
+ };
419
+ }
420
+ }
421
+ const refId = options.id || `r${randomBytes(5).toString('hex')}`;
422
+ const now = options.nowMs ?? Date.now();
423
+ const createdAt = new Date(now).toISOString();
424
+ const expiresAt = new Date(now + RSI_TTL_MS).toISOString();
425
+ const currentDoc = await this.p9.getMemoryDocument(options.scope, scopeId);
426
+ const prevMd = currentDoc?.contentMarkdown ?? '';
427
+ const wrapped = `<!-- refinement:${refId} -->\n${trimmed}\n<!-- /refinement:${refId} -->`;
428
+ const nextMd = prevMd.trim() ? `${prevMd.trimEnd()}\n\n${wrapped}\n` : `${wrapped}\n`;
429
+ enforceIndexCapacity(nextMd);
430
+ const meta = {
431
+ id: refId,
432
+ normalizedHash: normHash,
433
+ scope: options.scope,
434
+ scopeId,
435
+ content: trimmed,
436
+ evidence: options.evidence,
437
+ humanEdited: false,
438
+ status: 'active',
439
+ createdAt,
440
+ expiresAt,
441
+ };
442
+ const filteredMetas = metas.filter((m) => m.id !== refId);
443
+ await this.saveMetaList(options.scope, scopeId, [...filteredMetas, meta]);
444
+ await this.p9.putMemoryDocument({
445
+ scopeKind: options.scope,
446
+ scopeId,
447
+ contentMarkdown: nextMd,
448
+ contentSha256: sha256Text(nextMd),
449
+ updatedBy: principal.id,
450
+ sourceChatId: options.evidence.chatId,
451
+ });
452
+ await this.mirrorToHostPrivateDisk(options.scope, scopeId, nextMd);
453
+ return { accepted: true, meta };
454
+ }
455
+ async findRefinementAcrossScopes(refinementId, principal, hintWorkspaceId) {
456
+ const candidates = [
457
+ ['user', principal.id],
458
+ ['workspace', hintWorkspaceId || 'default'],
459
+ ['tenant', principal.tenantId],
460
+ ];
461
+ for (const [scope, scopeId] of candidates) {
462
+ const metas = await this.loadMetaList(scope, scopeId);
463
+ const index = metas.findIndex((m) => m.id === refinementId);
464
+ if (index >= 0) {
465
+ return { scope, scopeId, metas, index };
466
+ }
467
+ }
468
+ return null;
469
+ }
470
+ async renewRefinement(options) {
471
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
472
+ const found = await this.findRefinementAcrossScopes(options.refinementId, principal, options.workspaceId);
473
+ if (!found)
474
+ return null;
475
+ assertWritePermission(found.scope, principal);
476
+ const now = options.nowMs ?? Date.now();
477
+ const updated = {
478
+ ...found.metas[found.index],
479
+ status: 'active',
480
+ expiresAt: new Date(now + RSI_TTL_MS).toISOString(),
481
+ };
482
+ const next = [...found.metas];
483
+ next[found.index] = updated;
484
+ await this.saveMetaList(found.scope, found.scopeId, next);
485
+ return updated;
486
+ }
487
+ async convertRefinementToOrdinary(options) {
488
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
489
+ const found = await this.findRefinementAcrossScopes(options.refinementId, principal, options.workspaceId);
490
+ if (!found)
491
+ return null;
492
+ assertWritePermission(found.scope, principal);
493
+ const target = found.metas[found.index];
494
+ const updated = {
495
+ ...target,
496
+ status: 'ordinary',
497
+ expiresAt: null,
498
+ };
499
+ const next = [...found.metas];
500
+ next[found.index] = updated;
501
+ await this.saveMetaList(found.scope, found.scopeId, next);
502
+ const doc = await this.p9.getMemoryDocument(found.scope, found.scopeId);
503
+ if (doc) {
504
+ const blockRe = new RegExp(`<!--\\s*refinement:${target.id}\\s*-->([\\s\\S]*?)<!--\\s*\\/refinement:${target.id}\\s*-->`, 'g');
505
+ const unwrapped = doc.contentMarkdown.replace(blockRe, (_m, inner) => inner.trim());
506
+ await this.p9.putMemoryDocument({
507
+ scopeKind: found.scope,
508
+ scopeId: found.scopeId,
509
+ contentMarkdown: unwrapped,
510
+ contentSha256: sha256Text(unwrapped),
511
+ updatedBy: principal.id,
512
+ });
513
+ await this.mirrorToHostPrivateDisk(found.scope, found.scopeId, unwrapped);
514
+ }
515
+ return updated;
516
+ }
517
+ async withdrawRefinement(options) {
518
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
519
+ const found = await this.findRefinementAcrossScopes(options.refinementId, principal, options.workspaceId);
520
+ if (!found)
521
+ return null;
522
+ assertWritePermission(found.scope, principal);
523
+ const target = found.metas[found.index];
524
+ const updated = {
525
+ ...target,
526
+ status: 'withdrawn',
527
+ };
528
+ const next = [...found.metas];
529
+ next[found.index] = updated;
530
+ await this.saveMetaList(found.scope, found.scopeId, next);
531
+ const revoked = await this.loadRevokedSet(found.scope, found.scopeId);
532
+ revoked.add(target.normalizedHash);
533
+ await this.saveRevokedSet(found.scope, found.scopeId, revoked);
534
+ // Also record in DB entry table so SQLite/MySQL queries see the revoked hash
535
+ const entryRes = await this.p9.upsertMemoryEntry({
536
+ scopeKind: found.scope,
537
+ scopeId: found.scopeId,
538
+ content: target.content,
539
+ contentSha256: target.normalizedHash,
540
+ });
541
+ if (!entryRes.skippedRevoked) {
542
+ await this.p9.revokeMemoryEntry(entryRes.entry.id);
543
+ }
544
+ const doc = await this.p9.getMemoryDocument(found.scope, found.scopeId);
545
+ if (doc) {
546
+ const blockRe = new RegExp(`\\n*<!--\\s*refinement:${target.id}\\s*-->[\\s\\S]*?<!--\\s*\\/refinement:${target.id}\\s*-->\\n*`, 'g');
547
+ const cleaned = doc.contentMarkdown.replace(blockRe, '\n').trim();
548
+ const finalMd = cleaned ? `${cleaned}\n` : '';
549
+ await this.p9.putMemoryDocument({
550
+ scopeKind: found.scope,
551
+ scopeId: found.scopeId,
552
+ contentMarkdown: finalMd,
553
+ contentSha256: sha256Text(finalMd),
554
+ updatedBy: principal.id,
555
+ });
556
+ await this.mirrorToHostPrivateDisk(found.scope, found.scopeId, finalMd);
557
+ }
558
+ return updated;
559
+ }
560
+ async unrevokeHash(options) {
561
+ const principal = options.principal ?? LOCAL_DEFAULT_PRINCIPAL;
562
+ const scopeId = resolveAuthoritativeScopeId(options.scope, options.scopeId, principal);
563
+ assertWritePermission(options.scope, principal);
564
+ const revoked = await this.loadRevokedSet(options.scope, scopeId);
565
+ const existed = revoked.delete(options.hash);
566
+ if (existed) {
567
+ await this.saveRevokedSet(options.scope, scopeId, revoked);
568
+ }
569
+ return existed;
570
+ }
571
+ /**
572
+ * Renders active, non-expired, non-revoked markdown for a single scope within
573
+ * `budgetBytes`, preserving original source text on disk even when expired.
574
+ */
575
+ async renderVisibleMarkdownForScope(options) {
576
+ const doc = await this.p9.getMemoryDocument(options.scope, options.scopeId);
577
+ if (!doc || !doc.contentMarkdown.trim())
578
+ return '';
579
+ const metas = await this.loadMetaList(options.scope, options.scopeId);
580
+ const metaById = new Map(metas.map((m) => [m.id, m]));
581
+ const revoked = await this.loadRevokedSet(options.scope, options.scopeId);
582
+ const now = options.nowMs ?? Date.now();
583
+ const filtered = doc.contentMarkdown.replace(REFINEMENT_BLOCK_RE, (_full, id, inner) => {
584
+ const meta = metaById.get(id);
585
+ if (!meta)
586
+ return inner.trim();
587
+ if (meta.status === 'withdrawn')
588
+ return '';
589
+ if (revoked.has(meta.normalizedHash))
590
+ return '';
591
+ if (meta.status === 'active' && meta.expiresAt !== null) {
592
+ const exp = Date.parse(meta.expiresAt);
593
+ if (!Number.isNaN(exp) && now >= exp) {
594
+ return '';
595
+ }
596
+ }
597
+ return inner.trim();
598
+ });
599
+ const paragraphs = filtered
600
+ .split(/\n{2,}/)
601
+ .map((p) => p.trim())
602
+ .filter((p) => p.length > 0 && !revoked.has(normalizeMemoryParagraphHash(p)));
603
+ if (paragraphs.length === 0)
604
+ return '';
605
+ const kept = [];
606
+ let usedBytes = 0;
607
+ let omittedCount = 0;
608
+ for (const para of paragraphs) {
609
+ const candidateBytes = Buffer.byteLength(para, 'utf8') + (kept.length > 0 ? 2 : 0);
610
+ if (usedBytes + candidateBytes <= options.budgetBytes) {
611
+ kept.push(para);
612
+ usedBytes += candidateBytes;
613
+ }
614
+ else {
615
+ omittedCount += 1;
616
+ }
617
+ }
618
+ if (omittedCount > 0) {
619
+ kept.push(`[... ${omittedCount} additional paragraph(s) omitted by budget; call memory_read / memory_search for details]`);
620
+ }
621
+ return kept.join('\n\n');
622
+ }
623
+ }