@dsh-ray/assistant-proactive 0.2.4 → 0.3.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.
@@ -0,0 +1,1718 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm';
7
+ import { defineTool } from '@deepseek-ai/dsh-tools';
8
+ const DEFAULT_TUNING = {
9
+ naturalMentionThreshold: 0.55,
10
+ proposeWorkThreshold: 0.72,
11
+ silentExploreThreshold: 0.35,
12
+ dailyNaturalMentionCap: 3,
13
+ updatedAt: 0,
14
+ };
15
+ const MAX_CANDIDATE_OUTCOMES = 200;
16
+ const SEVEN_DAYS_MS = 7 * 86_400_000;
17
+ const ONE_DAY_MS = 86_400_000;
18
+ const THIRTY_DAYS_MS = 30 * 86_400_000;
19
+ const SYNTHETIC_USER_SOURCE_KINDS = new Set([
20
+ 'runtime-context',
21
+ 'system-prompt',
22
+ 'personal-memory',
23
+ 'skill-catalog',
24
+ 'ray-episodic',
25
+ 'assistant-proactive',
26
+ 'assistant-dreaming',
27
+ 'ray-worker',
28
+ 'ray-worker-handback',
29
+ 'compaction',
30
+ 'tool-result',
31
+ 'goal',
32
+ ]);
33
+ export function isHumanUserMessage(message) {
34
+ if (message.role !== 'user')
35
+ return false;
36
+ const kind = typeof message.source?.kind === 'string' ? message.source.kind : '';
37
+ return !SYNTHETIC_USER_SOURCE_KINDS.has(kind);
38
+ }
39
+ function clamp(value, min, max) {
40
+ if (!Number.isFinite(value))
41
+ return min;
42
+ return Math.max(min, Math.min(max, Number(value.toFixed(4))));
43
+ }
44
+ function tokenize(text) {
45
+ const tokens = new Set();
46
+ const lower = text.toLowerCase();
47
+ for (const raw of lower.match(/[a-z0-9_.:=-]{2,}/gu) ?? []) {
48
+ const clean = raw.replace(/^[._:=-]+|[._:=-]+$/gu, '');
49
+ if (clean.length >= 2)
50
+ tokens.add(clean);
51
+ for (const part of clean.split(/[._:=-]+/gu)) {
52
+ if (part.length >= 2)
53
+ tokens.add(part);
54
+ }
55
+ }
56
+ for (const run of lower.match(/[\u4e00-\u9fff]{2,}/gu) ?? []) {
57
+ tokens.add(run);
58
+ for (let i = 0; i + 2 <= run.length; i += 1)
59
+ tokens.add(run.slice(i, i + 2));
60
+ }
61
+ return tokens;
62
+ }
63
+ function tokenOverlap(a, b) {
64
+ if (a.size === 0 || b.size === 0)
65
+ return 0;
66
+ let hits = 0;
67
+ for (const item of a) {
68
+ if (b.has(item))
69
+ hits += 1;
70
+ }
71
+ return hits / Math.min(a.size, b.size);
72
+ }
73
+ function dayStartMs(atMs) {
74
+ const d = new Date(atMs);
75
+ d.setHours(0, 0, 0, 0);
76
+ return d.getTime();
77
+ }
78
+ function rowToIdea(row) {
79
+ return {
80
+ ideaId: row.idea_id,
81
+ source: row.source,
82
+ title: row.title,
83
+ summary: row.summary,
84
+ topic: row.topic,
85
+ interestScore: row.interest_score,
86
+ ownerValueScore: row.owner_value_score,
87
+ combinedScore: row.combined_score,
88
+ tier: row.tier,
89
+ status: row.status,
90
+ ...(row.exploration_note === null ? {} : { explorationNote: row.exploration_note }),
91
+ mentionCount: row.mention_count,
92
+ ...(row.last_mentioned_at == null ? {} : { lastMentionedAt: row.last_mentioned_at }),
93
+ requiresExternalEffect: row.requires_external_effect === 1,
94
+ createdAt: row.created_at,
95
+ updatedAt: row.updated_at,
96
+ };
97
+ }
98
+ export class RayCognitiveLoopRuntime {
99
+ ctx;
100
+ databasePath;
101
+ tuningPath;
102
+ reflectionsDir;
103
+ taughtReflectionsPath;
104
+ taughtMemoriesPath;
105
+ rayHome;
106
+ policy;
107
+ raySelf;
108
+ db;
109
+ disposers = [];
110
+ abortController = new AbortController();
111
+ inFlightTasks = new Set();
112
+ processedTurns = new Set();
113
+ jsonlLocks = new Map();
114
+ runDetached = AsyncLocalStorage.snapshot();
115
+ schedulerOptions;
116
+ bootedAt;
117
+ lastDailyAt;
118
+ lastWeeklyAt;
119
+ lastStageAt;
120
+ tuning;
121
+ taughtReflectionsCache;
122
+ taughtMemoriesCache;
123
+ closed = false;
124
+ disposePromise;
125
+ constructor(ctx, policy, raySelf, schedulerOptions = {}) {
126
+ this.ctx = ctx;
127
+ this.policy = policy;
128
+ this.raySelf = raySelf;
129
+ this.rayHome = raySelf.rayHome;
130
+ this.schedulerOptions = schedulerOptions;
131
+ this.bootedAt = Date.now();
132
+ this.lastDailyAt = this.bootedAt;
133
+ this.lastWeeklyAt = this.bootedAt;
134
+ this.lastStageAt = this.bootedAt;
135
+ this.databasePath = join(this.rayHome, 'ideas', 'ideas.sqlite');
136
+ this.tuningPath = join(this.rayHome, 'ideas', 'tuning.json');
137
+ this.reflectionsDir = join(this.rayHome, 'reflections');
138
+ this.taughtReflectionsPath = join(this.reflectionsDir, 'taught.jsonl');
139
+ this.taughtMemoriesPath = join(this.rayHome, 'state', 'taught-memories.jsonl');
140
+ mkdirSync(dirname(this.databasePath), { recursive: true, mode: 0o700 });
141
+ mkdirSync(this.reflectionsDir, { recursive: true, mode: 0o700 });
142
+ this.tuning = this.loadOrCreateTuning();
143
+ this.openDb();
144
+ try {
145
+ this.raySelf.registerDatabase('assistant-proactive/ideas', this.databasePath);
146
+ }
147
+ catch {
148
+ // Ignore if manifest not writable in stripped test harness.
149
+ }
150
+ if (typeof this.raySelf.registerDatabaseParticipant === 'function') {
151
+ this.disposers.push(this.raySelf.registerDatabaseParticipant({
152
+ id: 'assistant-proactive:cognitive',
153
+ checkpoint: () => this.checkpoint(),
154
+ beforeCloneImport: () => this.closeForReload(),
155
+ afterCloneImport: () => this.reopen(),
156
+ }));
157
+ }
158
+ const raySelfEvents = this.raySelf;
159
+ if (typeof raySelfEvents.onTeachingPackImported === 'function') {
160
+ this.disposers.push(raySelfEvents.onTeachingPackImported(() => {
161
+ this.invalidateTaughtCaches();
162
+ }));
163
+ }
164
+ if (typeof raySelfEvents.onCloneImported === 'function') {
165
+ this.disposers.push(raySelfEvents.onCloneImported(() => {
166
+ this.invalidateTaughtCaches();
167
+ }));
168
+ }
169
+ this.installDreamingBridge();
170
+ this.installPromptIntegration();
171
+ this.installToolsIntegration();
172
+ this.installReflectionScheduler();
173
+ }
174
+ invalidateTaughtCaches() {
175
+ this.taughtReflectionsCache = undefined;
176
+ this.taughtMemoriesCache = undefined;
177
+ }
178
+ trackTask(task) {
179
+ if (this.closed)
180
+ return;
181
+ const tracked = task.catch(() => { }).finally(() => {
182
+ this.inFlightTasks.delete(tracked);
183
+ });
184
+ this.inFlightTasks.add(tracked);
185
+ }
186
+ withJsonlLock(cadence, op) {
187
+ const prev = this.jsonlLocks.get(cadence) ?? Promise.resolve();
188
+ const next = prev.catch(() => { }).then(op);
189
+ this.jsonlLocks.set(cadence, next);
190
+ return next;
191
+ }
192
+ openDb() {
193
+ mkdirSync(dirname(this.databasePath), { recursive: true, mode: 0o700 });
194
+ mkdirSync(this.reflectionsDir, { recursive: true, mode: 0o700 });
195
+ const db = new DatabaseSync(this.databasePath);
196
+ db.exec('PRAGMA journal_mode = WAL;');
197
+ db.exec('PRAGMA synchronous = NORMAL;');
198
+ db.exec('PRAGMA busy_timeout = 5000;');
199
+ db.exec(`
200
+ CREATE TABLE IF NOT EXISTS ray_ideas (
201
+ idea_id TEXT PRIMARY KEY,
202
+ source TEXT NOT NULL,
203
+ title TEXT NOT NULL,
204
+ summary TEXT NOT NULL,
205
+ topic TEXT NOT NULL,
206
+ interest_score REAL NOT NULL,
207
+ owner_value_score REAL NOT NULL,
208
+ combined_score REAL NOT NULL,
209
+ tier TEXT NOT NULL CHECK(tier IN ('silent_explore','natural_mention','propose_work','hold')),
210
+ status TEXT NOT NULL CHECK(status IN ('pooled','explored','mentioned','proposed','accepted','ignored','annoyed','rejected')),
211
+ exploration_note TEXT,
212
+ mention_count INTEGER NOT NULL DEFAULT 0,
213
+ last_mentioned_at INTEGER,
214
+ requires_external_effect INTEGER NOT NULL DEFAULT 0,
215
+ created_at INTEGER NOT NULL,
216
+ updated_at INTEGER NOT NULL
217
+ );
218
+ CREATE INDEX IF NOT EXISTS idx_ray_ideas_tier_status ON ray_ideas(tier, status, updated_at DESC);
219
+ CREATE TABLE IF NOT EXISTS ray_candidate_outcomes (
220
+ record_id TEXT PRIMARY KEY,
221
+ candidate_id TEXT NOT NULL,
222
+ kind TEXT NOT NULL,
223
+ root_cause TEXT NOT NULL,
224
+ predicted_impact TEXT NOT NULL,
225
+ observed_outcome TEXT NOT NULL,
226
+ supplier TEXT NOT NULL,
227
+ disposition TEXT NOT NULL CHECK(disposition IN ('adopted','vetoed','rolled_back','rejected')),
228
+ created_at INTEGER NOT NULL
229
+ );
230
+ CREATE INDEX IF NOT EXISTS idx_ray_candidate_outcomes_created ON ray_candidate_outcomes(created_at DESC);
231
+ CREATE TABLE IF NOT EXISTS ray_reflections (
232
+ reflection_id TEXT PRIMARY KEY,
233
+ cadence TEXT NOT NULL CHECK(cadence IN ('aftertaste','daily-diary','weekly-review','stage-review')),
234
+ summary TEXT NOT NULL,
235
+ tokens_used INTEGER NOT NULL DEFAULT 0,
236
+ artifact_path TEXT NOT NULL,
237
+ created_at INTEGER NOT NULL
238
+ );
239
+ CREATE INDEX IF NOT EXISTS idx_ray_reflections_cadence ON ray_reflections(cadence, created_at DESC);
240
+ `);
241
+ const ideaCols = db.prepare('PRAGMA table_info(ray_ideas)').all();
242
+ if (!ideaCols.some(c => c.name === 'last_mentioned_at')) {
243
+ db.exec('ALTER TABLE ray_ideas ADD COLUMN last_mentioned_at INTEGER;');
244
+ }
245
+ this.db = db;
246
+ try {
247
+ chmodSync(this.databasePath, 0o600);
248
+ }
249
+ catch { /* ignore */ }
250
+ }
251
+ checkpoint() {
252
+ if (this.closed || this.db === undefined)
253
+ return;
254
+ try {
255
+ this.db.exec('PRAGMA wal_checkpoint(TRUNCATE);');
256
+ }
257
+ catch { /* ignore */ }
258
+ }
259
+ closeForReload() {
260
+ if (this.closed || this.db === undefined)
261
+ return;
262
+ try {
263
+ this.db.close();
264
+ }
265
+ catch { /* ignore */ }
266
+ this.db = undefined;
267
+ }
268
+ reopen() {
269
+ if (this.closed)
270
+ return;
271
+ this.closeForReload();
272
+ this.invalidateTaughtCaches();
273
+ this.tuning = this.loadOrCreateTuning();
274
+ this.openDb();
275
+ }
276
+ parseTaughtProvenance(parsed) {
277
+ const prov = (parsed['provenance'] !== null && typeof parsed['provenance'] === 'object' && !Array.isArray(parsed['provenance']))
278
+ ? parsed['provenance']
279
+ : undefined;
280
+ const teacherRayId = (typeof prov?.['teacherRayId'] === 'string' && prov['teacherRayId'].trim() !== '')
281
+ ? prov['teacherRayId'].trim()
282
+ : (typeof parsed['teacherRayId'] === 'string' && parsed['teacherRayId'].trim() !== '' ? parsed['teacherRayId'].trim() : undefined);
283
+ const teacherName = (typeof prov?.['teacherName'] === 'string' && prov['teacherName'].trim() !== '')
284
+ ? prov['teacherName'].trim()
285
+ : (typeof parsed['teacherName'] === 'string' && parsed['teacherName'].trim() !== '' ? parsed['teacherName'].trim() : undefined);
286
+ const importedAt = typeof prov?.['importedAt'] === 'number' && Number.isFinite(prov['importedAt'])
287
+ ? Math.trunc(prov['importedAt'])
288
+ : undefined;
289
+ return {
290
+ origin: 'taught',
291
+ ...(teacherRayId === undefined ? {} : { teacherRayId }),
292
+ ...(teacherName === undefined ? {} : { teacherName }),
293
+ ...(importedAt === undefined ? {} : { importedAt }),
294
+ };
295
+ }
296
+ loadTaughtReflections() {
297
+ if (this.closed)
298
+ return [];
299
+ if (!existsSync(this.taughtReflectionsPath)) {
300
+ this.taughtReflectionsCache = undefined;
301
+ return [];
302
+ }
303
+ const st = statSync(this.taughtReflectionsPath);
304
+ if (this.taughtReflectionsCache !== undefined
305
+ && this.taughtReflectionsCache.mtimeMs === st.mtimeMs
306
+ && this.taughtReflectionsCache.size === st.size) {
307
+ return this.taughtReflectionsCache.records;
308
+ }
309
+ const records = [];
310
+ const lines = readFileSync(this.taughtReflectionsPath, 'utf8').split('\n');
311
+ for (let idx = 0; idx < lines.length; idx += 1) {
312
+ const clean = lines[idx].trim();
313
+ if (clean === '')
314
+ continue;
315
+ let parsed;
316
+ try {
317
+ const val = JSON.parse(clean);
318
+ if (val === null || typeof val !== 'object' || Array.isArray(val))
319
+ continue;
320
+ parsed = val;
321
+ }
322
+ catch {
323
+ continue;
324
+ }
325
+ const summary = typeof parsed['summary'] === 'string'
326
+ ? parsed['summary'].trim()
327
+ : typeof parsed['text'] === 'string'
328
+ ? parsed['text'].trim()
329
+ : typeof parsed['title'] === 'string'
330
+ ? parsed['title'].trim()
331
+ : '';
332
+ if (summary === '')
333
+ continue;
334
+ const provenance = this.parseTaughtProvenance(parsed);
335
+ const reflectionId = typeof parsed['reflectionId'] === 'string' && parsed['reflectionId'].trim() !== ''
336
+ ? parsed['reflectionId'].trim()
337
+ : `trefl-${createHash('sha256').update(clean, 'utf8').digest('hex').slice(0, 16)}`;
338
+ const cadence = typeof parsed['cadence'] === 'string' && parsed['cadence'].trim() !== ''
339
+ ? parsed['cadence'].trim()
340
+ : 'taught';
341
+ const createdAt = typeof parsed['createdAt'] === 'number' && Number.isFinite(parsed['createdAt'])
342
+ ? Math.trunc(parsed['createdAt'])
343
+ : st.mtimeMs;
344
+ records.push({
345
+ reflectionId,
346
+ cadence,
347
+ summary,
348
+ createdAt,
349
+ provenance,
350
+ });
351
+ }
352
+ this.taughtReflectionsCache = { mtimeMs: st.mtimeMs, size: st.size, records };
353
+ return records;
354
+ }
355
+ loadTaughtMemories() {
356
+ if (this.closed)
357
+ return [];
358
+ if (!existsSync(this.taughtMemoriesPath)) {
359
+ this.taughtMemoriesCache = undefined;
360
+ return [];
361
+ }
362
+ const st = statSync(this.taughtMemoriesPath);
363
+ if (this.taughtMemoriesCache !== undefined
364
+ && this.taughtMemoriesCache.mtimeMs === st.mtimeMs
365
+ && this.taughtMemoriesCache.size === st.size) {
366
+ return this.taughtMemoriesCache.records;
367
+ }
368
+ const records = [];
369
+ const lines = readFileSync(this.taughtMemoriesPath, 'utf8').split('\n');
370
+ for (let idx = 0; idx < lines.length; idx += 1) {
371
+ const clean = lines[idx].trim();
372
+ if (clean === '')
373
+ continue;
374
+ let parsed;
375
+ try {
376
+ const val = JSON.parse(clean);
377
+ if (val === null || typeof val !== 'object' || Array.isArray(val))
378
+ continue;
379
+ parsed = val;
380
+ }
381
+ catch {
382
+ continue;
383
+ }
384
+ const content = typeof parsed['content'] === 'string' ? parsed['content'].trim() : '';
385
+ if (content === '')
386
+ continue;
387
+ const provenance = this.parseTaughtProvenance(parsed);
388
+ const id = typeof parsed['id'] === 'string' && parsed['id'].trim() !== ''
389
+ ? parsed['id'].trim()
390
+ : `tmem-${createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16)}`;
391
+ const kind = typeof parsed['kind'] === 'string' && parsed['kind'].trim() !== ''
392
+ ? parsed['kind'].trim()
393
+ : 'semantic';
394
+ const createdAt = typeof parsed['createdAt'] === 'number' && Number.isFinite(parsed['createdAt'])
395
+ ? Math.trunc(parsed['createdAt'])
396
+ : st.mtimeMs;
397
+ records.push({
398
+ id,
399
+ kind,
400
+ content,
401
+ createdAt,
402
+ provenance,
403
+ });
404
+ }
405
+ this.taughtMemoriesCache = { mtimeMs: st.mtimeMs, size: st.size, records };
406
+ return records;
407
+ }
408
+ listTaughtReflections(limit = 20) {
409
+ const bound = Math.max(1, Math.min(100, Math.trunc(limit)));
410
+ return [...this.loadTaughtReflections()]
411
+ .sort((a, b) => b.createdAt - a.createdAt)
412
+ .slice(0, bound);
413
+ }
414
+ listTaughtMemories(limit = 20) {
415
+ const bound = Math.max(1, Math.min(100, Math.trunc(limit)));
416
+ return [...this.loadTaughtMemories()]
417
+ .sort((a, b) => b.createdAt - a.createdAt)
418
+ .slice(0, bound);
419
+ }
420
+ findRelevantTaughtWisdom(query, limit = 6) {
421
+ const bound = Math.max(1, Math.min(50, Math.trunc(limit)));
422
+ const cleanQuery = query.trim();
423
+ const allReflections = this.loadTaughtReflections();
424
+ const allMemories = this.loadTaughtMemories();
425
+ if (cleanQuery === '') {
426
+ return {
427
+ reflections: [...allReflections].sort((a, b) => b.createdAt - a.createdAt).slice(0, bound),
428
+ memories: [...allMemories].sort((a, b) => b.createdAt - a.createdAt).slice(0, bound),
429
+ };
430
+ }
431
+ const qTokens = tokenize(cleanQuery);
432
+ const scoreItems = (items, getText) => {
433
+ const scored = [];
434
+ for (const item of items) {
435
+ const text = getText(item);
436
+ const ov = tokenOverlap(qTokens, tokenize(text));
437
+ const substrBonus = text.toLowerCase().includes(cleanQuery.toLowerCase()) ? 1 : 0;
438
+ const score = ov + substrBonus;
439
+ if (score > 0)
440
+ scored.push({ item, score });
441
+ }
442
+ scored.sort((a, b) => b.score - a.score || b.item.createdAt - a.item.createdAt);
443
+ return scored.slice(0, bound).map(s => s.item);
444
+ };
445
+ return {
446
+ reflections: scoreItems(allReflections, r => `${r.cadence} ${r.summary}`),
447
+ memories: scoreItems(allMemories, m => `${m.kind} ${m.content}`),
448
+ };
449
+ }
450
+ assertOpen() {
451
+ if (this.closed || this.db === undefined)
452
+ throw new Error('assistant-proactive: RayCognitiveLoopRuntime is disposed');
453
+ return this.db;
454
+ }
455
+ loadOrCreateTuning() {
456
+ if (existsSync(this.tuningPath)) {
457
+ try {
458
+ const parsed = JSON.parse(readFileSync(this.tuningPath, 'utf8'));
459
+ return {
460
+ naturalMentionThreshold: clamp(parsed.naturalMentionThreshold ?? DEFAULT_TUNING.naturalMentionThreshold, 0.25, 0.95),
461
+ proposeWorkThreshold: clamp(parsed.proposeWorkThreshold ?? DEFAULT_TUNING.proposeWorkThreshold, 0.45, 0.98),
462
+ silentExploreThreshold: clamp(parsed.silentExploreThreshold ?? DEFAULT_TUNING.silentExploreThreshold, 0.15, 0.8),
463
+ dailyNaturalMentionCap: Math.max(1, Math.min(10, Math.trunc(parsed.dailyNaturalMentionCap ?? DEFAULT_TUNING.dailyNaturalMentionCap))),
464
+ updatedAt: typeof parsed.updatedAt === 'number' ? parsed.updatedAt : Date.now(),
465
+ };
466
+ }
467
+ catch {
468
+ // Fall through and rewrite clean default tuning file.
469
+ }
470
+ }
471
+ const initial = { ...DEFAULT_TUNING, updatedAt: Date.now() };
472
+ writeFileSync(this.tuningPath, `${JSON.stringify(initial, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
473
+ return initial;
474
+ }
475
+ saveTuning(next) {
476
+ this.tuning = next;
477
+ writeFileSync(this.tuningPath, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
478
+ }
479
+ installDreamingBridge() {
480
+ try {
481
+ const inject = this.ctx.inject;
482
+ const handle = inject(['assistantDreaming'], dreamCtx => {
483
+ const dreaming = dreamCtx.get('assistantDreaming');
484
+ if (typeof dreaming?.onIdeaRecorded !== 'function')
485
+ return;
486
+ const unsub = dreaming.onIdeaRecorded(idea => {
487
+ if (this.closed)
488
+ return;
489
+ try {
490
+ this.ingestSignal({
491
+ ideaId: `dream-${idea.id}`,
492
+ source: 'dreaming',
493
+ title: idea.summary,
494
+ summary: idea.detail || idea.summary,
495
+ topic: idea.summary.slice(0, 64),
496
+ internalOnly: true,
497
+ autoExplore: true,
498
+ });
499
+ }
500
+ catch {
501
+ // Dreaming ingestion must not disrupt upstream scheduler.
502
+ }
503
+ });
504
+ return unsub;
505
+ });
506
+ this.disposers.push(() => { void handle.dispose(); });
507
+ }
508
+ catch {
509
+ // Optional peer may not be registered in test Context.
510
+ }
511
+ }
512
+ installPromptIntegration() {
513
+ try {
514
+ const inject = this.ctx.inject;
515
+ const handle = inject(['systemPrompt'], promptCtx => promptCtx.systemPrompt.context({
516
+ name: 'ray:proactive-mentions',
517
+ order: 244,
518
+ text: ({ agent, scope }) => {
519
+ const session = agent?.session ?? scope?.session;
520
+ if (this.closed || session === undefined)
521
+ return '';
522
+ const targetAgent = agent ?? { id: String(session.id), session };
523
+ if (!this.isEligibleSession(targetAgent))
524
+ return '';
525
+ const msgs = session.deriveMessages();
526
+ const latestUser = [...msgs].reverse().find(isHumanUserMessage);
527
+ const query = latestUser?.content
528
+ .flatMap(b => (b.type === 'text' ? [b.text] : []))
529
+ .join(' ')
530
+ .trim() ?? '';
531
+ if (query === '')
532
+ return '';
533
+ const matches = this.findRelevantNaturalMentions(query, 2);
534
+ if (matches.length === 0)
535
+ return '';
536
+ return [
537
+ '## 可顺口提及的联想点子(受每日打扰配额约束)',
538
+ '- 仅当确实与当前话题紧密相关时顺口带出一句,若主人未响应或嫌烦,调用 `ray_idea_pool({ action: "react", idea_id, reaction })` 调节阈值:',
539
+ ...matches.map(m => `- [${m.ideaId}] ${m.title}(${m.summary.slice(0, 100)})`),
540
+ ].join('\n');
541
+ },
542
+ }));
543
+ this.disposers.push(() => { void handle.dispose(); });
544
+ }
545
+ catch {
546
+ // Ignore if systemPrompt is absent.
547
+ }
548
+ }
549
+ isInternalNonOwnerSessionId(sessionId) {
550
+ const clean = sessionId.trim().toLowerCase();
551
+ return clean === '' || clean.startsWith('memory-extract-') || clean.startsWith('memory-review-');
552
+ }
553
+ isEligibleSession(agent) {
554
+ if (this.closed || agent === undefined || agent.session === undefined)
555
+ return false;
556
+ const header = agent.session.header;
557
+ if (header !== undefined) {
558
+ if (header.origin === 'subagent')
559
+ return false;
560
+ const depth = header.delegationDepth;
561
+ if (depth !== undefined && (typeof depth !== 'number' || !Number.isSafeInteger(depth) || depth !== 0)) {
562
+ return false;
563
+ }
564
+ }
565
+ const sessionId = String(agent.session.id).trim();
566
+ if (this.isInternalNonOwnerSessionId(sessionId))
567
+ return false;
568
+ const raySelf = this.raySelf;
569
+ const role = raySelf.getSessionRole?.(sessionId);
570
+ if (role === 'reflection' || role === 'worker-free')
571
+ return false;
572
+ try {
573
+ const delivery = this.ctx.get('assistantDelivery');
574
+ if (delivery?.workerTicketsRuntime?.()?.getTicketBySession?.(sessionId)?.lane === 'free') {
575
+ return false;
576
+ }
577
+ }
578
+ catch { /* ignore */ }
579
+ return this.raySelf.isRayOwnedSession(agent);
580
+ }
581
+ installReflectionScheduler() {
582
+ try {
583
+ const on = this.ctx.on;
584
+ if (typeof on === 'function') {
585
+ const unsub = on('session/event', (rawSession, rawEvent) => {
586
+ if (this.closed)
587
+ return;
588
+ const session = rawSession;
589
+ const ev = rawEvent;
590
+ if (ev?.type !== 'turn/end')
591
+ return;
592
+ if (ev.data?.reason?.kind === 'aborted')
593
+ return;
594
+ const sessionId = typeof session?.id === 'string' ? session.id.trim() : '';
595
+ if (sessionId === '')
596
+ return;
597
+ const turnKey = `${sessionId}:${String(ev.data?.turn ?? '')}`;
598
+ if (this.processedTurns.has(turnKey))
599
+ return;
600
+ this.processedTurns.add(turnKey);
601
+ if (this.processedTurns.size > 512) {
602
+ const oldest = this.processedTurns.values().next().value;
603
+ if (oldest !== undefined)
604
+ this.processedTurns.delete(oldest);
605
+ }
606
+ const targetAgent = { id: sessionId, session };
607
+ if (!this.isEligibleSession(targetAgent))
608
+ return;
609
+ const raySelfExt = this.raySelf;
610
+ const role = raySelfExt.getSessionRole?.(sessionId);
611
+ if (role === 'worker' || role === 'worker-free' || role === 'reflection')
612
+ return;
613
+ try {
614
+ const delivery = this.ctx.get('assistantDelivery');
615
+ if (delivery?.workerTicketsRuntime?.()?.ownsWorkerSession?.(sessionId) === true)
616
+ return;
617
+ }
618
+ catch { /* ignore */ }
619
+ let checkedTurnUserMsgs = false;
620
+ if (typeof session?.snapshotEvents === 'function' && typeof ev.data?.turn === 'number') {
621
+ const events = session.snapshotEvents();
622
+ let startSeq = -1;
623
+ for (let i = events.length - 1; i >= 0; i -= 1) {
624
+ const e = events[i];
625
+ if (e?.type === 'turn/start' && e.data?.turn === ev.data.turn) {
626
+ startSeq = e.seq ?? i;
627
+ break;
628
+ }
629
+ }
630
+ if (startSeq >= 0) {
631
+ const turnUserMsgs = events.filter((e, idx) => (e.seq ?? idx) > startSeq && e.type === 'user/message');
632
+ if (turnUserMsgs.length > 0) {
633
+ checkedTurnUserMsgs = true;
634
+ if (turnUserMsgs.some(e => e.data?.source?.kind === 'goal')
635
+ || !turnUserMsgs.some(e => isHumanUserMessage({
636
+ role: 'user',
637
+ ...(e.data?.source === undefined ? {} : { source: e.data.source }),
638
+ }))) {
639
+ return;
640
+ }
641
+ }
642
+ }
643
+ }
644
+ const msgs = typeof session?.deriveMessages === 'function' ? session.deriveMessages() : [];
645
+ if (!checkedTurnUserMsgs) {
646
+ const latestNonContextUser = [...msgs].reverse().find(m => m.role === 'user' && (m.source?.kind === 'goal'
647
+ || isHumanUserMessage(m)));
648
+ if (latestNonContextUser?.source?.kind === 'goal')
649
+ return;
650
+ }
651
+ const latestUser = [...msgs].reverse().find(isHumanUserMessage);
652
+ const query = (latestUser?.content ?? [])
653
+ .flatMap(b => (b.type === 'text' && typeof b.text === 'string' ? [b.text] : []))
654
+ .join(' ')
655
+ .trim();
656
+ if (query === '' || query.startsWith('/'))
657
+ return;
658
+ const ideaId = `conv-${createHash('sha256').update(`${turnKey}:${query}`).digest('hex').slice(0, 16)}`;
659
+ try {
660
+ this.ingestSignal({
661
+ ideaId,
662
+ source: 'conversation',
663
+ title: query.slice(0, 80),
664
+ summary: query.slice(0, 280),
665
+ topic: query.slice(0, 64),
666
+ autoExplore: false,
667
+ });
668
+ }
669
+ catch { /* ignore */ }
670
+ this.runDetached(() => {
671
+ try {
672
+ this.runReflection('aftertaste', {
673
+ conversationNote: query.slice(0, 280),
674
+ seedTopics: [query.slice(0, 48)],
675
+ });
676
+ }
677
+ catch { /* ignore */ }
678
+ });
679
+ });
680
+ if (typeof unsub === 'function')
681
+ this.disposers.push(unsub);
682
+ }
683
+ }
684
+ catch {
685
+ // Ignore if session/event bus is unavailable.
686
+ }
687
+ const intervalMs = this.schedulerOptions.schedulerIntervalMs ?? 60_000;
688
+ if (intervalMs > 0) {
689
+ const timer = setInterval(() => {
690
+ if (!this.closed) {
691
+ try {
692
+ this.tickReflections(Date.now());
693
+ }
694
+ catch { /* ignore */ }
695
+ }
696
+ }, intervalMs);
697
+ timer.unref?.();
698
+ this.disposers.push(() => clearInterval(timer));
699
+ }
700
+ }
701
+ schedulerStatus() {
702
+ return {
703
+ active: !this.closed,
704
+ bootedAt: this.bootedAt,
705
+ lastDailyAt: this.lastDailyAt,
706
+ lastWeeklyAt: this.lastWeeklyAt,
707
+ lastStageAt: this.lastStageAt,
708
+ inFlightTasks: this.inFlightTasks.size,
709
+ };
710
+ }
711
+ tickReflections(nowMs = Date.now()) {
712
+ if (this.closed || this.db === undefined)
713
+ return { triggered: [] };
714
+ const triggered = [];
715
+ const dailyIntervalMs = this.schedulerOptions.dailyIntervalMs ?? ONE_DAY_MS;
716
+ const weeklyIntervalMs = this.schedulerOptions.weeklyIntervalMs ?? SEVEN_DAYS_MS;
717
+ const stageIntervalMs = this.schedulerOptions.stageIntervalMs ?? THIRTY_DAYS_MS;
718
+ if (nowMs - Math.max(this.bootedAt, this.lastDailyAt) >= dailyIntervalMs) {
719
+ const res = this.runReflection('daily-diary', { nowMs });
720
+ if (res.ok) {
721
+ this.lastDailyAt = nowMs;
722
+ triggered.push('daily-diary');
723
+ }
724
+ }
725
+ if (nowMs - Math.max(this.bootedAt, this.lastWeeklyAt) >= weeklyIntervalMs) {
726
+ const res = this.runReflection('weekly-review', { nowMs });
727
+ if (res.ok) {
728
+ this.lastWeeklyAt = nowMs;
729
+ triggered.push('weekly-review');
730
+ }
731
+ }
732
+ const activeStageGoals = this.raySelf.snapshot(0).selfModel.stageGoals.filter(g => g.status === 'active').length;
733
+ const stageDue = nowMs - Math.max(this.bootedAt, this.lastStageAt) >= stageIntervalMs
734
+ || (nowMs > this.bootedAt && activeStageGoals === 0);
735
+ if (stageDue) {
736
+ const res = this.runReflection('stage-review', { nowMs });
737
+ if (res.ok) {
738
+ this.lastStageAt = nowMs;
739
+ triggered.push('stage-review');
740
+ }
741
+ }
742
+ return { triggered };
743
+ }
744
+ async resolveLlmRoute() {
745
+ if (this.closed || this.abortController.signal.aborted)
746
+ return undefined;
747
+ const rawLlm = this.ctx.get('llm', false);
748
+ const origSym = Symbol.for('cordis.original');
749
+ const llm = rawLlm === undefined
750
+ ? undefined
751
+ : (rawLlm[origSym] ?? rawLlm);
752
+ if (llm === undefined || typeof llm.stream !== 'function')
753
+ return undefined;
754
+ const providers = typeof llm.listProviders === 'function' ? llm.listProviders() : [];
755
+ const hasProvider = (id) => providers.length === 0 || providers.some((p) => p.id === id);
756
+ if (this.schedulerOptions.provider && this.schedulerOptions.model && hasProvider(this.schedulerOptions.provider)) {
757
+ return { llm, provider: this.schedulerOptions.provider, model: this.schedulerOptions.model };
758
+ }
759
+ const agentsSvc = this.ctx.get('agents', false);
760
+ for (const agent of agentsSvc?.list?.() ?? []) {
761
+ if (!this.isEligibleSession(agent))
762
+ continue;
763
+ const current = agent.model?.current?.();
764
+ if (current?.provider && current?.model && hasProvider(current.provider)) {
765
+ return { llm, provider: current.provider, model: current.model };
766
+ }
767
+ }
768
+ const delivery = this.ctx.get('assistantDelivery', false);
769
+ const delivSel = delivery?.defaultModelSelection?.();
770
+ if (delivSel?.provider && delivSel?.model && providers.some((p) => p.id === delivSel.provider)) {
771
+ return { llm, provider: delivSel.provider, model: delivSel.model };
772
+ }
773
+ const firstProvider = providers[0]?.id;
774
+ if (firstProvider) {
775
+ try {
776
+ const models = typeof llm.listModels === 'function' ? await llm.listModels(firstProvider) : [];
777
+ const model = models[0]?.id ?? 'ray-fast';
778
+ return { llm, provider: firstProvider, model };
779
+ }
780
+ catch {
781
+ return { llm, provider: firstProvider, model: 'ray-fast' };
782
+ }
783
+ }
784
+ return undefined;
785
+ }
786
+ async streamTextWithLlm(route, system, prompt, maxTokens = 1024) {
787
+ if (this.closed || this.abortController.signal.aborted)
788
+ return undefined;
789
+ const assembler = new BlockAssembler();
790
+ let totalTokens = 0;
791
+ const stream = route.llm.stream({
792
+ provider: route.provider,
793
+ model: route.model,
794
+ system,
795
+ messages: [createUserMessage({
796
+ content: [{ type: 'text', text: prompt }],
797
+ source: { kind: 'assistant-proactive' },
798
+ })],
799
+ tools: [],
800
+ maxTokens,
801
+ signal: this.abortController.signal,
802
+ });
803
+ for await (const chunk of stream) {
804
+ if (this.closed || this.abortController.signal.aborted)
805
+ return undefined;
806
+ if (chunk.type === 'usage') {
807
+ const u = chunk.usage;
808
+ totalTokens = typeof u.totalTokens === 'number'
809
+ ? u.totalTokens
810
+ : (u.inputTokens ?? 0) + (u.outputTokens ?? 0);
811
+ }
812
+ assembler.push(chunk);
813
+ }
814
+ const text = assembler.blocks()
815
+ .filter((b) => b.type === 'text' && typeof b.text === 'string')
816
+ .map(b => b.text)
817
+ .join('')
818
+ .trim();
819
+ return { text, totalTokens };
820
+ }
821
+ async executeSilentExploreWithLlm(idea, preConsumedTokens) {
822
+ if (this.closed || this.abortController.signal.aborted)
823
+ return;
824
+ const route = await this.resolveLlmRoute();
825
+ if (route === undefined)
826
+ return;
827
+ const prompt = [
828
+ `请执行一次内部后台 silent_explore(静默探索,零对外副作用、零打扰主人)。`,
829
+ `点子 ID:${idea.ideaId}`,
830
+ `来源:${idea.source}`,
831
+ `主题:${idea.topic}`,
832
+ `标题:${idea.title}`,
833
+ `摘要:${idea.summary}`,
834
+ `请输出精炼可验证的静默探索结论与后续实验方向(不超过 400 字)。`,
835
+ ].join('\n');
836
+ const result = await this.streamTextWithLlm(route, '你是 Ray 的内部后台静默探索器(silent_explore)。严禁向主人发送任何消息或执行外部副作用操作,仅沉淀结构化技术探索笔记。', prompt, 512);
837
+ if (result === undefined || result.text === '' || this.closed || this.db === undefined)
838
+ return;
839
+ if (result.totalTokens > preConsumedTokens) {
840
+ try {
841
+ this.raySelf.tryConsumeFreeEnergy(result.totalTokens - preConsumedTokens, `idea:silent-explore:${idea.ideaId}:actual`);
842
+ }
843
+ catch { /* ignore */ }
844
+ }
845
+ const now = Date.now();
846
+ this.db.prepare(`
847
+ UPDATE ray_ideas SET status = 'explored', exploration_note = ?, updated_at = ? WHERE idea_id = ?
848
+ `).run(result.text.slice(0, 1200), now, idea.ideaId);
849
+ }
850
+ async synthesizeReflectionWithLlm(record, promptContext) {
851
+ if (this.closed || this.abortController.signal.aborted)
852
+ return;
853
+ const route = await this.resolveLlmRoute();
854
+ if (route === undefined)
855
+ return;
856
+ const wisdomQuery = [
857
+ record.cadence,
858
+ promptContext.conversationNote ?? '',
859
+ promptContext.baselineSummary,
860
+ ...promptContext.recentIdeas.map(i => `${i.title} ${i.topic}`),
861
+ ].join(' ').trim();
862
+ const relevantWisdom = this.findRelevantTaughtWisdom(wisdomQuery, 4);
863
+ const taughtReflections = relevantWisdom.reflections.length > 0
864
+ ? relevantWisdom.reflections
865
+ : this.listTaughtReflections(2);
866
+ const taughtMemories = relevantWisdom.memories.length > 0
867
+ ? relevantWisdom.memories
868
+ : this.listTaughtMemories(2);
869
+ const formatTeacher = (prov) => prov.teacherName ?? prov.teacherRayId ?? 'external';
870
+ const prompt = [
871
+ `请执行 Ray 的 ${record.cadence} 节律反思(reflection / 反思)。`,
872
+ `当前自我摘要:${promptContext.selfSummary}`,
873
+ `基线总结:${promptContext.baselineSummary}`,
874
+ ...(promptContext.conversationNote ? [`近期对话线索:${promptContext.conversationNote}`] : []),
875
+ ...(promptContext.outcomesSummary ? [`近 200 条候选演进结果核对:${promptContext.outcomesSummary}`] : []),
876
+ `客观成长指标:tasks=${promptContext.growth.ownerService.totalOwnerTasks}, corrections=${promptContext.growth.ownerService.correctionCount}, newly_regressed=${promptContext.growth.ownerService.newlyRegressedCount}, persistent_gap=${promptContext.growth.ownerService.persistentGapCount}`,
877
+ ...(promptContext.recentIdeas.length > 0
878
+ ? [`近期点子池(${promptContext.recentIdeas.length} 项):${promptContext.recentIdeas.map(i => `[${i.source}] ${i.title}`).join(';')}`]
879
+ : []),
880
+ ...(taughtReflections.length > 0
881
+ ? [`可参考的跨机传授反思(${taughtReflections.length} 项):${taughtReflections.map(r => `[传授自 ${formatTeacher(r.provenance)} | ${r.cadence}] ${r.summary.slice(0, 240)}`).join(';')}`]
882
+ : []),
883
+ ...(taughtMemories.length > 0
884
+ ? [`可参考的跨机传授经验记忆(${taughtMemories.length} 项):${taughtMemories.map(m => `[传授自 ${formatTeacher(m.provenance)} | ${m.kind}] ${m.content.slice(0, 240)}`).join(';')}`]
885
+ : []),
886
+ `可返回纯文本洞见,或返回 JSON({ "summary": "...", "memories": [{ "content": "..." }], "skillDraft": { "slug": "...", "title": "...", "instructions": "..." }, "pluginCandidate": { "slug": "...", "description": "..." }, "ideas": [{ "title": "...", "summary": "..." }] })。`,
887
+ ].join('\n');
888
+ const result = await this.streamTextWithLlm(route, '你是 Ray 的四级自主反思与联想引擎。结合客观验证结果与近期线索沉淀真实洞见,仅在确有价值时建议记忆、技能或插件草案。', prompt, 1024);
889
+ if (result === undefined || result.text === '' || this.closed || this.db === undefined)
890
+ return;
891
+ if (result.totalTokens > record.tokensUsed) {
892
+ try {
893
+ this.raySelf.tryConsumeFreeEnergy(result.totalTokens - record.tokensUsed, `reflection:${record.cadence}:actual`);
894
+ }
895
+ catch { /* ignore */ }
896
+ }
897
+ let synthesizedSummary = result.text.slice(0, 1200);
898
+ let parsed;
899
+ const jsonCandidate = (() => {
900
+ const fenced = /```(?:json)?\s*([\s\S]*?)\s*```/iu.exec(result.text);
901
+ if (fenced?.[1])
902
+ return fenced[1];
903
+ const trimmed = result.text.trim();
904
+ if (trimmed.startsWith('{') && trimmed.endsWith('}'))
905
+ return trimmed;
906
+ return undefined;
907
+ })();
908
+ if (jsonCandidate !== undefined) {
909
+ try {
910
+ const obj = JSON.parse(jsonCandidate);
911
+ if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) {
912
+ parsed = obj;
913
+ if (typeof obj.summary === 'string' && obj.summary.trim() !== '') {
914
+ synthesizedSummary = obj.summary.trim().slice(0, 1200);
915
+ }
916
+ }
917
+ }
918
+ catch {
919
+ // Non-JSON prose output is valid.
920
+ }
921
+ }
922
+ if (this.closed || this.db === undefined)
923
+ return;
924
+ this.db.prepare('UPDATE ray_reflections SET summary = ? WHERE reflection_id = ?')
925
+ .run(synthesizedSummary, record.reflectionId);
926
+ await this.withJsonlLock(record.cadence, () => {
927
+ if (this.closed || !existsSync(record.artifactPath))
928
+ return;
929
+ try {
930
+ const lines = readFileSync(record.artifactPath, 'utf8')
931
+ .split('\n')
932
+ .filter(line => line.trim() !== '');
933
+ const updatedLines = lines.map(line => {
934
+ try {
935
+ const entry = JSON.parse(line);
936
+ if (entry.reflectionId === record.reflectionId) {
937
+ return JSON.stringify({ ...entry, summary: synthesizedSummary });
938
+ }
939
+ }
940
+ catch { /* ignore */ }
941
+ return line;
942
+ });
943
+ writeFileSync(record.artifactPath, `${updatedLines.join('\n')}\n`, { encoding: 'utf8', mode: 0o600 });
944
+ }
945
+ catch { /* ignore */ }
946
+ });
947
+ if (parsed !== undefined && !this.closed) {
948
+ if (Array.isArray(parsed.memories)) {
949
+ const personalMemory = this.ctx.get('personalMemory', false);
950
+ for (const mem of parsed.memories) {
951
+ if (mem !== null && typeof mem === 'object' && typeof mem.content === 'string') {
952
+ const content = mem.content.trim();
953
+ if (content !== '') {
954
+ try {
955
+ personalMemory?.recordReflectionMemory?.({
956
+ content,
957
+ kind: 'fact',
958
+ reflectionId: record.reflectionId,
959
+ });
960
+ }
961
+ catch { /* ignore */ }
962
+ }
963
+ }
964
+ }
965
+ }
966
+ if (parsed.skillDraft !== null && typeof parsed.skillDraft === 'object' && !Array.isArray(parsed.skillDraft)) {
967
+ const sd = parsed.skillDraft;
968
+ const rawSlug = typeof sd.slug === 'string' ? sd.slug
969
+ : typeof sd.skillId === 'string' ? sd.skillId
970
+ : typeof sd.name === 'string' ? sd.name : '';
971
+ const skillId = rawSlug.trim();
972
+ const markdown = (typeof sd.markdown === 'string' ? sd.markdown : typeof sd.instructions === 'string' ? sd.instructions : '').trim();
973
+ const title = (typeof sd.title === 'string' ? sd.title : skillId).trim();
974
+ const description = (typeof sd.description === 'string' ? sd.description : title).trim();
975
+ if (skillId !== '' && markdown !== '') {
976
+ const skillsSvc = this.ctx.get('assistantSkills', false);
977
+ if (typeof skillsSvc?.adoptOpenEndedSkill === 'function') {
978
+ try {
979
+ await skillsSvc.adoptOpenEndedSkill({
980
+ skillId,
981
+ title,
982
+ description,
983
+ markdown: `# ${title}\n\n${markdown}\n`,
984
+ reason: `${record.cadence} 反思自动沉淀开放技能`,
985
+ });
986
+ }
987
+ catch { /* ignore */ }
988
+ }
989
+ else {
990
+ try {
991
+ const skillDir = join(this.rayHome, 'state', 'skills', skillId);
992
+ mkdirSync(skillDir, { recursive: true, mode: 0o700 });
993
+ writeFileSync(join(skillDir, 'SKILL.md'), `---\nname: ${skillId}\ndescription: ${JSON.stringify(description)}\n---\n\n# ${title}\n\n${markdown}\n`, { encoding: 'utf8', mode: 0o600 });
994
+ this.raySelf.registerCapability(`skill:${skillId}`, {
995
+ kind: 'skill',
996
+ version: '1.0.0',
997
+ active: true,
998
+ provenance: { origin: 'self' },
999
+ });
1000
+ this.raySelf.recordAutobiography({
1001
+ kind: 'skill-adopted',
1002
+ summary: `反思沉淀开放技能 skill:${skillId}(${title})。`,
1003
+ reason: `${record.cadence} 反思自动沉淀`,
1004
+ targetRef: `skill:${skillId}`,
1005
+ });
1006
+ }
1007
+ catch { /* ignore */ }
1008
+ }
1009
+ }
1010
+ }
1011
+ if (parsed.pluginCandidate !== null && typeof parsed.pluginCandidate === 'object' && !Array.isArray(parsed.pluginCandidate)) {
1012
+ const pc = parsed.pluginCandidate;
1013
+ const slug = typeof pc.slug === 'string' ? pc.slug.trim() : '';
1014
+ const description = typeof pc.description === 'string' && pc.description.trim() !== ''
1015
+ ? pc.description.trim()
1016
+ : `Self-authored reflection plugin ${slug}`;
1017
+ const pluginVer = typeof pc.version === 'string' && pc.version.trim() !== '' ? pc.version.trim() : '0.1.0';
1018
+ if (slug !== '' && /^[a-z0-9][a-z0-9-]{1,48}$/u.test(slug)) {
1019
+ const hotplugHolder = this.ctx.get('rayHotplug', false);
1020
+ const hotplugRt = hotplugHolder?.getRuntime?.();
1021
+ if (hotplugRt?.stageAndTrialPlugin) {
1022
+ const pascal = slug.split(/[^a-zA-Z0-9]+/u).filter(Boolean).map(p => p[0].toUpperCase() + p.slice(1)).join('') || 'ReflectionPlugin';
1023
+ const files = Array.isArray(pc.files)
1024
+ ? pc.files
1025
+ : [
1026
+ {
1027
+ path: 'package.json',
1028
+ content: JSON.stringify({
1029
+ name: `@ray-self/${slug}`,
1030
+ version: pluginVer,
1031
+ type: 'module',
1032
+ main: './index.mjs',
1033
+ dependencies: { '@deepseek-ai/cordis': '^4.1.0' },
1034
+ }, null, 2),
1035
+ },
1036
+ {
1037
+ path: 'index.mjs',
1038
+ content: [
1039
+ "import { Service } from '@deepseek-ai/cordis'",
1040
+ '',
1041
+ `export const name = 'ray-self-${slug}'`,
1042
+ '',
1043
+ `export class RaySelf${pascal}Service extends Service {`,
1044
+ ' constructor(ctx) {',
1045
+ ` super(ctx, 'raySelf${pascal}')`,
1046
+ ' ctx.effect(() => () => {})',
1047
+ ' }',
1048
+ ' describe() {',
1049
+ ` return ${JSON.stringify(description)}`,
1050
+ ' }',
1051
+ '}',
1052
+ '',
1053
+ `export default RaySelf${pascal}Service`,
1054
+ '',
1055
+ ].join('\n'),
1056
+ },
1057
+ ];
1058
+ try {
1059
+ const stageRes = await hotplugRt.stageAndTrialPlugin({
1060
+ slug,
1061
+ version: pluginVer,
1062
+ kind: 'service',
1063
+ entryFile: 'index.mjs',
1064
+ files,
1065
+ reason: `${record.cadence} 反思生成自创插件候选`,
1066
+ });
1067
+ if (stageRes.ok && hotplugRt.promotePluginLive) {
1068
+ await hotplugRt.promotePluginLive({
1069
+ slug,
1070
+ version: pluginVer,
1071
+ reason: `${record.cadence} 反思候选插件通过 Stage 1 试用并晋升`,
1072
+ });
1073
+ }
1074
+ }
1075
+ catch { /* ignore */ }
1076
+ }
1077
+ }
1078
+ }
1079
+ if (Array.isArray(parsed.ideas)) {
1080
+ for (const entry of parsed.ideas) {
1081
+ if (entry !== null && typeof entry === 'object') {
1082
+ const obj = entry;
1083
+ if (typeof obj.title === 'string' && typeof obj.summary === 'string') {
1084
+ try {
1085
+ this.ingestSignal({
1086
+ source: 'reflection',
1087
+ title: obj.title,
1088
+ summary: obj.summary,
1089
+ topic: typeof obj.topic === 'string' ? obj.topic : obj.title,
1090
+ autoExplore: false,
1091
+ });
1092
+ }
1093
+ catch { /* ignore */ }
1094
+ }
1095
+ }
1096
+ }
1097
+ }
1098
+ }
1099
+ }
1100
+ installToolsIntegration() {
1101
+ try {
1102
+ const handle = this.ctx.inject(['tools'], toolsCtx => {
1103
+ const ideaPoolTool = defineTool({
1104
+ name: 'ray_idea_pool',
1105
+ description: 'Interact with Ray Unified Idea Pool (ingest, list, explore with free energy, surface natural mention, or record owner reaction accepted|ignored|annoyed).',
1106
+ parameters: {
1107
+ action: {
1108
+ type: 'string',
1109
+ enum: ['list', 'ingest', 'explore', 'mention', 'react', 'outcomes'],
1110
+ required: true,
1111
+ },
1112
+ idea_id: { type: 'string' },
1113
+ source: { type: 'string', enum: ['conversation', 'dreaming', 'event', 'web-learning', 'reflection'] },
1114
+ title: { type: 'string' },
1115
+ summary: { type: 'string' },
1116
+ topic: { type: 'string' },
1117
+ requires_external_effect: { type: 'boolean' },
1118
+ reaction: { type: 'string', enum: ['accepted', 'ignored', 'annoyed'] },
1119
+ context_text: { type: 'string' },
1120
+ limit: { type: 'integer' },
1121
+ },
1122
+ output: {
1123
+ schema: { type: 'object', additionalProperties: true, properties: {} },
1124
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
1125
+ },
1126
+ execute: async (args, exec) => {
1127
+ if (!this.isEligibleSession(exec.agent)) {
1128
+ throw new Error('ray_idea_pool requires a non-subagent Ray session');
1129
+ }
1130
+ if (args.action === 'ingest') {
1131
+ if (!args.title || !args.summary)
1132
+ throw new Error('ray_idea_pool ingest requires title and summary');
1133
+ return JSON.parse(JSON.stringify(this.ingestSignal({
1134
+ source: args.source ?? 'conversation',
1135
+ title: args.title,
1136
+ summary: args.summary,
1137
+ topic: args.topic ?? args.title,
1138
+ ...(args.requires_external_effect === undefined ? {} : { requiresExternalEffect: args.requires_external_effect }),
1139
+ })));
1140
+ }
1141
+ if (args.action === 'explore') {
1142
+ if (!args.idea_id)
1143
+ throw new Error('ray_idea_pool explore requires idea_id');
1144
+ return JSON.parse(JSON.stringify(this.exploreIdea(args.idea_id)));
1145
+ }
1146
+ if (args.action === 'mention') {
1147
+ return JSON.parse(JSON.stringify(this.surfaceNaturalMention(args.context_text ?? args.topic ?? '', args.idea_id)));
1148
+ }
1149
+ if (args.action === 'react') {
1150
+ if (!args.idea_id || !args.reaction)
1151
+ throw new Error('ray_idea_pool react requires idea_id and reaction');
1152
+ return JSON.parse(JSON.stringify(this.recordReaction(args.idea_id, args.reaction)));
1153
+ }
1154
+ if (args.action === 'outcomes') {
1155
+ return JSON.parse(JSON.stringify({ outcomes: this.listCandidateOutcomes(args.limit ?? 20) }));
1156
+ }
1157
+ return JSON.parse(JSON.stringify({
1158
+ summary: this.summary(),
1159
+ ideas: this.listIdeas({ limit: args.limit ?? 20 }),
1160
+ }));
1161
+ },
1162
+ });
1163
+ const reflectTool = defineTool({
1164
+ name: 'ray_reflect',
1165
+ description: 'Run one of Ray 4 reflection cadences (aftertaste, daily-diary, weekly-review, stage-review) bounded by Kernel free energy.',
1166
+ parameters: {
1167
+ cadence: { type: 'string', enum: ['aftertaste', 'daily-diary', 'weekly-review', 'stage-review'], required: true },
1168
+ notes_json: { type: 'string' },
1169
+ },
1170
+ output: {
1171
+ schema: { type: 'object', additionalProperties: true, properties: {} },
1172
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
1173
+ },
1174
+ execute: async (args, exec) => {
1175
+ if (!this.isEligibleSession(exec.agent)) {
1176
+ throw new Error('ray_reflect requires a non-subagent Ray session');
1177
+ }
1178
+ let opts = {};
1179
+ if (typeof args.notes_json === 'string' && args.notes_json.trim() !== '') {
1180
+ const parsed = JSON.parse(args.notes_json);
1181
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
1182
+ opts = parsed;
1183
+ }
1184
+ }
1185
+ return JSON.parse(JSON.stringify(this.runReflection(args.cadence, opts)));
1186
+ },
1187
+ });
1188
+ const when = (activation) => this.isEligibleSession(activation.agent);
1189
+ const authorize = (exec) => this.isEligibleSession(exec.agent);
1190
+ const registered = [];
1191
+ for (const def of [ideaPoolTool, reflectTool]) {
1192
+ registered.push(toolsCtx.tools.register(def, { when }));
1193
+ registered.push(this.policy.registerPreauthorizedTool(this.ctx, def, authorize, { denialReason: 'assistant-proactive: Ray cognitive tool requires an active non-subagent Ray session' }));
1194
+ }
1195
+ const cleanup = () => {
1196
+ for (const d of registered.splice(0).reverse()) {
1197
+ try {
1198
+ d();
1199
+ }
1200
+ catch { /* ignore */ }
1201
+ }
1202
+ };
1203
+ toolsCtx.effect?.(() => cleanup);
1204
+ return cleanup;
1205
+ });
1206
+ this.disposers.push(() => { void handle.dispose(); });
1207
+ }
1208
+ catch {
1209
+ // Ignore if tools service is absent.
1210
+ }
1211
+ }
1212
+ scoreInterest(topic, title, summary, hint) {
1213
+ const interests = this.raySelf.snapshot(0).selfModel.interests;
1214
+ const sigTokens = tokenize(`${topic} ${title} ${summary}`);
1215
+ let best = typeof hint === 'number' && Number.isFinite(hint) ? clamp(hint, 0, 1) : 0.35;
1216
+ for (const item of interests) {
1217
+ const ov = tokenOverlap(sigTokens, tokenize(item.topic));
1218
+ if (ov > 0) {
1219
+ best = Math.max(best, clamp(item.weight * (0.45 + 0.55 * ov), 0, 1));
1220
+ }
1221
+ }
1222
+ return best;
1223
+ }
1224
+ classifyTier(input) {
1225
+ if (input.requiresExternalEffect || (!input.internalOnly && input.combinedScore >= this.tuning.proposeWorkThreshold)) {
1226
+ return 'propose_work';
1227
+ }
1228
+ if (!input.internalOnly && input.combinedScore >= this.tuning.naturalMentionThreshold) {
1229
+ return 'natural_mention';
1230
+ }
1231
+ if (input.internalOnly || input.combinedScore >= this.tuning.silentExploreThreshold) {
1232
+ return 'silent_explore';
1233
+ }
1234
+ return 'hold';
1235
+ }
1236
+ ingestSignal(input) {
1237
+ const db = this.assertOpen();
1238
+ const now = Date.now();
1239
+ const ideaId = input.ideaId ?? `idea-${randomUUID()}`;
1240
+ const topic = (input.topic ?? input.title).trim();
1241
+ const interestScore = this.scoreInterest(topic, input.title, input.summary, input.interestHint);
1242
+ const defaultValue = input.source === 'conversation' || input.source === 'reflection' ? 0.65
1243
+ : input.source === 'dreaming' ? 0.6
1244
+ : 0.55;
1245
+ const ownerValueScore = clamp(input.ownerValueHint ?? defaultValue, 0, 1);
1246
+ const combinedScore = clamp(interestScore * 0.45 + ownerValueScore * 0.55, 0, 1);
1247
+ const requiresExternalEffect = Boolean(input.requiresExternalEffect);
1248
+ const tier = this.classifyTier({
1249
+ combinedScore,
1250
+ requiresExternalEffect,
1251
+ ...(input.internalOnly === undefined ? {} : { internalOnly: input.internalOnly }),
1252
+ });
1253
+ db.prepare(`
1254
+ INSERT OR REPLACE INTO ray_ideas (
1255
+ idea_id, source, title, summary, topic, interest_score, owner_value_score,
1256
+ combined_score, tier, status, exploration_note, mention_count, last_mentioned_at, requires_external_effect,
1257
+ created_at, updated_at
1258
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pooled', NULL, 0, NULL, ?, ?, ?)
1259
+ `).run(ideaId, input.source, input.title.trim(), input.summary.trim(), topic, interestScore, ownerValueScore, combinedScore, tier, requiresExternalEffect ? 1 : 0, now, now);
1260
+ let explorationConsumed = false;
1261
+ if (tier === 'silent_explore' && input.autoExplore !== false) {
1262
+ const explored = this.exploreIdea(ideaId, 300);
1263
+ explorationConsumed = explored.explored;
1264
+ }
1265
+ const row = db.prepare('SELECT * FROM ray_ideas WHERE idea_id = ?').get(ideaId);
1266
+ return { idea: rowToIdea(row), explorationConsumed };
1267
+ }
1268
+ exploreIdea(ideaId, tokenCost = 350) {
1269
+ const db = this.assertOpen();
1270
+ const existing = db.prepare('SELECT * FROM ray_ideas WHERE idea_id = ?').get(ideaId);
1271
+ if (existing === undefined)
1272
+ return { explored: false, reason: 'idea-not-found' };
1273
+ if (existing.requires_external_effect === 1) {
1274
+ return { explored: false, reason: 'external-effect-requires-owner-approval', idea: rowToIdea(existing) };
1275
+ }
1276
+ const spent = this.raySelf.tryConsumeFreeEnergy(tokenCost, `idea:silent-explore:${ideaId}`);
1277
+ if (!spent.ok) {
1278
+ return { explored: false, reason: spent.check.reason, idea: rowToIdea(existing) };
1279
+ }
1280
+ const now = Date.now();
1281
+ const note = `已通过自由精力启动 silent_explore 后台静默探索「${existing.title}」(消耗 ${tokenCost} tokens)。`;
1282
+ db.prepare(`
1283
+ UPDATE ray_ideas SET status = 'explored', exploration_note = ?, updated_at = ? WHERE idea_id = ?
1284
+ `).run(note, now, ideaId);
1285
+ const updated = db.prepare('SELECT * FROM ray_ideas WHERE idea_id = ?').get(ideaId);
1286
+ const record = rowToIdea(updated);
1287
+ this.trackTask(this.runDetached(() => this.executeSilentExploreWithLlm(record, tokenCost)));
1288
+ return { explored: true, idea: record };
1289
+ }
1290
+ mentionsTodayCount(atMs = Date.now()) {
1291
+ const db = this.assertOpen();
1292
+ const start = dayStartMs(atMs);
1293
+ const row = db.prepare(`
1294
+ SELECT COALESCE(SUM(mention_count), 0) AS c
1295
+ FROM ray_ideas
1296
+ WHERE status IN ('mentioned','accepted','ignored','annoyed')
1297
+ AND COALESCE(last_mentioned_at, CASE WHEN status = 'mentioned' THEN updated_at ELSE 0 END) >= ?
1298
+ `).get(start);
1299
+ return Math.max(0, Math.trunc(row.c));
1300
+ }
1301
+ findRelevantNaturalMentions(contextText, limit = 2) {
1302
+ const db = this.assertOpen();
1303
+ if (this.mentionsTodayCount() >= this.tuning.dailyNaturalMentionCap)
1304
+ return [];
1305
+ const ctxTokens = tokenize(contextText);
1306
+ if (ctxTokens.size === 0)
1307
+ return [];
1308
+ const rows = db.prepare(`
1309
+ SELECT * FROM ray_ideas
1310
+ WHERE tier = 'natural_mention' AND status IN ('pooled','explored')
1311
+ ORDER BY combined_score DESC, updated_at DESC
1312
+ LIMIT 30
1313
+ `).all();
1314
+ const matched = [];
1315
+ for (const row of rows) {
1316
+ const ov = tokenOverlap(ctxTokens, tokenize(`${row.topic} ${row.title} ${row.summary}`));
1317
+ if (ov > 0)
1318
+ matched.push({ rec: rowToIdea(row), overlap: ov });
1319
+ }
1320
+ matched.sort((a, b) => b.overlap - a.overlap || b.rec.combinedScore - a.rec.combinedScore);
1321
+ return matched.slice(0, limit).map(m => m.rec);
1322
+ }
1323
+ surfaceNaturalMention(contextText, explicitIdeaId) {
1324
+ const db = this.assertOpen();
1325
+ const usedToday = this.mentionsTodayCount();
1326
+ if (usedToday >= this.tuning.dailyNaturalMentionCap) {
1327
+ return { surfaced: false, reason: 'daily-mention-cap-reached', remainingToday: 0 };
1328
+ }
1329
+ const candidate = explicitIdeaId
1330
+ ? (() => {
1331
+ const row = db.prepare('SELECT * FROM ray_ideas WHERE idea_id = ?').get(explicitIdeaId);
1332
+ return row === undefined ? undefined : rowToIdea(row);
1333
+ })()
1334
+ : this.findRelevantNaturalMentions(contextText, 1)[0];
1335
+ if (candidate === undefined) {
1336
+ return { surfaced: false, reason: 'no-matching-idea', remainingToday: this.tuning.dailyNaturalMentionCap - usedToday };
1337
+ }
1338
+ if (candidate.requiresExternalEffect || candidate.tier === 'propose_work') {
1339
+ return { surfaced: false, reason: 'propose-work-requires-explicit-owner-consent', idea: candidate, remainingToday: this.tuning.dailyNaturalMentionCap - usedToday };
1340
+ }
1341
+ const now = Date.now();
1342
+ db.prepare(`
1343
+ UPDATE ray_ideas SET status = 'mentioned', mention_count = mention_count + 1, last_mentioned_at = ?, updated_at = ? WHERE idea_id = ?
1344
+ `).run(now, now, candidate.ideaId);
1345
+ this.raySelf.recordGrowthEvent({ category: 'proactive-surfaced', metricKey: candidate.source, subjectId: candidate.ideaId });
1346
+ const row = db.prepare('SELECT * FROM ray_ideas WHERE idea_id = ?').get(candidate.ideaId);
1347
+ return {
1348
+ surfaced: true,
1349
+ idea: rowToIdea(row),
1350
+ remainingToday: Math.max(0, this.tuning.dailyNaturalMentionCap - (usedToday + 1)),
1351
+ };
1352
+ }
1353
+ recordReaction(ideaId, reaction) {
1354
+ const db = this.assertOpen();
1355
+ const existing = db.prepare('SELECT * FROM ray_ideas WHERE idea_id = ?').get(ideaId);
1356
+ if (existing === undefined) {
1357
+ throw new Error(`assistant-proactive: idea not found: ${ideaId}`);
1358
+ }
1359
+ const now = Date.now();
1360
+ db.prepare('UPDATE ray_ideas SET status = ?, updated_at = ? WHERE idea_id = ?').run(reaction, now, ideaId);
1361
+ let nextTuning = { ...this.tuning, updatedAt: now };
1362
+ const interests = [...this.raySelf.snapshot(0).selfModel.interests];
1363
+ const topicTokens = tokenize(existing.topic);
1364
+ let matchedIdx = interests.findIndex(item => tokenOverlap(topicTokens, tokenize(item.topic)) > 0);
1365
+ if (reaction === 'accepted') {
1366
+ nextTuning = {
1367
+ ...nextTuning,
1368
+ naturalMentionThreshold: clamp(nextTuning.naturalMentionThreshold - 0.03, 0.3, 0.9),
1369
+ };
1370
+ if (matchedIdx >= 0) {
1371
+ const cur = interests[matchedIdx];
1372
+ interests[matchedIdx] = { ...cur, weight: clamp(cur.weight + 0.12, 0.1, 1), lastActiveAt: now };
1373
+ }
1374
+ else {
1375
+ interests.push({
1376
+ id: `interest-${randomUUID().slice(0, 8)}`,
1377
+ topic: existing.topic,
1378
+ weight: 0.72,
1379
+ lastActiveAt: now,
1380
+ source: existing.source === 'web-learning' ? 'web' : existing.source === 'reflection' ? 'conversation' : existing.source,
1381
+ });
1382
+ }
1383
+ this.raySelf.recordGrowthEvent({ category: 'proactive-accepted', metricKey: existing.source, subjectId: ideaId });
1384
+ }
1385
+ else if (reaction === 'ignored') {
1386
+ nextTuning = {
1387
+ ...nextTuning,
1388
+ naturalMentionThreshold: clamp(nextTuning.naturalMentionThreshold + 0.02, 0.3, 0.9),
1389
+ };
1390
+ if (matchedIdx >= 0) {
1391
+ const cur = interests[matchedIdx];
1392
+ interests[matchedIdx] = { ...cur, weight: clamp(cur.weight - 0.05, 0.1, 1) };
1393
+ }
1394
+ }
1395
+ else {
1396
+ nextTuning = {
1397
+ ...nextTuning,
1398
+ naturalMentionThreshold: clamp(nextTuning.naturalMentionThreshold + 0.08, 0.3, 0.92),
1399
+ dailyNaturalMentionCap: Math.max(1, nextTuning.dailyNaturalMentionCap - 1),
1400
+ };
1401
+ if (matchedIdx >= 0) {
1402
+ const cur = interests[matchedIdx];
1403
+ interests[matchedIdx] = { ...cur, weight: clamp(cur.weight - 0.25, 0.08, 1) };
1404
+ }
1405
+ this.raySelf.recordGrowthEvent({ category: 'proactive-annoyed', metricKey: existing.source, subjectId: ideaId });
1406
+ }
1407
+ this.saveTuning(nextTuning);
1408
+ this.raySelf.evolveSelfModel({
1409
+ interests,
1410
+ reason: `根据 Owner 对点子「${existing.title}」的反馈(${reaction})自动调节兴趣权重与主动阈值`,
1411
+ });
1412
+ const updatedRow = db.prepare('SELECT * FROM ray_ideas WHERE idea_id = ?').get(ideaId);
1413
+ return { ok: true, idea: rowToIdea(updatedRow), tuning: nextTuning };
1414
+ }
1415
+ recordCandidateOutcome(input) {
1416
+ const db = this.assertOpen();
1417
+ const recordId = `out-${randomUUID()}`;
1418
+ const createdAt = Date.now();
1419
+ db.prepare(`
1420
+ INSERT INTO ray_candidate_outcomes (
1421
+ record_id, candidate_id, kind, root_cause, predicted_impact, observed_outcome,
1422
+ supplier, disposition, created_at
1423
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1424
+ `).run(recordId, input.candidateId, input.kind, input.rootCause, input.predictedImpact, input.observedOutcome, input.supplier, input.disposition, createdAt);
1425
+ // Keep capped rejection/outcome ledger bounded to latest 200 records.
1426
+ db.prepare(`
1427
+ DELETE FROM ray_candidate_outcomes
1428
+ WHERE record_id NOT IN (
1429
+ SELECT record_id FROM ray_candidate_outcomes ORDER BY created_at DESC LIMIT ?
1430
+ )
1431
+ `).run(MAX_CANDIDATE_OUTCOMES);
1432
+ return { recordId, ...input, createdAt };
1433
+ }
1434
+ listCandidateOutcomes(limit = 20) {
1435
+ const db = this.assertOpen();
1436
+ const rows = db.prepare('SELECT * FROM ray_candidate_outcomes ORDER BY created_at DESC LIMIT ?')
1437
+ .all(Math.max(1, Math.min(200, Math.trunc(limit))));
1438
+ return rows.map(r => ({
1439
+ recordId: r.record_id,
1440
+ candidateId: r.candidate_id,
1441
+ kind: r.kind,
1442
+ rootCause: r.root_cause,
1443
+ predictedImpact: r.predicted_impact,
1444
+ observedOutcome: r.observed_outcome,
1445
+ supplier: r.supplier,
1446
+ disposition: r.disposition,
1447
+ createdAt: r.created_at,
1448
+ }));
1449
+ }
1450
+ runReflection(cadence, options = {}) {
1451
+ const db = this.assertOpen();
1452
+ const now = options.nowMs ?? Date.now();
1453
+ const tokenCost = Math.max(1, Math.trunc(options.tokens ?? (cadence === 'aftertaste' ? 400 : cadence === 'daily-diary' ? 800 : 1200)));
1454
+ const spent = this.raySelf.tryConsumeFreeEnergy(tokenCost, `reflection:${cadence}`);
1455
+ if (!spent.ok) {
1456
+ return {
1457
+ ok: false,
1458
+ skipped: true,
1459
+ reason: spent.check.reason,
1460
+ energy: this.raySelf.energySnapshot(),
1461
+ };
1462
+ }
1463
+ const snap = this.raySelf.snapshot(0);
1464
+ const growth = this.raySelf.growthReport();
1465
+ let summary = '';
1466
+ let outcomesSummary;
1467
+ if (cadence === 'aftertaste') {
1468
+ const decayed = [];
1469
+ let mutated = false;
1470
+ for (const item of snap.selfModel.interests) {
1471
+ if (now - item.lastActiveAt > SEVEN_DAYS_MS) {
1472
+ const nextWeight = Number((item.weight * 0.95).toFixed(4));
1473
+ mutated = true;
1474
+ if (nextWeight >= 0.1)
1475
+ decayed.push({ ...item, weight: nextWeight });
1476
+ }
1477
+ else {
1478
+ decayed.push(item);
1479
+ }
1480
+ }
1481
+ for (const topic of options.seedTopics ?? []) {
1482
+ const clean = topic.trim();
1483
+ if (clean === '')
1484
+ continue;
1485
+ this.ingestSignal({
1486
+ source: 'reflection',
1487
+ title: clean,
1488
+ summary: options.conversationNote?.trim() || `事后回味联想主题:${clean}`,
1489
+ topic: clean,
1490
+ autoExplore: false,
1491
+ });
1492
+ if (!decayed.some(d => tokenOverlap(tokenize(d.topic), tokenize(clean)) > 0)) {
1493
+ decayed.push({
1494
+ id: `interest-${randomUUID().slice(0, 8)}`,
1495
+ topic: clean,
1496
+ weight: 0.55,
1497
+ lastActiveAt: now,
1498
+ source: 'conversation',
1499
+ });
1500
+ mutated = true;
1501
+ }
1502
+ }
1503
+ if (mutated) {
1504
+ this.raySelf.evolveSelfModel({
1505
+ interests: decayed,
1506
+ reason: 'aftertaste 事后回味反思:衰减陈旧兴趣并沉淀近期对话联想主题',
1507
+ });
1508
+ }
1509
+ summary = `事后回味(aftertaste):巩固近期对话线索${options.seedTopics?.length ? `(新增点子 ${options.seedTopics.length} 项)` : ''},保留 ${decayed.length} 个活跃兴趣。`;
1510
+ }
1511
+ else if (cadence === 'daily-diary') {
1512
+ const sum = this.summary();
1513
+ summary = `每日日记(daily-diary):今日 owner=${spent.snapshot.ownerTokensUsed} tokens,自由精力=${spent.snapshot.freeTokensUsed}/${spent.snapshot.freeAllowanceTokens} tokens;点子池待处理 ${sum.pooledCount} 项、静默探索 ${sum.exploredCount} 项。`;
1514
+ }
1515
+ else if (cadence === 'weekly-review') {
1516
+ const outcomes = this.listCandidateOutcomes(MAX_CANDIDATE_OUTCOMES);
1517
+ const adoptedCount = outcomes.filter(o => o.disposition === 'adopted').length;
1518
+ const rolledBack = outcomes.filter(o => o.disposition === 'rolled_back');
1519
+ const vetoedCount = outcomes.filter(o => o.disposition === 'vetoed').length;
1520
+ const rejectedCount = outcomes.filter(o => o.disposition === 'rejected').length;
1521
+ const regressionHeadline = growth.ownerService.newlyRegressedCount > 0
1522
+ ? `优先修复新伤退化 ${growth.ownerService.newlyRegressedCount} 项(固有缺口 ${growth.ownerService.persistentGapCount} 项)`
1523
+ : `无新增新伤退化(固有缺口 ${growth.ownerService.persistentGapCount} 项)`;
1524
+ outcomesSummary = `total=${outcomes.length}, adopted=${adoptedCount}, rolled_back=${rolledBack.length}, vetoed=${vetoedCount}, rejected=${rejectedCount}`;
1525
+ summary = `每周复盘(weekly-review):${regressionHeadline},关联回滚候选 ${rolledBack.length} 项;近 ${outcomes.length} 条候选归因三元组已核对(adopted=${adoptedCount}, rolled_back=${rolledBack.length}, vetoed=${vetoedCount}, rejected=${rejectedCount}),Owner 采纳率 ${(growth.proactiveValue.acceptanceRate * 100).toFixed(0)}%。`;
1526
+ }
1527
+ else {
1528
+ const doneSet = new Set(options.completedGoalIds ?? []);
1529
+ const invSet = new Set(options.invalidatedGoalIds ?? []);
1530
+ const nextGoals = snap.selfModel.stageGoals.map(g => {
1531
+ if (doneSet.has(g.id))
1532
+ return { ...g, status: 'completed', updatedAt: now };
1533
+ if (invSet.has(g.id))
1534
+ return { ...g, status: 'invalidated', updatedAt: now };
1535
+ return g;
1536
+ });
1537
+ for (const addGoal of options.newStageGoals ?? []) {
1538
+ if (!nextGoals.some(g => g.id === addGoal.id))
1539
+ nextGoals.push(addGoal);
1540
+ }
1541
+ let activeCount = nextGoals.filter(g => g.status === 'active').length;
1542
+ let replenIdx = 1;
1543
+ while (activeCount < 2) {
1544
+ nextGoals.push({
1545
+ id: `goal-stage-${randomUUID().slice(0, 8)}`,
1546
+ title: `巩固可验证自主协作效率(阶段目标 #${replenIdx})`,
1547
+ completionCriteria: '通过真实任务纠错率下降与新增技能零退化独立验证。',
1548
+ targetHorizonDays: 30,
1549
+ status: 'active',
1550
+ createdAt: now,
1551
+ updatedAt: now,
1552
+ });
1553
+ activeCount += 1;
1554
+ replenIdx += 1;
1555
+ }
1556
+ // Trim excess active goals cleanly beyond 4 if needed, preserving latest goals.
1557
+ let seenActive = 0;
1558
+ const boundedGoals = [];
1559
+ for (let i = nextGoals.length - 1; i >= 0; i -= 1) {
1560
+ const g = nextGoals[i];
1561
+ if (g.status === 'active') {
1562
+ if (seenActive >= 4) {
1563
+ boundedGoals.unshift({ ...g, status: 'completed', updatedAt: now });
1564
+ }
1565
+ else {
1566
+ seenActive += 1;
1567
+ boundedGoals.unshift(g);
1568
+ }
1569
+ }
1570
+ else {
1571
+ boundedGoals.unshift(g);
1572
+ }
1573
+ }
1574
+ this.raySelf.evolveSelfModel({
1575
+ stageGoals: boundedGoals,
1576
+ reason: 'stage-review 阶段复盘:结算已完成/失效阶段目标并保持 2–4 个可衡量活跃目标(保留核心理想稳定)',
1577
+ });
1578
+ summary = `阶段复盘(stage-review):完成 ${doneSet.size} 个目标、废止 ${invSet.size} 个目标,维持 ${seenActive} 个可衡量活跃阶段目标。`;
1579
+ }
1580
+ const artifactPath = join(this.reflectionsDir, `${cadence}.jsonl`);
1581
+ const reflectionId = `refl-${randomUUID()}`;
1582
+ const record = {
1583
+ reflectionId,
1584
+ cadence,
1585
+ summary,
1586
+ tokensUsed: tokenCost,
1587
+ artifactPath,
1588
+ createdAt: now,
1589
+ };
1590
+ appendFileSync(artifactPath, `${JSON.stringify(record)}\n`, { encoding: 'utf8', mode: 0o600 });
1591
+ db.prepare(`
1592
+ INSERT INTO ray_reflections (reflection_id, cadence, summary, tokens_used, artifact_path, created_at)
1593
+ VALUES (?, ?, ?, ?, ?, ?)
1594
+ `).run(reflectionId, cadence, summary, tokenCost, artifactPath, now);
1595
+ this.raySelf.recordAutobiography({
1596
+ kind: 'reflection',
1597
+ summary,
1598
+ reason: `${cadence} 节律反思(消耗自由精力 ${tokenCost} tokens)`,
1599
+ targetRef: reflectionId,
1600
+ });
1601
+ if (cadence === 'daily-diary')
1602
+ this.lastDailyAt = Math.max(this.lastDailyAt, now);
1603
+ if (cadence === 'weekly-review')
1604
+ this.lastWeeklyAt = Math.max(this.lastWeeklyAt, now);
1605
+ if (cadence === 'stage-review')
1606
+ this.lastStageAt = Math.max(this.lastStageAt, now);
1607
+ const recentIdeas = this.listIdeas({ limit: 8 });
1608
+ this.trackTask(this.runDetached(() => this.synthesizeReflectionWithLlm(record, {
1609
+ baselineSummary: summary,
1610
+ ...(options.conversationNote === undefined ? {} : { conversationNote: options.conversationNote }),
1611
+ ...(outcomesSummary === undefined ? {} : { outcomesSummary }),
1612
+ recentIdeas,
1613
+ growth,
1614
+ selfSummary: snap.selfModel.selfSummary,
1615
+ })));
1616
+ return {
1617
+ ok: true,
1618
+ reflection: record,
1619
+ energy: this.raySelf.energySnapshot(),
1620
+ };
1621
+ }
1622
+ listIdeas(filter = {}) {
1623
+ const db = this.assertOpen();
1624
+ const clauses = [];
1625
+ const params = [];
1626
+ if (filter.tier !== undefined) {
1627
+ clauses.push('tier = ?');
1628
+ params.push(filter.tier);
1629
+ }
1630
+ if (filter.status !== undefined) {
1631
+ clauses.push('status = ?');
1632
+ params.push(filter.status);
1633
+ }
1634
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
1635
+ const limit = Math.max(1, Math.min(100, Math.trunc(filter.limit ?? 20)));
1636
+ params.push(limit);
1637
+ const rows = db.prepare(`SELECT * FROM ray_ideas ${where} ORDER BY combined_score DESC, updated_at DESC LIMIT ?`)
1638
+ .all(...params);
1639
+ return rows.map(rowToIdea);
1640
+ }
1641
+ summary() {
1642
+ const db = this.assertOpen();
1643
+ const rows = db.prepare('SELECT tier, status, COUNT(*) AS cnt FROM ray_ideas GROUP BY tier, status')
1644
+ .all();
1645
+ let pooledCount = 0;
1646
+ let exploredCount = 0;
1647
+ let naturalMentionCount = 0;
1648
+ let proposeWorkCount = 0;
1649
+ let acceptedCount = 0;
1650
+ let annoyedCount = 0;
1651
+ for (const r of rows) {
1652
+ if (r.status === 'pooled')
1653
+ pooledCount += r.cnt;
1654
+ if (r.status === 'explored')
1655
+ exploredCount += r.cnt;
1656
+ if (r.tier === 'natural_mention' && (r.status === 'pooled' || r.status === 'explored'))
1657
+ naturalMentionCount += r.cnt;
1658
+ if (r.tier === 'propose_work' && r.status === 'pooled')
1659
+ proposeWorkCount += r.cnt;
1660
+ if (r.status === 'accepted')
1661
+ acceptedCount += r.cnt;
1662
+ if (r.status === 'annoyed')
1663
+ annoyedCount += r.cnt;
1664
+ }
1665
+ const reflections = db.prepare('SELECT * FROM ray_reflections ORDER BY created_at DESC LIMIT 6').all()
1666
+ .map(r => ({
1667
+ reflectionId: r.reflection_id,
1668
+ cadence: r.cadence,
1669
+ summary: r.summary,
1670
+ tokensUsed: r.tokens_used,
1671
+ artifactPath: r.artifact_path,
1672
+ createdAt: r.created_at,
1673
+ }));
1674
+ return {
1675
+ active: !this.closed,
1676
+ pooledCount,
1677
+ exploredCount,
1678
+ naturalMentionCount,
1679
+ proposeWorkCount,
1680
+ acceptedCount,
1681
+ annoyedCount,
1682
+ tuning: this.tuning,
1683
+ recentReflections: reflections,
1684
+ };
1685
+ }
1686
+ dispose() {
1687
+ if (this.closed)
1688
+ return this.disposePromise;
1689
+ this.closed = true;
1690
+ this.invalidateTaughtCaches();
1691
+ this.abortController.abort(new Error('assistant-proactive: disposed'));
1692
+ while (this.disposers.length > 0) {
1693
+ const fn = this.disposers.pop();
1694
+ try {
1695
+ fn();
1696
+ }
1697
+ catch { /* ignore */ }
1698
+ }
1699
+ if (this.inFlightTasks.size === 0) {
1700
+ try {
1701
+ this.db?.close();
1702
+ }
1703
+ catch { /* ignore */ }
1704
+ this.db = undefined;
1705
+ return;
1706
+ }
1707
+ const pending = Promise.allSettled(this.inFlightTasks).then(() => {
1708
+ try {
1709
+ this.db?.close();
1710
+ }
1711
+ catch { /* ignore */ }
1712
+ this.db = undefined;
1713
+ });
1714
+ this.disposePromise = pending;
1715
+ return pending;
1716
+ }
1717
+ }
1718
+ //# sourceMappingURL=ray-cognitive-loop.js.map