mio-agent-runtime 0.5.16 → 0.5.22

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.
@@ -1,1610 +1,1529 @@
1
- #!/usr/bin/env node
2
- 'use strict'
3
-
4
- const fs = require('fs')
5
- const path = require('path')
6
- const crypto = require('crypto')
7
- const readline = require('readline')
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const crypto = require('crypto')
7
+ const readline = require('readline')
8
8
  const { execFileSync } = require('child_process')
9
9
  const { getEvolutionStatus } = require('../runtime-modules.js')
10
10
  const { listHostCapabilities } = require('../host-capabilities.js')
11
11
  const { createEvolutionCutoverTools } = require('../evolution-cutover.js')
12
-
13
- const SERVER_INFO = { name: 'mio-intelligence-mcp', version: '0.1.0' }
14
- const PROTOCOL_VERSION = '2024-11-05'
15
-
16
- const dataDir = path.resolve(
17
- process.env.MIO_DATA_DIR || path.join(process.cwd(), '.mio-intelligence')
18
- )
19
- const memoryPath = path.join(dataDir, 'memory.jsonl')
20
- const tracePath = path.join(dataDir, 'traces.jsonl')
21
- const experienceReusePath = path.join(dataDir, 'experience_reuse.jsonl')
22
- const queryPath = path.join(dataDir, 'queries.jsonl')
23
- const agentsPath = path.join(dataDir, 'agents.jsonl')
24
- const subscriptionPath = path.join(dataDir, 'subscriptions.jsonl')
12
+ const { createMemoryStore } = require('../memory-store.js')
13
+ const { createDigest } = require('../digest.js')
14
+
15
+ const { CreativityEngine } = require('../creativity-engine.js')
16
+
17
+ // Observer research pipeline (optional — installed via @akemi-mio/observer)
18
+ let ObserverStore = null
19
+ let ObserverService = null
20
+ try {
21
+ const obs = require('@akemi-mio/observer')
22
+ ObserverStore = obs.ObserverStore
23
+ ObserverService = obs.ObserverService
24
+ } catch {}
25
+
26
+ // Insight self-observation engine (optional — installed via @akemi-mio/insight)
27
+ let InsightStore = null
28
+ let InsightGenerator = null
29
+ let PresenceService = null
30
+ try {
31
+ const insight = require('@akemi-mio/insight')
32
+ InsightStore = insight.InsightStore
33
+ InsightGenerator = insight.InsightGenerator
34
+ PresenceService = insight.PresenceService
35
+ } catch {}
36
+
37
+ const SERVER_INFO = { name: 'mio-intelligence-mcp', version: '0.1.0' }
38
+ const PROTOCOL_VERSION = '2024-11-05'
39
+
40
+ // ═══════════════════════════════════════════════
41
+ // LLM chatJson — used by creativity engine
42
+ // ═══════════════════════════════════════════════
43
+
44
+ async function chatJson(userText, opts = {}) {
45
+ const apiUrl = process.env.LLM_API_URL || 'https://opencode.ai/zen/go/v1/chat/completions'
46
+ const apiKey = process.env.LLM_KEY || ''
47
+ const model = process.env.LLM_CHAT_MODEL || process.env.LLM_MODEL || 'deepseek-v4-flash'
48
+ const system = opts.system || 'You are a creative AI assistant. Output JSON.'
49
+ const temperature = opts.temperature ?? 0.3
50
+
51
+ try {
52
+ const resp = await fetch(apiUrl, {
53
+ method: 'POST',
54
+ headers: {
55
+ 'Content-Type': 'application/json',
56
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
57
+ },
58
+ body: JSON.stringify({
59
+ model,
60
+ temperature,
61
+ messages: [
62
+ { role: 'system', content: system },
63
+ { role: 'user', content: userText },
64
+ ],
65
+ response_format: { type: 'json_object' },
66
+ }),
67
+ signal: AbortSignal.timeout(opts.timeoutMs || 30000),
68
+ })
69
+
70
+ if (!resp.ok) return { error: `HTTP ${resp.status}` }
71
+ const json = await resp.json()
72
+ const text = json.choices?.[0]?.message?.content || ''
73
+ try {
74
+ return { data: JSON.parse(text) }
75
+ } catch {
76
+ return { data: text }
77
+ }
78
+ } catch (err) {
79
+ return { error: String(err) }
80
+ }
81
+ }
82
+
83
+ const dataDir = path.resolve(
84
+ process.env.MIO_DATA_DIR || path.join(process.cwd(), '.mio-intelligence')
85
+ )
86
+ const memoryPath = path.join(dataDir, 'memory.jsonl')
87
+ const tracePath = path.join(dataDir, 'traces.jsonl')
88
+ const experienceReusePath = path.join(dataDir, 'experience_reuse.jsonl')
89
+ const queryPath = path.join(dataDir, 'queries.jsonl')
90
+ const agentsPath = path.join(dataDir, 'agents.jsonl')
91
+ const subscriptionPath = path.join(dataDir, 'subscriptions.jsonl')
25
92
  const digestStatePath = path.join(dataDir, 'digest_state.json')
26
93
  fs.mkdirSync(dataDir, { recursive: true })
27
94
 
28
95
  const { loadPhase0, summarizePhase0, renderPhase0Markdown } = require('./phase0')
29
96
  const evolutionCutover = createEvolutionCutoverTools({ dataDir, appendJsonl, readJsonl, projectName })
30
-
31
- let runtimeContext = {}
32
- try {
33
- const rawContext = process.env.MIO_CONTEXT
34
- if (rawContext) {
35
- const parsed = JSON.parse(rawContext)
36
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
37
- runtimeContext = parsed
38
- }
39
- }
40
- } catch (_) {
41
- runtimeContext = {}
42
- }
43
-
44
- function runtimeAgentId() {
45
- return runtimeContext.agentId || null
46
- }
47
-
48
- // Phase 0 auto-claim: match memory.query results with a later task_outcome
49
- // from the same agent+project, so reuse evidence does not depend on the
50
- // agent self-reporting mio.experience.reuse.
51
- const REUSE_MATCH_WINDOW_MS = (() => {
52
- const minutes = Number(process.env.MIO_REUSE_MATCH_WINDOW_MIN)
53
- return Number.isFinite(minutes) && minutes > 0 ? minutes * 60 * 1000 : 60 * 60 * 1000
54
- })()
55
- const MAX_RECENT_QUERIES = 200
56
- let recentQueries = []
57
-
58
- function loadRecentQueries() {
59
- const now = Date.now()
60
- const entries = readJsonl(queryPath)
61
- .filter(
62
- (entry) =>
63
- entry &&
64
- typeof entry.agent === 'string' &&
65
- entry.agent &&
66
- typeof entry.expiresAt === 'number' &&
67
- entry.expiresAt > now
68
- )
69
- .slice(-MAX_RECENT_QUERIES)
70
- recentQueries = entries
71
- return entries
72
- }
73
-
74
- function persistRecentQueries(entries) {
75
- const limited = entries.slice(-MAX_RECENT_QUERIES)
76
- fs.mkdirSync(dataDir, { recursive: true })
77
- fs.writeFileSync(
78
- queryPath,
79
- limited.length > 0 ? limited.map((entry) => JSON.stringify(entry)).join('\n') + '\n' : '',
80
- 'utf8'
81
- )
82
- recentQueries = limited
83
- return limited
84
- }
85
-
86
- function createId(prefix) {
87
- return `${prefix}_${Date.now()}_${crypto.randomBytes(6).toString('hex')}`
88
- }
89
-
90
- function appendJsonl(file, value) {
91
- fs.appendFileSync(file, `${JSON.stringify(value)}\n`, 'utf8')
92
- }
93
-
94
- function writeJsonl(file, values) {
95
- fs.mkdirSync(path.dirname(file), { recursive: true })
96
- fs.writeFileSync(
97
- file,
98
- values.length > 0 ? values.map((value) => JSON.stringify(value)).join('\n') + '\n' : '',
99
- 'utf8'
100
- )
101
- }
102
-
103
- function readJsonl(file) {
104
- if (!fs.existsSync(file)) return []
105
- return fs
106
- .readFileSync(file, 'utf8')
107
- .split(/\r?\n/)
108
- .filter(Boolean)
109
- .map((line) => {
110
- try {
111
- return JSON.parse(line)
112
- } catch (_) {
113
- return null
114
- }
115
- })
116
- .filter(Boolean)
117
- }
118
-
119
- let lastProjectCwd = null
120
- let lastProjectName = null
121
-
122
- function projectName() {
123
- const currentCwd = process.cwd()
124
- if (lastProjectCwd === currentCwd && lastProjectName) {
125
- return lastProjectName
126
- }
127
- lastProjectCwd = currentCwd
128
- if (runtimeContext.project) {
129
- lastProjectName = runtimeContext.project
130
- return lastProjectName
131
- }
132
- try {
133
- const commonDir = execFileSync(
134
- 'git',
135
- ['rev-parse', '--path-format=absolute', '--git-common-dir'],
136
- {
137
- cwd: currentCwd,
138
- encoding: 'utf8',
139
- stdio: ['ignore', 'pipe', 'ignore'],
140
- }
141
- ).trim()
142
- if (commonDir) {
143
- const repoRoot = path.dirname(commonDir)
144
- const name = path.basename(repoRoot)
145
- if (name) {
146
- lastProjectName = name
147
- return lastProjectName
148
- }
149
- }
150
- } catch (_) {
151
- // fall through to cwd basename
152
- }
153
- lastProjectName = path.basename(currentCwd)
154
- return lastProjectName
155
- }
156
-
157
- function normalizeTags(tags) {
158
- if (Array.isArray(tags)) return tags.map((tag) => String(tag).trim()).filter(Boolean)
159
- if (typeof tags === 'string') {
160
- return tags
161
- .split(',')
162
- .map((tag) => tag.trim())
163
- .filter(Boolean)
164
- }
165
- return []
166
- }
167
-
168
- function tokenize(text) {
169
- const normalized = String(text || '').toLowerCase()
170
- const latin = normalized.match(/[a-z0-9]+/g) || []
171
- const cjk = (normalized.match(/[\u4e00-\u9fff]/g) || []).map((char) => `cjk:${char}`)
172
- return [...latin, ...cjk]
173
- }
174
-
175
- function normalizeScope(value) {
176
- const s = String(value || 'project').trim().toLowerCase()
177
- if (s === 'global' || s === 'all') return s
178
- return 'project'
179
- }
180
-
181
- function isGlobalRecord(record) {
182
- return String(record.scope || '').trim().toLowerCase() === 'global'
183
- }
184
-
185
- function matchesProjectScope(record, project, scope) {
186
- const s = normalizeScope(scope)
187
- if (s === 'global') return isGlobalRecord(record)
188
- if (s === 'all') {
189
- if (isGlobalRecord(record)) return true
190
- return !project || record.project === project
191
- }
192
- // project (default): project-scoped records matching the project only
193
- if (isGlobalRecord(record)) return false
194
- return !project || record.project === project
195
- }
196
-
197
- function latinTokens(text) {
198
- return String(text || '').toLowerCase().match(/[a-z0-9]+/g) || []
199
- }
200
-
201
- function cjkBigrams(text) {
202
- const chars = String(text || '').toLowerCase().match(/[\u4e00-\u9fff]/g) || []
203
- const bigrams = new Set()
204
- for (let i = 0; i + 1 < chars.length; i += 1) {
205
- bigrams.add(`${chars[i]}${chars[i + 1]}`)
206
- }
207
- return bigrams
208
- }
209
-
210
- function scoreRecord(record, queryText, project, evidence) {
211
- if (project && record.project && record.project !== project) return 0
212
- const content = `${record.content || ''} ${(record.tags || []).join(' ')} ${record.kind || ''}`
213
- const haystackTokens = tokenize(content)
214
- const haystackLatin = latinTokens(content)
215
- const queryTokens = tokenize(queryText)
216
- let score = 0
217
- for (const token of queryTokens) {
218
- if (haystackTokens.includes(token)) score += 2
219
- }
220
- const queryLatin = queryTokens.filter((token) => !token.startsWith('cjk:'))
221
- for (const token of queryLatin) {
222
- if (
223
- token.length >= 3 &&
224
- haystackLatin.some((item) => item.startsWith(token) || token.startsWith(item))
225
- ) {
226
- score += 1
227
- }
228
- }
229
- const queryBigrams = cjkBigrams(queryText)
230
- const haystackBigrams = cjkBigrams(content)
231
- if (queryBigrams.size > 0 && haystackBigrams.size > 0) {
232
- let matched = 0
233
- for (const bigram of queryBigrams) {
234
- if (haystackBigrams.has(bigram)) matched += 1
235
- }
236
- score += matched * 1.5
237
- }
238
- // Recency only boosts ranking among actual matches; it must not enable recall.
239
- if (score > 0 && record.timestamp) {
240
- const ageDays = Math.max(0, (Date.now() - Date.parse(record.timestamp)) / 86400000)
241
- score += Math.max(0, 0.5 - ageDays * 0.05)
242
- }
243
- // Evidence weighting (P2): memories successfully reused rank higher; never enables recall.
244
- if (score > 0 && evidence && evidence.has(record.id)) {
245
- const ev = evidence.get(record.id)
246
- score += Math.min(2, ev.reuseCount * 0.6 + (ev.confirmedCount > 0 ? 1 : 0))
247
- }
248
- return score
249
- }
250
-
251
- function matchesMemoryFilters(record, kind, tags) {
252
- if (kind) {
253
- const recordKind = String(record.kind || '').trim().toLowerCase()
254
- if (recordKind !== kind) return false
255
- }
256
- if (tags.length > 0) {
257
- const recordTags = new Set(
258
- (record.tags || []).map((tag) => String(tag).trim().toLowerCase()),
259
- )
260
- for (const tag of tags) {
261
- if (!recordTags.has(tag)) return false
262
- }
263
- }
264
- return true
265
- }
266
-
267
- function queryMemory(args = {}) {
268
- const query = String(args.query || '')
269
- const project = args.project || projectName()
270
- const limit = Math.min(Math.max(Number(args.limit) || 5, 1), 20)
271
- const kind = args.kind ? String(args.kind).trim().toLowerCase() : null
272
- const tags = Array.isArray(args.tags)
273
- ? args.tags.map((tag) => String(tag).trim().toLowerCase()).filter(Boolean)
274
- : []
275
- const scope = normalizeScope(args.scope)
276
- const evidence = loadEvidenceWeights()
277
- const scoreFor = (record) =>
278
- scoreRecord(record, query, project, evidence) +
279
- (scope === 'all' && isGlobalRecord(record) ? 0.5 : 0)
280
- const results = readJsonl(memoryPath)
281
- .filter((record) => record.archived !== true)
282
- .filter((record) => matchesMemoryFilters(record, kind, tags))
283
- .filter((record) => matchesProjectScope(record, project, scope))
284
- .filter((record) => scoreFor(record) > 0)
285
- .sort((a, b) => {
286
- return scoreFor(b) - scoreFor(a)
287
- })
288
- .slice(0, limit)
289
- .map((record) => {
290
- const ev = evidence.get(record.id)
291
- if (!ev) return record
292
- return {
293
- ...record,
294
- evidence: {
295
- reuseCount: ev.reuseCount,
296
- confirmedCount: ev.confirmedCount,
297
- lastReusedAt: ev.lastReusedAt,
298
- },
299
- }
300
- })
301
- const layerCounts = { project: 0, global: 0 }
302
- for (const record of results) {
303
- if (record.scope === 'global' || !record.project) layerCounts.global += 1
304
- else layerCounts.project += 1
305
- }
306
- if (results.length > 0) {
307
- const timestamp = Date.now()
308
- const entries = loadRecentQueries()
309
- entries.push({
310
- agent: runtimeAgentId() || 'mcp',
311
- project,
312
- query,
313
- resultIds: results.map((record) => record.id).filter(Boolean),
314
- resultSources: results.map((record) => record.source || null),
315
- timestamp,
316
- expiresAt: timestamp + REUSE_MATCH_WINDOW_MS,
317
- })
318
- persistRecentQueries(entries)
319
- }
320
- return {
321
- query,
322
- project,
323
- scope,
324
- layers: layerCounts,
325
- kind: kind || null,
326
- tags: tags,
327
- count: results.length,
328
- results,
329
- }
330
- }
331
-
332
- function recordMemory(args = {}) {
333
- const content = String(args.content || '').trim()
334
- if (!content) throw new Error('memory.record requires a non-empty content')
335
- const scope = normalizeScope(args.scope)
336
- const record = {
337
- id: createId('mem'),
338
- timestamp: new Date().toISOString(),
339
- kind: args.kind || 'note',
340
- content,
341
- tags: normalizeTags(args.tags),
342
- project: scope === 'global' ? null : args.project || projectName(),
343
- scope,
344
- source: args.source || runtimeAgentId() || 'mcp',
345
- }
346
- appendJsonl(memoryPath, record)
347
- return record
348
- }
349
-
350
- function ingestObservation(args = {}) {
351
- const traceId = String(args.trace_id || '').trim()
352
- const eventType = String(args.event_type || '').trim()
353
- if (!traceId) throw new Error('observer.ingest requires trace_id')
354
- if (!eventType) throw new Error('observer.ingest requires event_type')
355
- const event = {
356
- id: createId('trace'),
357
- timestamp: new Date().toISOString(),
358
- trace_id: traceId,
359
- event_type: eventType,
360
- outcome: args.outcome || null,
361
- payload: args.payload || {},
362
- agent: args.agent || runtimeAgentId(),
363
- host: args.host || 'mcp',
364
- project: args.project || projectName(),
365
- }
366
- appendJsonl(tracePath, event)
367
- const autoClaims = autoClaimExperienceReuse(event)
368
- if (autoClaims.length > 0) {
369
- return { recorded: true, event, autoClaims }
370
- }
371
- return { recorded: true, event }
372
- }
373
-
374
- function autoClaimExperienceReuse(event) {
375
- if (String(event.event_type || '').toLowerCase() !== 'task_outcome') return []
376
- const targetAgent = String(event.agent || '').trim()
377
- if (!targetAgent) return []
378
- const now = Date.now()
379
- const claims = []
380
- const remaining = []
381
- const entries = loadRecentQueries()
382
- for (const entry of entries) {
383
- const expired = now - entry.timestamp > REUSE_MATCH_WINDOW_MS
384
- const matches =
385
- entry.agent === targetAgent && (!event.project || entry.project === event.project)
386
- if (expired || matches) {
387
- if (matches && !expired) {
388
- claims.push(buildAutoClaim(entry, event, targetAgent))
389
- }
390
- continue
391
- }
392
- remaining.push(entry)
393
- }
394
- persistRecentQueries(remaining)
395
- for (const evidence of claims) {
396
- appendJsonl(experienceReusePath, evidence)
397
- }
398
- return claims
399
- }
400
-
401
- function buildAutoClaim(entry, event, targetAgent) {
402
- const crossSourceIndex = entry.resultSources.findIndex(
403
- (source) => source && String(source).toLowerCase() !== targetAgent.toLowerCase()
404
- )
405
- const sourceAgent =
406
- crossSourceIndex >= 0
407
- ? String(entry.resultSources[crossSourceIndex])
408
- : targetAgent
409
- const experienceId =
410
- entry.resultIds[crossSourceIndex >= 0 ? crossSourceIndex : 0] ||
411
- entry.resultIds[0] ||
412
- 'unknown'
413
- const outcomeImproved = String(event.outcome || '').toLowerCase() === 'success'
414
- return {
415
- id: createId('xfer'),
416
- timestamp: new Date().toISOString(),
417
- sourceAgent,
418
- targetAgent,
419
- experienceId,
420
- reuse: true,
421
- behaviorChanged: false,
422
- outcomeImproved,
423
- project: entry.project,
424
- source: 'auto_claim',
425
- traceId: event.trace_id || null,
426
- notes: `Auto-claimed: memory.query "${entry.query}" matched task_outcome ${event.outcome || 'unknown'} in trace ${event.trace_id || 'unknown'}.`,
427
- }
428
- }
429
-
430
- const SUBSCRIPTION_DEFAULT_TTL_DAYS = 30
431
- const MAX_SUBSCRIPTIONS_PER_AGENT = 20
432
- const MAX_DIGEST_EVENTS = 100
433
-
434
- function readDigestState() {
435
- if (!fs.existsSync(digestStatePath)) return {}
436
- try {
437
- const parsed = JSON.parse(fs.readFileSync(digestStatePath, 'utf8'))
438
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
439
- } catch (_) {
440
- return {}
441
- }
442
- }
443
-
444
- function writeDigestState(state) {
445
- fs.mkdirSync(dataDir, { recursive: true })
446
- fs.writeFileSync(digestStatePath, JSON.stringify(state), 'utf8')
447
- }
448
-
449
- function subscribeKey(agent, project, eventTypes, topic) {
450
- return `${agent}|${project}|${eventTypes.join(',')}|${topic || ''}`
451
- }
452
-
453
- function loadActiveSubscriptions(agent) {
454
- const now = Date.now()
455
- return readJsonl(subscriptionPath)
456
- .filter((subscription) => subscription && subscription.agent === agent)
457
- .filter((subscription) => {
458
- if (subscription.expiresAt) {
459
- const expires = new Date(subscription.expiresAt).getTime()
460
- if (Number.isFinite(expires) && expires <= now) return false
461
- }
462
- return true
463
- })
464
- }
465
-
466
- function subscribeObserver(args = {}) {
467
- const agent = runtimeAgentId() || 'mcp'
468
- const project = args.project || projectName()
469
- const eventTypes = Array.isArray(args.eventTypes)
470
- ? args.eventTypes.map((value) => String(value).trim().toLowerCase()).filter(Boolean)
471
- : []
472
- const topic = args.topic ? String(args.topic).trim().slice(0, 120) : ''
473
- const ttlDays = Number(args.ttlDays) || SUBSCRIPTION_DEFAULT_TTL_DAYS
474
- const ttlMs = Math.max(1, ttlDays) * 24 * 60 * 60 * 1000
475
-
476
- const subscriptions = readJsonl(subscriptionPath)
477
- const key = subscribeKey(agent, project, eventTypes, topic)
478
- let existing = subscriptions.find((subscription) => {
479
- return (
480
- subscription &&
481
- subscribeKey(
482
- subscription.agent,
483
- subscription.project,
484
- subscription.eventTypes || [],
485
- subscription.topic || '',
486
- ) === key
487
- )
488
- })
489
- const now = new Date()
490
- const expiresAt = new Date(now.getTime() + ttlMs).toISOString()
491
- if (existing) {
492
- existing.updatedAt = now.toISOString()
493
- existing.expiresAt = expiresAt
494
- } else {
495
- existing = {
496
- id: createId('sub'),
497
- agent,
498
- project,
499
- eventTypes,
500
- topic: topic || null,
501
- createdAt: now.toISOString(),
502
- updatedAt: now.toISOString(),
503
- expiresAt,
504
- }
505
- subscriptions.push(existing)
506
- }
507
- const agentSubscriptions = subscriptions.filter((subscription) => subscription.agent === agent)
508
- if (agentSubscriptions.length > MAX_SUBSCRIPTIONS_PER_AGENT) {
509
- throw new Error(`Too many subscriptions for agent ${agent} (max ${MAX_SUBSCRIPTIONS_PER_AGENT})`)
510
- }
511
- writeJsonl(subscriptionPath, subscriptions)
512
- return { subscribed: true, subscription: existing, project }
513
- }
514
-
515
- function observerDigest(args = {}) {
516
- const agent = runtimeAgentId() || 'mcp'
517
- const project = args.project || projectName()
518
- const limit = Math.min(Math.max(Number(args.limit) || 20, 1), MAX_DIGEST_EVENTS)
519
- const filterEventTypes = Array.isArray(args.eventTypes)
520
- ? args.eventTypes.map((value) => String(value).trim().toLowerCase()).filter(Boolean)
521
- : null
522
-
523
- let subscriptions = loadActiveSubscriptions(agent)
524
- if (args.project) {
525
- subscriptions = subscriptions.filter((subscription) => subscription.project === project)
526
- }
527
- if (filterEventTypes) {
528
- subscriptions = subscriptions.filter((subscription) => {
529
- if ((subscription.eventTypes || []).length === 0) return true
530
- return filterEventTypes.some((eventType) =>
531
- (subscription.eventTypes || []).includes(eventType),
532
- )
533
- })
534
- }
535
-
536
- const state = readDigestState()
537
- const traces = readJsonl(tracePath)
538
- const digestTime = new Date().toISOString()
539
- const events = []
540
- const seenIds = new Set()
541
- const matchedSubscriptionIds = new Set()
542
-
543
- for (const subscription of subscriptions) {
544
- const cursor = state[subscription.id] || null
545
- const cursorTime = cursor ? Date.parse(cursor) : null
546
- const subscriptionEventTypes = subscription.eventTypes || []
547
- let lastEventTime = null
548
- for (const event of traces) {
549
- if (subscription.project && event.project && event.project !== subscription.project) {
550
- continue
551
- }
552
- if (
553
- subscriptionEventTypes.length > 0 &&
554
- !subscriptionEventTypes.includes(String(event.event_type || '').toLowerCase())
555
- ) {
556
- continue
557
- }
558
- if (subscription.topic) {
559
- const haystack = `${event.event_type || ''} ${JSON.stringify(event.payload || {})}`
560
- .toLowerCase()
561
- if (!haystack.includes(subscription.topic.toLowerCase())) continue
562
- }
563
- const eventTime = event.timestamp ? Date.parse(event.timestamp) : null
564
- if (cursorTime !== null && eventTime !== null && eventTime <= cursorTime) continue
565
- if (eventTime !== null && (lastEventTime === null || eventTime > lastEventTime)) {
566
- lastEventTime = eventTime
567
- }
568
- if (seenIds.has(event.id)) continue
569
- seenIds.add(event.id)
570
- events.push({
571
- id: event.id,
572
- trace_id: event.trace_id || null,
573
- event_type: event.event_type,
574
- outcome: event.outcome || null,
575
- timestamp: event.timestamp,
576
- agent: event.agent || null,
577
- payload: event.payload || null,
578
- })
579
- matchedSubscriptionIds.add(subscription.id)
580
- if (events.length >= limit) break
581
- }
582
- if (lastEventTime !== null) {
583
- state[subscription.id] = new Date(lastEventTime).toISOString()
584
- } else if (cursor === null) {
585
- state[subscription.id] = digestTime
586
- }
587
- if (events.length >= limit) break
588
- }
589
-
590
- writeDigestState(state)
591
- return {
592
- project,
593
- agent,
594
- subscriptionCount: subscriptions.length,
595
- matchedSubscriptions: Array.from(matchedSubscriptionIds),
596
- count: events.length,
597
- events,
598
- }
599
- }
600
-
601
- function contentTokens(value) {
602
- const text = String(value || '').toLowerCase()
603
- const latin = text.match(/[a-z0-9]+/g) || []
604
- const chars = text.match(/[\u4e00-\u9fff]/g) || []
605
- const bigrams = []
606
- for (let i = 0; i < chars.length - 1; i++) {
607
- bigrams.push(`${chars[i]}${chars[i + 1]}`)
608
- }
609
- return [...latin, ...bigrams]
610
- }
611
-
612
- function jaccardSimilarity(a, b) {
613
- const setA = new Set(contentTokens(a))
614
- const setB = new Set(contentTokens(b))
615
- if (setA.size === 0 || setB.size === 0) return 0
616
- let intersection = 0
617
- for (const token of setA) {
618
- if (setB.has(token)) intersection += 1
619
- }
620
- const union = setA.size + setB.size - intersection
621
- return union === 0 ? 0 : intersection / union
622
- }
623
-
624
- function findDuplicateGroups(records, limit) {
625
- const parent = new Map()
626
- for (const record of records) parent.set(record.id, record.id)
627
- const find = (id) => {
628
- while (parent.get(id) !== id) {
629
- parent.set(id, parent.get(parent.get(id)))
630
- id = parent.get(id)
631
- }
632
- return id
633
- }
634
- const union = (a, b) => {
635
- const ra = find(a)
636
- const rb = find(b)
637
- if (ra !== rb) parent.set(ra, rb)
638
- }
639
- for (let i = 0; i < records.length; i++) {
640
- for (let j = i + 1; j < records.length; j++) {
641
- if (
642
- jaccardSimilarity(records[i].content, records[j].content) >= MEMORY_DUPLICATE_SIMILARITY
643
- ) {
644
- union(records[i].id, records[j].id)
645
- }
646
- }
647
- }
648
- const byRoot = new Map()
649
- for (const record of records) {
650
- const root = find(record.id)
651
- if (!byRoot.has(root)) byRoot.set(root, [])
652
- byRoot.get(root).push(record)
653
- }
654
- return Array.from(byRoot.values())
655
- .filter((group) => group.length >= 2)
656
- .sort((a, b) => b.length - a.length)
657
- .slice(0, limit)
658
- }
659
-
660
- function analyzeMemory(args = {}) {
661
- const project = args.project || projectName()
662
- const limit = Math.min(Math.max(Number(args.limit) || 5, 1), 20)
663
- const records = readJsonl(memoryPath).filter(
664
- (record) => !project || record.project === project || !record.project,
665
- )
666
- const archived = records.filter((record) => record.archived === true).length
667
- const activeRecords = records.filter((record) => record.archived !== true)
668
- const total = activeRecords.length
669
- const layerCounts = { project: 0, global: 0 }
670
- for (const record of activeRecords) {
671
- if (record.scope === 'global' || !record.project) layerCounts.global += 1
672
- else layerCounts.project += 1
673
- }
674
-
675
- const byKind = {}
676
- const lowQuality = []
677
- for (const record of activeRecords) {
678
- const kind = String(record.kind || '').trim() || 'unknown'
679
- byKind[kind] = (byKind[kind] || 0) + 1
680
- const content = String(record.content || '').trim()
681
- const issues = []
682
- if (!content) issues.push('missing content')
683
- else if (content.length < MEMORY_SHORT_CONTENT_MIN) issues.push('content too short')
684
- if (!record.kind || !String(record.kind).trim()) issues.push('missing kind')
685
- if (issues.length > 0) {
686
- lowQuality.push({
687
- id: record.id,
688
- timestamp: record.timestamp,
689
- kind: record.kind || null,
690
- content: content.slice(0, 200) || null,
691
- issues,
692
- })
693
- }
694
- }
695
-
696
- let duplicateGroups = []
697
- let duplicatesSkipped = false
698
- if (activeRecords.length > MAX_PAIRWISE_MEMORY) {
699
- duplicatesSkipped = true
700
- } else {
701
- duplicateGroups = findDuplicateGroups(activeRecords, limit).map((group) => ({
702
- size: group.length,
703
- records: group.map((record) => ({
704
- id: record.id,
705
- timestamp: record.timestamp,
706
- kind: record.kind || null,
707
- content: String(record.content || '').slice(0, 200),
708
- })),
709
- }))
710
- }
711
-
712
- const issues = {
713
- lowQuality: lowQuality.length,
714
- duplicateGroups: duplicateGroups.length,
715
- duplicatesSkipped,
716
- }
717
-
718
- const suggestions = []
719
- if (duplicateGroups.length > 0) {
720
- suggestions.push(
721
- `Found ${duplicateGroups.length} duplicate group(s); consider archiving or merging duplicates to keep recall precise.`,
722
- )
723
- }
724
- if (lowQuality.length > 0) {
725
- suggestions.push(
726
- `${lowQuality.length} low-quality record(s) (missing kind/content or too short); consider fixing or removing them.`,
727
- )
728
- }
729
- if (total === 0) {
730
- suggestions.push('No memory records for this project yet.')
731
- } else if (duplicateGroups.length === 0 && lowQuality.length === 0) {
732
- suggestions.push('Memory looks healthy; no dedup or quality fixes needed.')
733
- }
734
-
735
- return {
736
- project: project || null,
737
- total,
738
- archived,
739
- layers: layerCounts,
740
- byKind,
741
- issues,
742
- duplicates: duplicateGroups,
743
- lowQuality: lowQuality.slice(0, limit),
744
- suggestions,
745
- }
746
- }
747
-
748
- function migrateMemory(args = {}) {
749
- const idsInput = Array.isArray(args.ids) ? args.ids : []
750
- const ids = idsInput.map((value) => String(value).trim()).filter(Boolean)
751
- if (ids.length === 0) throw new Error('memory.migrate requires ids (array of memory record ids)')
752
- const targetScope = normalizeScope(args.scope)
753
- if (targetScope === 'all') throw new Error('memory.migrate scope must be project or global')
754
- const project = args.project || projectName()
755
- const reason = args.reason ? String(args.reason).trim().slice(0, 200) : null
756
-
757
- const records = readJsonl(memoryPath)
758
- const idSet = new Set(ids)
759
- const updated = []
760
- const unchanged = []
761
- const notFound = [...ids]
762
- for (const record of records) {
763
- if (!idSet.has(record.id)) continue
764
- const fromScope = record.scope || 'project'
765
- const fromProject = record.project || null
766
- if (fromScope === targetScope) {
767
- unchanged.push(record.id)
768
- } else {
769
- record.scope = targetScope
770
- record.project = targetScope === 'global' ? null : project
771
- record.migratedAt = new Date().toISOString()
772
- record.migratedFrom = fromScope === 'global' ? 'global' : fromProject || 'project'
773
- if (reason) record.migrateReason = reason
774
- updated.push(record.id)
775
- }
776
- const index = notFound.indexOf(record.id)
777
- if (index >= 0) notFound.splice(index, 1)
778
- }
779
- writeJsonl(memoryPath, records)
780
-
781
- return {
782
- project: project || null,
783
- scope: targetScope,
784
- updated,
785
- updatedCount: updated.length,
786
- unchanged,
787
- notFound,
788
- }
789
- }
790
- function archiveMemory(args = {}) {
791
- const idsInput = Array.isArray(args.ids) ? args.ids : []
792
- const ids = idsInput.map((value) => String(value).trim()).filter(Boolean)
793
- if (ids.length === 0) throw new Error('memory.archive requires ids (array of memory record ids)')
794
- const project = args.project || projectName()
795
- const restore = args.restore === true || args.restore === 'true'
796
- const reason = args.reason ? String(args.reason).trim().slice(0, 200) : null
797
-
798
- const records = readJsonl(memoryPath)
799
- const idSet = new Set(ids)
800
- const archived = []
801
- const notFound = [...ids]
802
- for (const record of records) {
803
- if (!idSet.has(record.id)) continue
804
- if (project && record.project && record.project !== project) continue
805
- if (restore) {
806
- if (record.archived === true) {
807
- delete record.archived
808
- delete record.archivedAt
809
- delete record.archiveReason
810
- archived.push(record.id)
811
- }
812
- } else if (record.archived !== true) {
813
- record.archived = true
814
- record.archivedAt = new Date().toISOString()
815
- if (reason) record.archiveReason = reason
816
- archived.push(record.id)
817
- }
818
- const index = notFound.indexOf(record.id)
819
- if (index >= 0) notFound.splice(index, 1)
820
- }
821
- writeJsonl(memoryPath, records)
822
-
823
- return {
824
- project: project || null,
825
- restored: restore,
826
- archived,
827
- archivedCount: archived.length,
828
- notFound,
829
- }
830
- }
831
-
832
- const FAILURE_OUTCOMES = new Set(['failure', 'error', 'aborted', 'retry'])
833
- const MEMORY_DUPLICATE_SIMILARITY = 0.75
834
- const MEMORY_SHORT_CONTENT_MIN = 20
835
- const MAX_PAIRWISE_MEMORY = 1500
836
-
837
- function isFailureOutcome(value) {
838
- return FAILURE_OUTCOMES.has(String(value || '').toLowerCase())
839
- }
840
-
841
- function summarizeTrace(event) {
842
- const payload = event.payload
843
- if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
844
- if (typeof payload.summary === 'string' && payload.summary.trim()) {
845
- return payload.summary.trim().slice(0, 160)
846
- }
847
- if (typeof payload.tool === 'string' && payload.tool.trim()) {
848
- return `tool: ${payload.tool.trim().slice(0, 120)}`
849
- }
850
- if (typeof payload.error === 'string' && payload.error.trim()) {
851
- return payload.error.trim().slice(0, 160)
852
- }
853
- }
854
- return String(event.event_type || 'trace').slice(0, 120)
855
- }
856
-
857
- function buildPolicyGuidance({ total, failures, risk, failureExamples, relatedMemories }) {
858
- const guidance = {
859
- level: 'none',
860
- rationale: null,
861
- saferAlternatives: [],
862
- verificationSteps: [],
863
- avoid: [],
864
- hardGate: false,
865
- }
866
- if (total === 0) {
867
- guidance.rationale =
868
- 'No historical evidence for this action yet. Treat as normal risk and record the outcome.'
869
- return guidance
870
- }
871
- const verifiedMemories = relatedMemories.filter((record) => record.evidence)
872
- const hasVerified = verifiedMemories.length > 0
873
- if (risk >= 0.4 && failures >= 2) {
874
- guidance.level = hasVerified ? 'actionable' : 'advisory'
875
- guidance.rationale =
876
- 'Repeated historical failures. Prefer an alternative approach and add rollback/verification.'
877
- guidance.avoid = failureExamples
878
- .map((example) => example.summary)
879
- .filter(Boolean)
880
- .slice(0, 3)
881
- } else if (risk >= 0.2 || hasVerified) {
882
- guidance.level = hasVerified ? 'actionable' : 'advisory'
883
- guidance.rationale = hasVerified
884
- ? 'Verified experience exists for this action; apply it before proceeding.'
885
- : 'Moderate historical risk. Add verification before proceeding.'
886
- } else {
887
- guidance.level = 'advisory'
888
- guidance.rationale = 'Low historical risk. Proceed with normal checks and record the outcome.'
889
- }
890
- if (hasVerified) {
891
- guidance.saferAlternatives = verifiedMemories.slice(0, 3).map((record) => ({
892
- memoryId: record.id,
893
- reuseCount: record.evidence.reuseCount,
894
- content: String(record.content || '').slice(0, 300),
895
- }))
896
- }
897
- guidance.verificationSteps = [
898
- 'Add an explicit verification step after execution (dry-run, rollback plan, or assertion).',
899
- 'Record the outcome with mio.observer.ingest so the evidence base improves.',
900
- ]
901
- return guidance
902
- }
903
-
904
- function policyCheck(args = {}) {
905
- const action = String(args.action || '').trim()
906
- if (!action) throw new Error('policy.check requires action')
907
- const project = args.project || projectName()
908
- const actionTokens = tokenize(action)
909
- const traces = readJsonl(tracePath).filter((event) => {
910
- if (project && event.project && event.project !== project) return false
911
- const haystack = tokenize(
912
- `${event.event_type || ''} ${JSON.stringify(event.payload || {})}`
913
- )
914
- return actionTokens.some((token) => haystack.includes(token))
915
- })
916
- const total = traces.length
917
- const failures = traces.filter((event) => isFailureOutcome(event.outcome)).length
918
- const risk = total > 0 ? failures / total : null
919
- const riskLevel = total === 0 ? 'unknown' : risk >= 0.4 ? 'high' : risk >= 0.2 ? 'moderate' : 'low'
920
- const outcomeCounts = traces.reduce((counts, event) => {
921
- const outcome = String(event.outcome || 'unknown').toLowerCase() || 'unknown'
922
- counts[outcome] = (counts[outcome] || 0) + 1
923
- return counts
924
- }, {})
925
- const failureExamples = traces
926
- .filter((event) => isFailureOutcome(event.outcome))
927
- .sort((a, b) => new Date(b.timestamp || 0).getTime() - new Date(a.timestamp || 0).getTime())
928
- .slice(0, 3)
929
- .map((event) => ({
930
- trace_id: event.trace_id || event.id || null,
931
- event_type: event.event_type || null,
932
- outcome: event.outcome || null,
933
- timestamp: event.timestamp || null,
934
- agent: event.agent || null,
935
- summary: summarizeTrace(event),
936
- }))
937
- let suggestion
938
- if (total === 0) {
939
- suggestion = 'No history for this action. Treat as normal risk and record the outcome.'
940
- } else if (risk >= 0.4) {
941
- suggestion = 'Historically risky. Prefer an alternative approach or add rollback/verification.'
942
- } else if (risk >= 0.2) {
943
- suggestion = 'Moderate risk. Add verification before proceeding.'
944
- } else {
945
- suggestion = 'Low historical risk. Proceed with normal checks.'
946
- }
947
- const evidence = loadEvidenceWeights()
948
- const relatedMemories = readJsonl(memoryPath)
949
- .filter((record) => scoreRecord(record, action, project, evidence) > 0)
950
- .sort((a, b) => scoreRecord(b, action, project, evidence) - scoreRecord(a, action, project, evidence))
951
- .slice(0, 3)
952
- .map((record) => {
953
- const ev = evidence.get(record.id)
954
- return {
955
- id: record.id,
956
- timestamp: record.timestamp,
957
- kind: record.kind,
958
- content: record.content,
959
- tags: record.tags,
960
- evidence: ev
961
- ? { reuseCount: ev.reuseCount, confirmedCount: ev.confirmedCount }
962
- : null,
963
- }
964
- })
965
- return {
966
- action,
967
- project,
968
- total,
969
- failures,
970
- risk: risk === null ? null : Number(risk.toFixed(3)),
971
- riskLevel,
972
- outcomeCounts,
973
- failureExamples,
974
- suggestion,
975
- guidance: buildPolicyGuidance({
976
- total,
977
- failures,
978
- risk,
979
- failureExamples,
980
- relatedMemories,
981
- }),
982
- related_memories: relatedMemories,
983
- }
984
- }
985
-
986
- function recordExperienceReuse(args = {}) {
987
- const sourceAgent = String(args.sourceAgent || '').trim()
988
- const targetAgent = String(args.targetAgent || '').trim()
989
- const experienceId = String(args.experienceId || '').trim()
990
- if (!sourceAgent) throw new Error('experience.reuse requires sourceAgent')
991
- if (!targetAgent) throw new Error('experience.reuse requires targetAgent')
992
- if (!experienceId) throw new Error('experience.reuse requires experienceId')
993
-
994
- const project = args.project || projectName()
995
- const evidence = {
996
- id: createId('xfer'),
997
- timestamp: new Date().toISOString(),
998
- sourceAgent,
999
- targetAgent,
1000
- experienceId,
1001
- reuse: args.reuse === true || args.reuse === 'true',
1002
- behaviorChanged: args.behaviorChanged === true || args.behaviorChanged === 'true',
1003
- outcomeImproved: args.outcomeImproved === true || args.outcomeImproved === 'true',
1004
- project,
1005
- source: args.source || 'agent_report',
1006
- notes: args.notes || null,
1007
- }
1008
- appendJsonl(experienceReusePath, evidence)
1009
-
1010
- const report = loadPhase0(dataDir, project)
1011
- return {
1012
- recorded: true,
1013
- evidence,
1014
- phase0: summarizePhase0(report),
1015
- }
1016
- }
1017
-
1018
- function confirmExperienceReuse(args = {}) {
1019
- const id = String(args.id || '').trim()
1020
- if (!id) throw new Error('experience.confirm requires id of an auto-claimed reuse record')
1021
- const records = readJsonl(experienceReusePath)
1022
- const index = records.findIndex((record) => record && record.id === id)
1023
- if (index < 0) {
1024
- throw new Error(`No experience reuse record found with id ${id}`)
1025
- }
1026
- const record = records[index]
1027
- if (record.source !== 'auto_claim') {
1028
- throw new Error('experience.confirm only applies to source=auto_claim reuse records')
1029
- }
1030
- const outcomeImproved =
1031
- args.outcomeImproved === undefined || args.outcomeImproved === null
1032
- ? record.outcomeImproved === true
1033
- : args.outcomeImproved === true || args.outcomeImproved === 'true'
1034
- const updated = {
1035
- ...record,
1036
- behaviorChanged: true,
1037
- outcomeImproved,
1038
- confirmed: true,
1039
- confirmedAt: new Date().toISOString(),
1040
- confirmedBy: String(args.confirmedBy || 'agent').trim() || 'agent',
1041
- notes: args.notes ? String(args.notes).trim() : record.notes || null,
1042
- }
1043
- records[index] = updated
1044
- writeJsonl(experienceReusePath, records)
1045
-
1046
- const report = loadPhase0(dataDir, updated.project)
1047
- return {
1048
- confirmed: true,
1049
- evidence: updated,
1050
- phase0: summarizePhase0(report),
1051
- }
1052
- }
1053
-
1054
- const REUSE_STATUS_FILTERS = Object.freeze({
1055
- pending: (record) => record.source === 'auto_claim' && record.confirmed !== true,
1056
- confirmed: (record) => record.confirmed === true,
1057
- verified: (record) =>
1058
- (record.reuse === true || record.reuse === 'true') &&
1059
- (record.behaviorChanged === true || record.behaviorChanged === 'true') &&
1060
- (record.outcomeImproved === true || record.outcomeImproved === 'true'),
1061
- auto_claim: (record) => record.source === 'auto_claim',
1062
- agent_report: (record) => record.source !== 'auto_claim',
1063
- })
1064
-
1065
- function loadEvidenceWeights() {
1066
- const weights = new Map()
1067
- for (const record of readJsonl(experienceReusePath)) {
1068
- if (!REUSE_STATUS_FILTERS.verified(record)) continue
1069
- const id = record.experienceId
1070
- if (!id) continue
1071
- let entry = weights.get(id)
1072
- if (!entry) {
1073
- entry = { reuseCount: 0, confirmedCount: 0, lastReusedAt: null }
1074
- weights.set(id, entry)
1075
- }
1076
- entry.reuseCount += 1
1077
- if (record.confirmed === true) entry.confirmedCount += 1
1078
- if (!entry.lastReusedAt || new Date(record.timestamp || 0) > new Date(entry.lastReusedAt)) {
1079
- entry.lastReusedAt = record.timestamp || null
1080
- }
1081
- }
1082
- return weights
1083
- }
1084
-
1085
- function listExperienceReuse(args = {}) {
1086
- const project = args.project || projectName()
1087
- const status = String(args.status || 'all').trim().toLowerCase()
1088
- const targetAgent = String(args.targetAgent || '').trim().toLowerCase()
1089
- const limit = Math.min(Math.max(Number(args.limit) || 20, 1), 100)
1090
-
1091
- let records = readJsonl(experienceReusePath)
1092
- if (project) records = records.filter((record) => record.project === project)
1093
- if (targetAgent) {
1094
- records = records.filter(
1095
- (record) => String(record.targetAgent || '').toLowerCase() === targetAgent,
1096
- )
1097
- }
1098
- const matcher = REUSE_STATUS_FILTERS[status]
1099
- if (matcher) records = records.filter(matcher)
1100
- records.sort((a, b) => {
1101
- const at = new Date(a.timestamp || 0).getTime()
1102
- const bt = new Date(b.timestamp || 0).getTime()
1103
- return bt - at
1104
- })
1105
-
1106
- const visible = records.slice(0, limit).map((record) => ({
1107
- id: record.id,
1108
- source: record.source,
1109
- sourceAgent: record.sourceAgent,
1110
- targetAgent: record.targetAgent,
1111
- experienceId: record.experienceId,
1112
- reuse: record.reuse === true || record.reuse === 'true',
1113
- behaviorChanged: record.behaviorChanged === true || record.behaviorChanged === 'true',
1114
- outcomeImproved: record.outcomeImproved === true || record.outcomeImproved === 'true',
1115
- confirmed: record.confirmed === true,
1116
- confirmedBy: record.confirmedBy || null,
1117
- traceId: record.traceId || null,
1118
- timestamp: record.timestamp,
1119
- project: record.project,
1120
- notes:
1121
- typeof record.notes === 'string' && record.notes ? record.notes.slice(0, 300) : null,
1122
- }))
1123
-
1124
- return {
1125
- project: project || null,
1126
- status,
1127
- count: visible.length,
1128
- total: records.length,
1129
- records: visible,
1130
- }
1131
- }
1132
-
1133
- function registerAgent(args = {}) {
1134
- const agentId = String(args.agentId || '').trim()
1135
- if (!agentId) throw new Error('agent.register requires a non-empty agentId')
1136
- const project = args.project || projectName()
1137
- const hostType = args.hostType || 'mcp'
1138
- const capabilities = Array.isArray(args.capabilities) ? args.capabilities : []
1139
- const now = new Date().toISOString()
1140
- const agents = readJsonl(agentsPath)
1141
- const existing = agents.find((a) => a.agentId === agentId && a.project === project)
1142
- let result
1143
- if (existing) {
1144
- existing.lastSeenAt = now
1145
- existing.sessionCount = (existing.sessionCount || 1) + 1
1146
- existing.hostType = hostType
1147
- if (capabilities.length > 0) existing.capabilities = capabilities
1148
- result = existing
1149
- } else {
1150
- result = {
1151
- id: createId('agent'),
1152
- agentId,
1153
- hostType,
1154
- capabilities,
1155
- registeredAt: now,
1156
- lastSeenAt: now,
1157
- sessionCount: 1,
1158
- project,
1159
- }
1160
- agents.push(result)
1161
- }
1162
- writeJsonl(agentsPath, agents)
1163
- return { id: result.id, agentId: result.agentId, registered: !existing, sessionCount: result.sessionCount, hostType: result.hostType, capabilities: result.capabilities }
1164
- }
1165
-
1166
- function listAgents(args = {}) {
1167
- const project = args.project || null
1168
- let agents = readJsonl(agentsPath)
1169
- if (project) agents = agents.filter((a) => a.project === project)
1170
- return {
1171
- count: agents.length,
1172
- agents: agents.map((a) => ({
1173
- id: a.id, agentId: a.agentId, hostType: a.hostType,
1174
- capabilities: a.capabilities, registeredAt: a.registeredAt,
1175
- lastSeenAt: a.lastSeenAt, sessionCount: a.sessionCount,
1176
- taskCount: a.taskCount || 0, successCount: a.successCount || 0, failureCount: a.failureCount || 0,
1177
- project: a.project,
1178
- })),
1179
- }
1180
- }
1181
-
1182
- function reportAgent(args = {}) {
1183
- const targetAgent = args.agentId || null
1184
- const project = args.project || projectName()
1185
- const agents = readJsonl(agentsPath)
1186
- const filtered = agents.filter((a) =>
1187
- (!targetAgent || a.agentId === targetAgent) && (!project || a.project === project)
1188
- )
1189
- const traces = readJsonl(tracePath)
1190
- const memories = readJsonl(memoryPath)
1191
- const reuses = readJsonl(experienceReusePath)
1192
- const reports = filtered.map((agent) => {
1193
- const agentTraces = traces.filter((t) => t.agent === agent.agentId)
1194
- const outcomes = agentTraces.filter((t) => t.event_type === 'task_outcome')
1195
- const successes = outcomes.filter((t) => t.outcome === 'success').length
1196
- const failures = outcomes.filter((t) => t.outcome === 'failure').length
1197
- const agentMemories = memories.filter((m) => m.source === agent.agentId)
1198
- const agentReuses = reuses.filter((r) => r.sourceAgent === agent.agentId || r.targetAgent === agent.agentId)
1199
- const verified = agentReuses.filter((r) => r.confirmed && r.reuse && r.behaviorChanged && r.outcomeImproved)
1200
- const regTasks = agent.taskCount || 0
1201
- const regSuccess = agent.successCount || 0
1202
- const regFail = agent.failureCount || 0
1203
- const taskTotal = regTasks > 0 ? regTasks : outcomes.length
1204
- const taskSuccess = regTasks > 0 ? regSuccess : successes
1205
- const taskFail = regTasks > 0 ? regFail : failures
1206
- return {
1207
- agentId: agent.agentId,
1208
- hostType: agent.hostType,
1209
- sessionCount: agent.sessionCount,
1210
- registeredAt: agent.registeredAt,
1211
- lastSeenAt: agent.lastSeenAt,
1212
- taskOutcomes: { total: taskTotal, success: taskSuccess, failure: taskFail, successRate: taskTotal > 0 ? Math.round((taskSuccess / taskTotal) * 100) : 0 },
1213
- memories: agentMemories.length,
1214
- experienceReuses: { total: agentReuses.length, verified: verified.length },
1215
- active: (Date.now() - new Date(agent.lastSeenAt).getTime()) < 24 * 60 * 60 * 1000,
1216
- }
1217
- })
1218
- return { project, count: reports.length, reports }
1219
- }
1220
-
1221
- function routeTask(args = {}) {
1222
- const task = String(args.task || '').trim()
1223
- if (!task) throw new Error('task.route requires a non-empty task')
1224
- const project = args.project || projectName()
1225
- const scope = normalizeScope(args.scope)
1226
- const limit = Math.min(Math.max(Number(args.limit) || 5, 1), 10)
1227
-
1228
- const memories = readJsonl(memoryPath).filter((record) => record.archived !== true)
1229
- const memoryById = new Map(memories.map((record) => [record.id, record]))
1230
- const evidence = loadEvidenceWeights()
1231
-
1232
- // Match verified reuse experiences whose source memory is relevant to the task.
1233
- const routeByMemory = new Map()
1234
- for (const record of readJsonl(experienceReusePath)) {
1235
- if (!REUSE_STATUS_FILTERS.verified(record)) continue
1236
- const memory = memoryById.get(record.experienceId)
1237
- if (!memory || !matchesProjectScope(memory, project, scope)) continue
1238
- const score = scoreRecord(memory, task, project)
1239
- if (score <= 0) continue
1240
- let entry = routeByMemory.get(record.experienceId)
1241
- if (!entry) {
1242
- entry = {
1243
- experienceId: record.experienceId,
1244
- memory,
1245
- weight: 0,
1246
- confirmed: false,
1247
- sourceAgents: new Set(),
1248
- targetAgents: new Set(),
1249
- reuseCount: 0,
1250
- }
1251
- routeByMemory.set(record.experienceId, entry)
1252
- }
1253
- entry.reuseCount += 1
1254
- if (record.confirmed === true) entry.confirmed = true
1255
- if (record.sourceAgent) entry.sourceAgents.add(record.sourceAgent)
1256
- if (record.targetAgent) entry.targetAgents.add(record.targetAgent)
1257
- entry.weight = Math.max(entry.weight, score + (entry.confirmed ? 2 : 1.5))
1258
- }
1259
-
1260
- const routes = [...routeByMemory.values()]
1261
- .sort((a, b) => b.weight - a.weight)
1262
- .slice(0, limit)
1263
- .map((entry) => ({
1264
- experienceId: entry.experienceId,
1265
- reuseCount: entry.reuseCount,
1266
- confirmed: entry.confirmed,
1267
- sourceAgents: [...entry.sourceAgents].filter(Boolean),
1268
- targetAgents: [...entry.targetAgents].filter(Boolean),
1269
- score: Number(entry.weight.toFixed(2)),
1270
- memory: {
1271
- id: entry.memory.id,
1272
- timestamp: entry.memory.timestamp,
1273
- kind: entry.memory.kind,
1274
- content: entry.memory.content,
1275
- tags: entry.memory.tags || [],
1276
- project: entry.memory.project || null,
1277
- scope: entry.memory.scope || 'project',
1278
- },
1279
- }))
1280
-
1281
- // Broader context: top related memories not already routed.
1282
- const routedIds = new Set(routes.map((route) => route.experienceId))
1283
- const scoreRelated = (record) =>
1284
- scoreRecord(record, task, project, evidence) +
1285
- (scope === 'all' && isGlobalRecord(record) ? 0.5 : 0)
1286
- const relatedMemories = memories
1287
- .filter((record) => !routedIds.has(record.id))
1288
- .filter((record) => matchesProjectScope(record, project, scope))
1289
- .filter((record) => scoreRelated(record) > 0)
1290
- .sort((a, b) => scoreRelated(b) - scoreRelated(a))
1291
- .slice(0, Math.max(limit, 5))
1292
- .map((record) => {
1293
- const ev = evidence.get(record.id)
1294
- return {
1295
- id: record.id,
1296
- timestamp: record.timestamp,
1297
- kind: record.kind,
1298
- content: record.content,
1299
- tags: record.tags || [],
1300
- project: record.project || null,
1301
- scope: record.scope || 'project',
1302
- evidence: ev
1303
- ? { reuseCount: ev.reuseCount, confirmedCount: ev.confirmedCount }
1304
- : null,
1305
- }
1306
- })
1307
-
1308
- // Feed the query log so a later task_outcome can auto-claim route-driven reuse.
1309
- if (routes.length > 0 || relatedMemories.length > 0) {
1310
- const now = Date.now()
1311
- const entries = loadRecentQueries()
1312
- entries.push({
1313
- agent: runtimeAgentId() || 'mcp',
1314
- project,
1315
- query: task,
1316
- resultIds: [...routedIds, ...relatedMemories.map((record) => record.id)].filter(Boolean),
1317
- resultSources: [...routes.map(() => 'experience'), ...relatedMemories.map((record) => record.source || null)],
1318
- timestamp: now,
1319
- expiresAt: now + REUSE_MATCH_WINDOW_MS,
1320
- })
1321
- persistRecentQueries(entries)
1322
- }
1323
-
1324
- let suggestion
1325
- if (routes.length > 0) {
1326
- suggestion =
1327
- `Route ${routes.length} verified experience(s) to this task; apply the top match first and record the outcome with mio.observer.ingest / mio.experience.reuse.`
1328
- } else if (relatedMemories.length > 0) {
1329
- suggestion =
1330
- 'No verified experience matches yet. Consult the related memories, then record the outcome so this task can seed future routes.'
1331
- } else {
1332
- suggestion =
1333
- 'No matching experience or memory found. Proceed with care and record the outcome to grow the experience base.'
1334
- }
1335
-
1336
- return {
1337
- task,
1338
- project,
1339
- scope,
1340
- count: routes.length,
1341
- routes,
1342
- relatedMemories,
1343
- summary: {
1344
- verifiedRoutes: routes.length,
1345
- relatedMemories: relatedMemories.length,
1346
- suggestion,
1347
- },
1348
- }
1349
- }
1350
- function phase0Report(args = {}) {
1351
- const project = args.project || projectName()
1352
- const report = loadPhase0(dataDir, project)
1353
- const format = String(args.format || 'json').trim().toLowerCase()
1354
- if (format === 'markdown') {
1355
- return {
1356
- project,
1357
- format: 'markdown',
1358
- markdown: renderPhase0Markdown(report),
1359
- }
1360
- }
1361
- return {
1362
- project,
1363
- ...report,
1364
- }
1365
- }
1366
-
1367
- const TOOLS = [
1368
- {
1369
- name: 'mio.memory.query',
1370
- description: 'Search local Mio project memory for context, decisions, and historical problems.',
1371
- inputSchema: {
1372
- type: 'object',
1373
- properties: {
1374
- query: { type: 'string', description: 'Question or topic to recall.' },
1375
- project: { type: 'string', description: 'Project name filter. Defaults to current directory name.' },
1376
- limit: { type: 'number', description: 'Maximum results, between 1 and 20. Defaults to 5.' },
1377
- kind: { type: 'string', description: 'Only return records with this kind (decision, context, problem, note).' },
1378
- tags: { type: 'array', items: { type: 'string' }, description: 'Only return records containing all of these tags (AND).' },
1379
- scope: { type: 'string', description: 'Search scope: project (default), global, or all.' },
1380
- },
1381
- required: ['query'],
1382
- },
1383
- },
1384
- {
1385
- name: 'mio.memory.archive',
1386
- description: 'Archive (or restore) memory records by id. Archived records are excluded from memory.query and memory.analyze.',
1387
- inputSchema: {
1388
- type: 'object',
1389
- properties: {
1390
- ids: { type: 'array', items: { type: 'string' }, description: 'Memory record ids to archive or restore.' },
1391
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1392
- restore: { type: 'boolean', description: 'When true, un-archive the given ids instead.' },
1393
- reason: { type: 'string', description: 'Optional archive reason.' },
1394
- },
1395
- required: ['ids'],
1396
- },
1397
- },
1398
- {
1399
- name: 'mio.memory.migrate',
1400
- description: 'Migrate memory records between project and global layers (P3). Moving to global makes the record reusable across projects (project set to null); moving to project restores project scoping.',
1401
- inputSchema: {
1402
- type: 'object',
1403
- properties: {
1404
- ids: { type: 'array', items: { type: 'string' }, description: 'Memory record ids to migrate.' },
1405
- scope: { type: 'string', description: 'Target layer: global or project.' },
1406
- project: { type: 'string', description: 'Target project for project scope. Defaults to current repository.' },
1407
- reason: { type: 'string', description: 'Optional migration reason.' },
1408
- },
1409
- required: ['ids', 'scope'],
1410
- },
1411
- },
1412
- {
1413
- name: 'mio.memory.record',
1414
- description: 'Record a decision, project context, or historical problem into local Mio memory.',
1415
- inputSchema: {
1416
- type: 'object',
1417
- properties: {
1418
- content: { type: 'string', description: 'Memory content.' },
1419
- kind: { type: 'string', description: 'Memory kind, such as decision, context, or problem.' },
1420
- tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags.' },
1421
- project: { type: 'string', description: 'Project name. Defaults to current directory name.' },
1422
- scope: { type: 'string', description: 'Record scope: project (default) or global.' },
1423
- source: { type: 'string', description: 'Recording source. Defaults to mcp.' },
1424
- },
1425
- required: ['content'],
1426
- },
1427
- },
1428
- {
1429
- name: 'mio.observer.ingest',
1430
- description: 'Ingest an Agent Trace event such as tool_call, error, retry, or task_outcome.',
1431
- inputSchema: {
1432
- type: 'object',
1433
- properties: {
1434
- trace_id: { type: 'string', description: 'Stable trace identifier.' },
1435
- event_type: { type: 'string', description: 'Event type, such as tool_call, error, retry, task_outcome.' },
1436
- payload: { type: 'object', description: 'Event payload.' },
1437
- outcome: { type: 'string', description: 'Optional outcome: success, failure, error, aborted, retry.' },
1438
- agent: { type: 'string', description: 'Agent identifier.' },
1439
- host: { type: 'string', description: 'Host name. Defaults to mcp.' },
1440
- project: { type: 'string', description: 'Project name. Defaults to current directory name.' },
1441
- },
1442
- required: ['trace_id', 'event_type'],
1443
- },
1444
- },
1445
- {
1446
- name: 'mio.observer.subscribe',
1447
- description: 'Subscribe to observer events (project, event types, optional topic). New matching events are delivered via mio.observer.digest.',
1448
- inputSchema: {
1449
- type: 'object',
1450
- properties: {
1451
- eventTypes: { type: 'array', items: { type: 'string' }, description: 'Event types to watch, e.g. error, retry, task_outcome. Empty means all.' },
1452
- project: { type: 'string', description: 'Project name. Defaults to current repository.' },
1453
- topic: { type: 'string', description: 'Optional keyword; only events whose payload mentions it match.' },
1454
- ttlDays: { type: 'number', description: 'Subscription lifetime in days. Defaults to 30.' },
1455
- },
1456
- },
1457
- },
1458
- {
1459
- name: 'mio.observer.digest',
1460
- description: 'Return new observer events matching active subscriptions since the last digest, and advance the cursor.',
1461
- inputSchema: {
1462
- type: 'object',
1463
- properties: {
1464
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1465
- eventTypes: { type: 'array', items: { type: 'string' }, description: 'Optional extra event type filter.' },
1466
- limit: { type: 'number', description: 'Maximum events to return, 1-100. Defaults to 20.' },
1467
- },
1468
- },
1469
- },
1470
- {
1471
- name: 'mio.policy.check',
1472
- description: 'Check historical risk for an action before executing it, returning risk level, outcome counts, and recent failure examples.',
1473
- inputSchema: {
1474
- type: 'object',
1475
- properties: {
1476
- action: { type: 'string', description: 'The action or tool operation to check.' },
1477
- project: { type: 'string', description: 'Project name filter. Defaults to current directory name.' },
1478
- context: { type: 'string', description: 'Optional additional context.' },
1479
- },
1480
- required: ['action'],
1481
- },
1482
- },
1483
- {
1484
- name: 'mio.memory.analyze',
1485
- description: 'Analyze local Mio memory quality: kind distribution, duplicate groups, and low-quality records.',
1486
- inputSchema: {
1487
- type: 'object',
1488
- properties: {
1489
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1490
- limit: { type: 'number', description: 'Maximum duplicates/low-quality examples to return, 1-20. Defaults to 5.' },
1491
- },
1492
- },
1493
- },
1494
- {
1495
- name: 'mio.experience.reuse',
1496
- description: 'Record Phase 0 evidence of cross-agent experience reuse.',
1497
- inputSchema: {
1498
- type: 'object',
1499
- properties: {
1500
- sourceAgent: { type: 'string', description: 'Agent that produced the experience.' },
1501
- targetAgent: { type: 'string', description: 'Agent that reused the experience.' },
1502
- experienceId: { type: 'string', description: 'Stable experience or memory id.' },
1503
- reuse: { type: 'boolean', description: 'True when memory.query returned historical experience and it was reused.' },
1504
- behaviorChanged: { type: 'boolean', description: 'True when target Agent behavior changed because of the reused experience.' },
1505
- outcomeImproved: { type: 'boolean', description: 'True when the task outcome improved.' },
1506
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1507
- notes: { type: 'string', description: 'Optional evidence notes.' },
1508
- },
1509
- required: ['sourceAgent', 'targetAgent', 'experienceId', 'reuse', 'behaviorChanged', 'outcomeImproved'],
1510
- },
1511
- },
1512
- {
1513
- name: 'mio.experience.confirm',
1514
- description: 'Confirm an auto-claimed reuse record as verified reuse evidence.',
1515
- inputSchema: {
1516
- type: 'object',
1517
- properties: {
1518
- id: { type: 'string', description: 'Id of the auto-claimed reuse record returned by mio.observer.ingest.' },
1519
- confirmedBy: { type: 'string', description: 'Who confirmed the reuse: agent or human. Defaults to agent.' },
1520
- outcomeImproved: { type: 'boolean', description: 'Override: true when the reused experience improved the task outcome. Defaults to the auto-claim value.' },
1521
- notes: { type: 'string', description: 'Optional confirmation notes.' },
1522
- },
1523
- required: ['id'],
1524
- },
1525
- },
1526
- {
1527
- name: 'mio.experience.list',
1528
- description: 'List Phase 0 experience reuse evidence, optionally filtered by status or target agent.',
1529
- inputSchema: {
1530
- type: 'object',
1531
- properties: {
1532
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1533
- status: { type: 'string', description: 'Filter: pending (auto-claim awaiting confirmation), confirmed, verified, auto_claim, agent_report, all. Defaults to all.' },
1534
- targetAgent: { type: 'string', description: 'Filter records by target agent.' },
1535
- limit: { type: 'number', description: 'Maximum records to return, 1-100. Defaults to 20.' },
1536
- },
1537
- },
1538
- },
1539
- {
1540
- name: 'mio.phase0.report',
1541
- description: 'Generate the current Phase 0 cross-agent validation report, as JSON or rendered Markdown.',
1542
- inputSchema: {
1543
- type: 'object',
1544
- properties: {
1545
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1546
- format: { type: 'string', description: 'Output format: json or markdown. Defaults to json.' },
1547
- },
1548
- },
1549
- },
1550
- {
1551
- name: 'mio.task.route',
1552
- description: 'Route an incoming task to the most relevant verified experiences and related memories, turning recall into decision influence (P1).',
1553
- inputSchema: {
1554
- type: 'object',
1555
- properties: {
1556
- task: { type: 'string', description: 'Task description to route, e.g. \'fix IPC communication bug\'.' },
1557
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1558
- scope: { type: 'string', description: 'Search scope: project (default), global, or all.' },
1559
- limit: { type: 'number', description: 'Maximum routes, between 1 and 10. Defaults to 5.' },
1560
- },
1561
- required: ['task'],
1562
- },
1563
- },
1564
- {
1565
- name: 'mio.agent.register',
1566
- description: 'Register or update an agent in the Mio Agent Registry. Upserts by agentId+project; updates lastSeenAt and sessionCount.',
1567
- inputSchema: {
1568
- type: 'object',
1569
- properties: {
1570
- agentId: { type: 'string', description: 'Unique agent identifier (e.g. codex, opencode).' },
1571
- hostType: { type: 'string', description: 'Host type: mcp, observer, or plugin. Defaults to mcp.' },
1572
- capabilities: { type: 'array', items: { type: 'string' }, description: 'Agent capabilities.' },
1573
- project: { type: 'string', description: 'Project name. Defaults to current directory name.' },
1574
- },
1575
- required: ['agentId'],
1576
- },
1577
- },
1578
- {
1579
- name: 'mio.agent.list',
1580
- description: 'List all registered agents, optionally filtered by project.',
1581
- inputSchema: {
1582
- type: 'object',
1583
- properties: {
1584
- project: { type: 'string', description: 'Project name filter. Omit for all agents.' },
1585
- },
1586
- },
1587
- },
1588
- {
1589
- name: 'mio.agent.report',
1590
- description: 'Performance report for one or all agents, aggregating task outcomes, memory, and experience reuse.',
1591
- inputSchema: {
1592
- type: 'object',
1593
- properties: {
1594
- agentId: { type: 'string', description: 'Agent to report on. Omit for all agents.' },
1595
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1596
- },
1597
- },
1598
- },
97
+ const creativityEngine = new CreativityEngine(path.join(dataDir, 'creativity'), chatJson)
98
+ const insightStore = InsightStore ? new InsightStore(path.join(dataDir, 'insights', 'insights.json')) : null
99
+
100
+ let runtimeContext = {}
101
+ try {
102
+ const rawContext = process.env.MIO_CONTEXT
103
+ if (rawContext) {
104
+ const parsed = JSON.parse(rawContext)
105
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
106
+ runtimeContext = parsed
107
+ }
108
+ }
109
+ } catch (_) {
110
+ runtimeContext = {}
111
+ }
112
+
113
+ function runtimeAgentId() {
114
+ return runtimeContext.agentId || null
115
+ }
116
+
117
+ // Phase 0 auto-claim: match memory.query results with a later task_outcome
118
+ // from the same agent+project, so reuse evidence does not depend on the
119
+ // agent self-reporting mio.experience.reuse.
120
+ const REUSE_MATCH_WINDOW_MS = (() => {
121
+ const minutes = Number(process.env.MIO_REUSE_MATCH_WINDOW_MIN)
122
+ return Number.isFinite(minutes) && minutes > 0 ? minutes * 60 * 1000 : 60 * 60 * 1000
123
+ })()
124
+ const MAX_RECENT_QUERIES = 200
125
+ let recentQueries = []
126
+
127
+ function loadRecentQueries() {
128
+ const now = Date.now()
129
+ const entries = readJsonl(queryPath)
130
+ .filter(
131
+ (entry) =>
132
+ entry &&
133
+ typeof entry.agent === 'string' &&
134
+ entry.agent &&
135
+ typeof entry.expiresAt === 'number' &&
136
+ entry.expiresAt > now
137
+ )
138
+ .slice(-MAX_RECENT_QUERIES)
139
+ recentQueries = entries
140
+ return entries
141
+ }
142
+
143
+ function persistRecentQueries(entries) {
144
+ const limited = entries.slice(-MAX_RECENT_QUERIES)
145
+ fs.mkdirSync(dataDir, { recursive: true })
146
+ fs.writeFileSync(
147
+ queryPath,
148
+ limited.length > 0 ? limited.map((entry) => JSON.stringify(entry)).join('\n') + '\n' : '',
149
+ 'utf8'
150
+ )
151
+ recentQueries = limited
152
+ return limited
153
+ }
154
+
155
+ function createId(prefix) {
156
+ return `${prefix}_${Date.now()}_${crypto.randomBytes(6).toString('hex')}`
157
+ }
158
+
159
+ function appendJsonl(file, value) {
160
+ fs.appendFileSync(file, `${JSON.stringify(value)}\n`, 'utf8')
161
+ }
162
+
163
+ function writeJsonl(file, values) {
164
+ fs.mkdirSync(path.dirname(file), { recursive: true })
165
+ fs.writeFileSync(
166
+ file,
167
+ values.length > 0 ? values.map((value) => JSON.stringify(value)).join('\n') + '\n' : '',
168
+ 'utf8'
169
+ )
170
+ }
171
+
172
+ function readJsonl(file) {
173
+ if (!fs.existsSync(file)) return []
174
+ return fs
175
+ .readFileSync(file, 'utf8')
176
+ .split(/\r?\n/)
177
+ .filter(Boolean)
178
+ .map((line) => {
179
+ try {
180
+ return JSON.parse(line)
181
+ } catch (_) {
182
+ return null
183
+ }
184
+ })
185
+ .filter(Boolean)
186
+ }
187
+
188
+ let lastProjectCwd = null
189
+ let lastProjectName = null
190
+
191
+ function projectName() {
192
+ const currentCwd = process.cwd()
193
+ if (lastProjectCwd === currentCwd && lastProjectName) {
194
+ return lastProjectName
195
+ }
196
+ lastProjectCwd = currentCwd
197
+ if (runtimeContext.project) {
198
+ lastProjectName = runtimeContext.project
199
+ return lastProjectName
200
+ }
201
+ try {
202
+ const commonDir = execFileSync(
203
+ 'git',
204
+ ['rev-parse', '--path-format=absolute', '--git-common-dir'],
205
+ {
206
+ cwd: currentCwd,
207
+ encoding: 'utf8',
208
+ stdio: ['ignore', 'pipe', 'ignore'],
209
+ }
210
+ ).trim()
211
+ if (commonDir) {
212
+ const repoRoot = path.dirname(commonDir)
213
+ const name = path.basename(repoRoot)
214
+ if (name) {
215
+ lastProjectName = name
216
+ return lastProjectName
217
+ }
218
+ }
219
+ } catch (_) {
220
+ // fall through to cwd basename
221
+ }
222
+ lastProjectName = path.basename(currentCwd)
223
+ return lastProjectName
224
+ }
225
+
226
+ // Memory store: shared implementation with the CLI (`mio recall`/`mio remember`).
227
+ // The pure scoring/filter helpers and queryMemory/recordMemory live in
228
+ // server/memory-store.js so both entry points rank and persist identically.
229
+ const REUSE_STATUS_FILTERS = Object.freeze({
230
+ pending: (record) => record.source === 'auto_claim' && record.confirmed !== true,
231
+ confirmed: (record) => record.confirmed === true,
232
+ verified: (record) =>
233
+ (record.reuse === true || record.reuse === 'true') &&
234
+ (record.behaviorChanged === true || record.behaviorChanged === 'true') &&
235
+ (record.outcomeImproved === true || record.outcomeImproved === 'true'),
236
+ auto_claim: (record) => record.source === 'auto_claim',
237
+ agent_report: (record) => record.source !== 'auto_claim',
238
+ })
239
+
240
+ const memoryStore = createMemoryStore({
241
+ dataDir,
242
+ projectName,
243
+ agentId: runtimeAgentId,
244
+ reuseMatchWindowMs: REUSE_MATCH_WINDOW_MS,
245
+ verifiedFilter: REUSE_STATUS_FILTERS.verified,
246
+ recordQuery(entry) {
247
+ const entries = loadRecentQueries()
248
+ entries.push(entry)
249
+ persistRecentQueries(entries)
250
+ },
251
+ })
252
+
253
+ const digestEngine = createDigest({ home: dataDir })
254
+
255
+ const {
256
+ normalizeTags,
257
+ tokenize,
258
+ normalizeScope,
259
+ isGlobalRecord,
260
+ matchesProjectScope,
261
+ latinTokens,
262
+ cjkBigrams,
263
+ scoreRecord,
264
+ matchesMemoryFilters,
265
+ queryMemory,
266
+ recordMemory,
267
+ queryTraces,
268
+ loadEvidenceWeights,
269
+ } = memoryStore
270
+
271
+ function ingestObservation(args = {}) {
272
+ const traceId = String(args.trace_id || '').trim()
273
+ const eventType = String(args.event_type || '').trim()
274
+ if (!traceId) throw new Error('observer.ingest requires trace_id')
275
+ if (!eventType) throw new Error('observer.ingest requires event_type')
276
+ const event = {
277
+ id: createId('trace'),
278
+ timestamp: new Date().toISOString(),
279
+ trace_id: traceId,
280
+ event_type: eventType,
281
+ outcome: args.outcome || null,
282
+ payload: args.payload || {},
283
+ agent: args.agent || runtimeAgentId(),
284
+ host: args.host || 'mcp',
285
+ project: args.project || projectName(),
286
+ }
287
+ appendJsonl(tracePath, event)
288
+ const autoClaims = autoClaimExperienceReuse(event)
289
+ if (autoClaims.length > 0) {
290
+ return { recorded: true, event, autoClaims }
291
+ }
292
+ return { recorded: true, event }
293
+ }
294
+
295
+ function autoClaimExperienceReuse(event) {
296
+ if (String(event.event_type || '').toLowerCase() !== 'task_outcome') return []
297
+ const targetAgent = String(event.agent || '').trim()
298
+ if (!targetAgent) return []
299
+ const now = Date.now()
300
+ const claims = []
301
+ const remaining = []
302
+ const entries = loadRecentQueries()
303
+ for (const entry of entries) {
304
+ const expired = now - entry.timestamp > REUSE_MATCH_WINDOW_MS
305
+ const matches =
306
+ entry.agent === targetAgent && (!event.project || entry.project === event.project)
307
+ if (expired || matches) {
308
+ if (matches && !expired) {
309
+ claims.push(buildAutoClaim(entry, event, targetAgent))
310
+ }
311
+ continue
312
+ }
313
+ remaining.push(entry)
314
+ }
315
+ persistRecentQueries(remaining)
316
+ for (const evidence of claims) {
317
+ appendJsonl(experienceReusePath, evidence)
318
+ }
319
+ return claims
320
+ }
321
+
322
+ function buildAutoClaim(entry, event, targetAgent) {
323
+ const crossSourceIndex = entry.resultSources.findIndex(
324
+ (source) => source && String(source).toLowerCase() !== targetAgent.toLowerCase()
325
+ )
326
+ const sourceAgent =
327
+ crossSourceIndex >= 0
328
+ ? String(entry.resultSources[crossSourceIndex])
329
+ : targetAgent
330
+ const experienceId =
331
+ entry.resultIds[crossSourceIndex >= 0 ? crossSourceIndex : 0] ||
332
+ entry.resultIds[0] ||
333
+ 'unknown'
334
+ const outcomeImproved = String(event.outcome || '').toLowerCase() === 'success'
335
+ return {
336
+ id: createId('xfer'),
337
+ timestamp: new Date().toISOString(),
338
+ sourceAgent,
339
+ targetAgent,
340
+ experienceId,
341
+ reuse: true,
342
+ behaviorChanged: false,
343
+ outcomeImproved,
344
+ project: entry.project,
345
+ source: 'auto_claim',
346
+ traceId: event.trace_id || null,
347
+ notes: `Auto-claimed: memory.query "${entry.query}" matched task_outcome ${event.outcome || 'unknown'} in trace ${event.trace_id || 'unknown'}.`,
348
+ }
349
+ }
350
+
351
+ const SUBSCRIPTION_DEFAULT_TTL_DAYS = 30
352
+ const MAX_SUBSCRIPTIONS_PER_AGENT = 20
353
+ const MAX_DIGEST_EVENTS = 100
354
+
355
+ function readDigestState() {
356
+ if (!fs.existsSync(digestStatePath)) return {}
357
+ try {
358
+ const parsed = JSON.parse(fs.readFileSync(digestStatePath, 'utf8'))
359
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
360
+ } catch (_) {
361
+ return {}
362
+ }
363
+ }
364
+
365
+ function writeDigestState(state) {
366
+ fs.mkdirSync(dataDir, { recursive: true })
367
+ fs.writeFileSync(digestStatePath, JSON.stringify(state), 'utf8')
368
+ }
369
+
370
+ function subscribeKey(agent, project, eventTypes, topic) {
371
+ return `${agent}|${project}|${eventTypes.join(',')}|${topic || ''}`
372
+ }
373
+
374
+ function loadActiveSubscriptions(agent) {
375
+ const now = Date.now()
376
+ return readJsonl(subscriptionPath)
377
+ .filter((subscription) => subscription && subscription.agent === agent)
378
+ .filter((subscription) => {
379
+ if (subscription.expiresAt) {
380
+ const expires = new Date(subscription.expiresAt).getTime()
381
+ if (Number.isFinite(expires) && expires <= now) return false
382
+ }
383
+ return true
384
+ })
385
+ }
386
+
387
+ function subscribeObserver(args = {}) {
388
+ const agent = runtimeAgentId() || 'mcp'
389
+ const project = args.project || projectName()
390
+ const eventTypes = Array.isArray(args.eventTypes)
391
+ ? args.eventTypes.map((value) => String(value).trim().toLowerCase()).filter(Boolean)
392
+ : []
393
+ const topic = args.topic ? String(args.topic).trim().slice(0, 120) : ''
394
+ const ttlDays = Number(args.ttlDays) || SUBSCRIPTION_DEFAULT_TTL_DAYS
395
+ const ttlMs = Math.max(1, ttlDays) * 24 * 60 * 60 * 1000
396
+
397
+ const subscriptions = readJsonl(subscriptionPath)
398
+ const key = subscribeKey(agent, project, eventTypes, topic)
399
+ let existing = subscriptions.find((subscription) => {
400
+ return (
401
+ subscription &&
402
+ subscribeKey(
403
+ subscription.agent,
404
+ subscription.project,
405
+ subscription.eventTypes || [],
406
+ subscription.topic || '',
407
+ ) === key
408
+ )
409
+ })
410
+ const now = new Date()
411
+ const expiresAt = new Date(now.getTime() + ttlMs).toISOString()
412
+ if (existing) {
413
+ existing.updatedAt = now.toISOString()
414
+ existing.expiresAt = expiresAt
415
+ } else {
416
+ existing = {
417
+ id: createId('sub'),
418
+ agent,
419
+ project,
420
+ eventTypes,
421
+ topic: topic || null,
422
+ createdAt: now.toISOString(),
423
+ updatedAt: now.toISOString(),
424
+ expiresAt,
425
+ }
426
+ subscriptions.push(existing)
427
+ }
428
+ const agentSubscriptions = subscriptions.filter((subscription) => subscription.agent === agent)
429
+ if (agentSubscriptions.length > MAX_SUBSCRIPTIONS_PER_AGENT) {
430
+ throw new Error(`Too many subscriptions for agent ${agent} (max ${MAX_SUBSCRIPTIONS_PER_AGENT})`)
431
+ }
432
+ writeJsonl(subscriptionPath, subscriptions)
433
+ return { subscribed: true, subscription: existing, project }
434
+ }
435
+
436
+ function observerDigest(args = {}) {
437
+ const agent = runtimeAgentId() || 'mcp'
438
+ const project = args.project || projectName()
439
+ const limit = Math.min(Math.max(Number(args.limit) || 20, 1), MAX_DIGEST_EVENTS)
440
+ const filterEventTypes = Array.isArray(args.eventTypes)
441
+ ? args.eventTypes.map((value) => String(value).trim().toLowerCase()).filter(Boolean)
442
+ : null
443
+
444
+ let subscriptions = loadActiveSubscriptions(agent)
445
+ if (args.project) {
446
+ subscriptions = subscriptions.filter((subscription) => subscription.project === project)
447
+ }
448
+ if (filterEventTypes) {
449
+ subscriptions = subscriptions.filter((subscription) => {
450
+ if ((subscription.eventTypes || []).length === 0) return true
451
+ return filterEventTypes.some((eventType) =>
452
+ (subscription.eventTypes || []).includes(eventType),
453
+ )
454
+ })
455
+ }
456
+
457
+ const state = readDigestState()
458
+ const traces = readJsonl(tracePath)
459
+ const digestTime = new Date().toISOString()
460
+ const events = []
461
+ const seenIds = new Set()
462
+ const matchedSubscriptionIds = new Set()
463
+
464
+ for (const subscription of subscriptions) {
465
+ const cursor = state[subscription.id] || null
466
+ const cursorTime = cursor ? Date.parse(cursor) : null
467
+ const subscriptionEventTypes = subscription.eventTypes || []
468
+ let lastEventTime = null
469
+ for (const event of traces) {
470
+ if (subscription.project && event.project && event.project !== subscription.project) {
471
+ continue
472
+ }
473
+ if (
474
+ subscriptionEventTypes.length > 0 &&
475
+ !subscriptionEventTypes.includes(String(event.event_type || '').toLowerCase())
476
+ ) {
477
+ continue
478
+ }
479
+ if (subscription.topic) {
480
+ const haystack = `${event.event_type || ''} ${JSON.stringify(event.payload || {})}`
481
+ .toLowerCase()
482
+ if (!haystack.includes(subscription.topic.toLowerCase())) continue
483
+ }
484
+ const eventTime = event.timestamp ? Date.parse(event.timestamp) : null
485
+ if (cursorTime !== null && eventTime !== null && eventTime <= cursorTime) continue
486
+ if (eventTime !== null && (lastEventTime === null || eventTime > lastEventTime)) {
487
+ lastEventTime = eventTime
488
+ }
489
+ if (seenIds.has(event.id)) continue
490
+ seenIds.add(event.id)
491
+ events.push({
492
+ id: event.id,
493
+ trace_id: event.trace_id || null,
494
+ event_type: event.event_type,
495
+ outcome: event.outcome || null,
496
+ timestamp: event.timestamp,
497
+ agent: event.agent || null,
498
+ payload: event.payload || null,
499
+ })
500
+ matchedSubscriptionIds.add(subscription.id)
501
+ if (events.length >= limit) break
502
+ }
503
+ if (lastEventTime !== null) {
504
+ state[subscription.id] = new Date(lastEventTime).toISOString()
505
+ } else if (cursor === null) {
506
+ state[subscription.id] = digestTime
507
+ }
508
+ if (events.length >= limit) break
509
+ }
510
+
511
+ writeDigestState(state)
512
+ return {
513
+ project,
514
+ agent,
515
+ subscriptionCount: subscriptions.length,
516
+ matchedSubscriptions: Array.from(matchedSubscriptionIds),
517
+ count: events.length,
518
+ events,
519
+ }
520
+ }
521
+
522
+ function contentTokens(value) {
523
+ const text = String(value || '').toLowerCase()
524
+ const latin = text.match(/[a-z0-9]+/g) || []
525
+ const chars = text.match(/[\u4e00-\u9fff]/g) || []
526
+ const bigrams = []
527
+ for (let i = 0; i < chars.length - 1; i++) {
528
+ bigrams.push(`${chars[i]}${chars[i + 1]}`)
529
+ }
530
+ return [...latin, ...bigrams]
531
+ }
532
+
533
+ function jaccardSimilarity(a, b) {
534
+ const setA = new Set(contentTokens(a))
535
+ const setB = new Set(contentTokens(b))
536
+ if (setA.size === 0 || setB.size === 0) return 0
537
+ let intersection = 0
538
+ for (const token of setA) {
539
+ if (setB.has(token)) intersection += 1
540
+ }
541
+ const union = setA.size + setB.size - intersection
542
+ return union === 0 ? 0 : intersection / union
543
+ }
544
+
545
+ function findDuplicateGroups(records, limit) {
546
+ const parent = new Map()
547
+ for (const record of records) parent.set(record.id, record.id)
548
+ const find = (id) => {
549
+ while (parent.get(id) !== id) {
550
+ parent.set(id, parent.get(parent.get(id)))
551
+ id = parent.get(id)
552
+ }
553
+ return id
554
+ }
555
+ const union = (a, b) => {
556
+ const ra = find(a)
557
+ const rb = find(b)
558
+ if (ra !== rb) parent.set(ra, rb)
559
+ }
560
+ for (let i = 0; i < records.length; i++) {
561
+ for (let j = i + 1; j < records.length; j++) {
562
+ if (
563
+ jaccardSimilarity(records[i].content, records[j].content) >= MEMORY_DUPLICATE_SIMILARITY
564
+ ) {
565
+ union(records[i].id, records[j].id)
566
+ }
567
+ }
568
+ }
569
+ const byRoot = new Map()
570
+ for (const record of records) {
571
+ const root = find(record.id)
572
+ if (!byRoot.has(root)) byRoot.set(root, [])
573
+ byRoot.get(root).push(record)
574
+ }
575
+ return Array.from(byRoot.values())
576
+ .filter((group) => group.length >= 2)
577
+ .sort((a, b) => b.length - a.length)
578
+ .slice(0, limit)
579
+ }
580
+
581
+ function analyzeMemory(args = {}) {
582
+ const project = args.project || projectName()
583
+ const limit = Math.min(Math.max(Number(args.limit) || 5, 1), 20)
584
+ const records = readJsonl(memoryPath).filter(
585
+ (record) => !project || record.project === project || !record.project,
586
+ )
587
+ const archived = records.filter((record) => record.archived === true).length
588
+ const activeRecords = records.filter((record) => record.archived !== true)
589
+ const total = activeRecords.length
590
+ const layerCounts = { project: 0, global: 0 }
591
+ for (const record of activeRecords) {
592
+ if (record.scope === 'global' || !record.project) layerCounts.global += 1
593
+ else layerCounts.project += 1
594
+ }
595
+
596
+ const byKind = {}
597
+ const lowQuality = []
598
+ for (const record of activeRecords) {
599
+ const kind = String(record.kind || '').trim() || 'unknown'
600
+ byKind[kind] = (byKind[kind] || 0) + 1
601
+ const content = String(record.content || '').trim()
602
+ const issues = []
603
+ if (!content) issues.push('missing content')
604
+ else if (content.length < MEMORY_SHORT_CONTENT_MIN) issues.push('content too short')
605
+ if (!record.kind || !String(record.kind).trim()) issues.push('missing kind')
606
+ if (issues.length > 0) {
607
+ lowQuality.push({
608
+ id: record.id,
609
+ timestamp: record.timestamp,
610
+ kind: record.kind || null,
611
+ content: content.slice(0, 200) || null,
612
+ issues,
613
+ })
614
+ }
615
+ }
616
+
617
+ let duplicateGroups = []
618
+ let duplicatesSkipped = false
619
+ if (activeRecords.length > MAX_PAIRWISE_MEMORY) {
620
+ duplicatesSkipped = true
621
+ } else {
622
+ duplicateGroups = findDuplicateGroups(activeRecords, limit).map((group) => ({
623
+ size: group.length,
624
+ records: group.map((record) => ({
625
+ id: record.id,
626
+ timestamp: record.timestamp,
627
+ kind: record.kind || null,
628
+ content: String(record.content || '').slice(0, 200),
629
+ })),
630
+ }))
631
+ }
632
+
633
+ const issues = {
634
+ lowQuality: lowQuality.length,
635
+ duplicateGroups: duplicateGroups.length,
636
+ duplicatesSkipped,
637
+ }
638
+
639
+ const suggestions = []
640
+ if (duplicateGroups.length > 0) {
641
+ suggestions.push(
642
+ `Found ${duplicateGroups.length} duplicate group(s); consider archiving or merging duplicates to keep recall precise.`,
643
+ )
644
+ }
645
+ if (lowQuality.length > 0) {
646
+ suggestions.push(
647
+ `${lowQuality.length} low-quality record(s) (missing kind/content or too short); consider fixing or removing them.`,
648
+ )
649
+ }
650
+ if (total === 0) {
651
+ suggestions.push('No memory records for this project yet.')
652
+ } else if (duplicateGroups.length === 0 && lowQuality.length === 0) {
653
+ suggestions.push('Memory looks healthy; no dedup or quality fixes needed.')
654
+ }
655
+
656
+ return {
657
+ project: project || null,
658
+ total,
659
+ archived,
660
+ layers: layerCounts,
661
+ byKind,
662
+ issues,
663
+ duplicates: duplicateGroups,
664
+ lowQuality: lowQuality.slice(0, limit),
665
+ suggestions,
666
+ }
667
+ }
668
+
669
+ function migrateMemory(args = {}) {
670
+ const idsInput = Array.isArray(args.ids) ? args.ids : []
671
+ const ids = idsInput.map((value) => String(value).trim()).filter(Boolean)
672
+ if (ids.length === 0) throw new Error('memory.migrate requires ids (array of memory record ids)')
673
+ const targetScope = normalizeScope(args.scope)
674
+ if (targetScope === 'all') throw new Error('memory.migrate scope must be project or global')
675
+ const project = args.project || projectName()
676
+ const reason = args.reason ? String(args.reason).trim().slice(0, 200) : null
677
+
678
+ const records = readJsonl(memoryPath)
679
+ const idSet = new Set(ids)
680
+ const updated = []
681
+ const unchanged = []
682
+ const notFound = [...ids]
683
+ for (const record of records) {
684
+ if (!idSet.has(record.id)) continue
685
+ const fromScope = record.scope || 'project'
686
+ const fromProject = record.project || null
687
+ if (fromScope === targetScope) {
688
+ unchanged.push(record.id)
689
+ } else {
690
+ record.scope = targetScope
691
+ record.project = targetScope === 'global' ? null : project
692
+ record.migratedAt = new Date().toISOString()
693
+ record.migratedFrom = fromScope === 'global' ? 'global' : fromProject || 'project'
694
+ if (reason) record.migrateReason = reason
695
+ updated.push(record.id)
696
+ }
697
+ const index = notFound.indexOf(record.id)
698
+ if (index >= 0) notFound.splice(index, 1)
699
+ }
700
+ writeJsonl(memoryPath, records)
701
+
702
+ return {
703
+ project: project || null,
704
+ scope: targetScope,
705
+ updated,
706
+ updatedCount: updated.length,
707
+ unchanged,
708
+ notFound,
709
+ }
710
+ }
711
+ function archiveMemory(args = {}) {
712
+ const idsInput = Array.isArray(args.ids) ? args.ids : []
713
+ const ids = idsInput.map((value) => String(value).trim()).filter(Boolean)
714
+ if (ids.length === 0) throw new Error('memory.archive requires ids (array of memory record ids)')
715
+ const project = args.project || projectName()
716
+ const restore = args.restore === true || args.restore === 'true'
717
+ const reason = args.reason ? String(args.reason).trim().slice(0, 200) : null
718
+
719
+ const records = readJsonl(memoryPath)
720
+ const idSet = new Set(ids)
721
+ const archived = []
722
+ const notFound = [...ids]
723
+ for (const record of records) {
724
+ if (!idSet.has(record.id)) continue
725
+ if (project && record.project && record.project !== project) continue
726
+ if (restore) {
727
+ if (record.archived === true) {
728
+ delete record.archived
729
+ delete record.archivedAt
730
+ delete record.archiveReason
731
+ archived.push(record.id)
732
+ }
733
+ } else if (record.archived !== true) {
734
+ record.archived = true
735
+ record.archivedAt = new Date().toISOString()
736
+ if (reason) record.archiveReason = reason
737
+ archived.push(record.id)
738
+ }
739
+ const index = notFound.indexOf(record.id)
740
+ if (index >= 0) notFound.splice(index, 1)
741
+ }
742
+ writeJsonl(memoryPath, records)
743
+
744
+ return {
745
+ project: project || null,
746
+ restored: restore,
747
+ archived,
748
+ archivedCount: archived.length,
749
+ notFound,
750
+ }
751
+ }
752
+
753
+ const FAILURE_OUTCOMES = new Set(['failure', 'error', 'aborted', 'retry'])
754
+ const MEMORY_DUPLICATE_SIMILARITY = 0.75
755
+ const MEMORY_SHORT_CONTENT_MIN = 20
756
+ const MAX_PAIRWISE_MEMORY = 1500
757
+
758
+ function isFailureOutcome(value) {
759
+ return FAILURE_OUTCOMES.has(String(value || '').toLowerCase())
760
+ }
761
+
762
+ function summarizeTrace(event) {
763
+ const payload = event.payload
764
+ if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
765
+ if (typeof payload.summary === 'string' && payload.summary.trim()) {
766
+ return payload.summary.trim().slice(0, 160)
767
+ }
768
+ if (typeof payload.tool === 'string' && payload.tool.trim()) {
769
+ return `tool: ${payload.tool.trim().slice(0, 120)}`
770
+ }
771
+ if (typeof payload.error === 'string' && payload.error.trim()) {
772
+ return payload.error.trim().slice(0, 160)
773
+ }
774
+ }
775
+ return String(event.event_type || 'trace').slice(0, 120)
776
+ }
777
+
778
+ function buildPolicyGuidance({ total, failures, risk, failureExamples, relatedMemories }) {
779
+ const guidance = {
780
+ level: 'none',
781
+ rationale: null,
782
+ saferAlternatives: [],
783
+ verificationSteps: [],
784
+ avoid: [],
785
+ hardGate: false,
786
+ }
787
+ if (total === 0) {
788
+ guidance.rationale =
789
+ 'No historical evidence for this action yet. Treat as normal risk and record the outcome.'
790
+ return guidance
791
+ }
792
+ const verifiedMemories = relatedMemories.filter((record) => record.evidence)
793
+ const hasVerified = verifiedMemories.length > 0
794
+ if (risk >= 0.4 && failures >= 2) {
795
+ guidance.level = hasVerified ? 'actionable' : 'advisory'
796
+ guidance.rationale =
797
+ 'Repeated historical failures. Prefer an alternative approach and add rollback/verification.'
798
+ guidance.avoid = failureExamples
799
+ .map((example) => example.summary)
800
+ .filter(Boolean)
801
+ .slice(0, 3)
802
+ } else if (risk >= 0.2 || hasVerified) {
803
+ guidance.level = hasVerified ? 'actionable' : 'advisory'
804
+ guidance.rationale = hasVerified
805
+ ? 'Verified experience exists for this action; apply it before proceeding.'
806
+ : 'Moderate historical risk. Add verification before proceeding.'
807
+ } else {
808
+ guidance.level = 'advisory'
809
+ guidance.rationale = 'Low historical risk. Proceed with normal checks and record the outcome.'
810
+ }
811
+ if (hasVerified) {
812
+ guidance.saferAlternatives = verifiedMemories.slice(0, 3).map((record) => ({
813
+ memoryId: record.id,
814
+ reuseCount: record.evidence.reuseCount,
815
+ content: String(record.content || '').slice(0, 300),
816
+ }))
817
+ }
818
+ guidance.verificationSteps = [
819
+ 'Add an explicit verification step after execution (dry-run, rollback plan, or assertion).',
820
+ 'Record the outcome with mio.observer.ingest so the evidence base improves.',
821
+ ]
822
+ return guidance
823
+ }
824
+
825
+ function policyCheck(args = {}) {
826
+ const action = String(args.action || '').trim()
827
+ if (!action) throw new Error('policy.check requires action')
828
+ const project = args.project || projectName()
829
+ const actionTokens = tokenize(action)
830
+ const traces = readJsonl(tracePath).filter((event) => {
831
+ if (project && event.project && event.project !== project) return false
832
+ const haystack = tokenize(
833
+ `${event.event_type || ''} ${JSON.stringify(event.payload || {})}`
834
+ )
835
+ return actionTokens.some((token) => haystack.includes(token))
836
+ })
837
+ const total = traces.length
838
+ const failures = traces.filter((event) => isFailureOutcome(event.outcome)).length
839
+ const risk = total > 0 ? failures / total : null
840
+ const riskLevel = total === 0 ? 'unknown' : risk >= 0.4 ? 'high' : risk >= 0.2 ? 'moderate' : 'low'
841
+ const outcomeCounts = traces.reduce((counts, event) => {
842
+ const outcome = String(event.outcome || 'unknown').toLowerCase() || 'unknown'
843
+ counts[outcome] = (counts[outcome] || 0) + 1
844
+ return counts
845
+ }, {})
846
+ const failureExamples = traces
847
+ .filter((event) => isFailureOutcome(event.outcome))
848
+ .sort((a, b) => new Date(b.timestamp || 0).getTime() - new Date(a.timestamp || 0).getTime())
849
+ .slice(0, 3)
850
+ .map((event) => ({
851
+ trace_id: event.trace_id || event.id || null,
852
+ event_type: event.event_type || null,
853
+ outcome: event.outcome || null,
854
+ timestamp: event.timestamp || null,
855
+ agent: event.agent || null,
856
+ summary: summarizeTrace(event),
857
+ }))
858
+ let suggestion
859
+ if (total === 0) {
860
+ suggestion = 'No history for this action. Treat as normal risk and record the outcome.'
861
+ } else if (risk >= 0.4) {
862
+ suggestion = 'Historically risky. Prefer an alternative approach or add rollback/verification.'
863
+ } else if (risk >= 0.2) {
864
+ suggestion = 'Moderate risk. Add verification before proceeding.'
865
+ } else {
866
+ suggestion = 'Low historical risk. Proceed with normal checks.'
867
+ }
868
+ const evidence = loadEvidenceWeights()
869
+ const relatedMemories = readJsonl(memoryPath)
870
+ .filter((record) => scoreRecord(record, action, project, evidence) > 0)
871
+ .sort((a, b) => scoreRecord(b, action, project, evidence) - scoreRecord(a, action, project, evidence))
872
+ .slice(0, 3)
873
+ .map((record) => {
874
+ const ev = evidence.get(record.id)
875
+ return {
876
+ id: record.id,
877
+ timestamp: record.timestamp,
878
+ kind: record.kind,
879
+ content: record.content,
880
+ tags: record.tags,
881
+ evidence: ev
882
+ ? { reuseCount: ev.reuseCount, confirmedCount: ev.confirmedCount }
883
+ : null,
884
+ }
885
+ })
886
+ return {
887
+ action,
888
+ project,
889
+ total,
890
+ failures,
891
+ risk: risk === null ? null : Number(risk.toFixed(3)),
892
+ riskLevel,
893
+ outcomeCounts,
894
+ failureExamples,
895
+ suggestion,
896
+ guidance: buildPolicyGuidance({
897
+ total,
898
+ failures,
899
+ risk,
900
+ failureExamples,
901
+ relatedMemories,
902
+ }),
903
+ related_memories: relatedMemories,
904
+ }
905
+ }
906
+
907
+ function recordExperienceReuse(args = {}) {
908
+ const sourceAgent = String(args.sourceAgent || '').trim()
909
+ const targetAgent = String(args.targetAgent || '').trim()
910
+ const experienceId = String(args.experienceId || '').trim()
911
+ if (!sourceAgent) throw new Error('experience.reuse requires sourceAgent')
912
+ if (!targetAgent) throw new Error('experience.reuse requires targetAgent')
913
+ if (!experienceId) throw new Error('experience.reuse requires experienceId')
914
+
915
+ const project = args.project || projectName()
916
+ const evidence = {
917
+ id: createId('xfer'),
918
+ timestamp: new Date().toISOString(),
919
+ sourceAgent,
920
+ targetAgent,
921
+ experienceId,
922
+ reuse: args.reuse === true || args.reuse === 'true',
923
+ behaviorChanged: args.behaviorChanged === true || args.behaviorChanged === 'true',
924
+ outcomeImproved: args.outcomeImproved === true || args.outcomeImproved === 'true',
925
+ project,
926
+ source: args.source || 'agent_report',
927
+ notes: args.notes || null,
928
+ }
929
+ appendJsonl(experienceReusePath, evidence)
930
+
931
+ const report = loadPhase0(dataDir, project)
932
+ return {
933
+ recorded: true,
934
+ evidence,
935
+ phase0: summarizePhase0(report),
936
+ }
937
+ }
938
+
939
+ function confirmExperienceReuse(args = {}) {
940
+ const id = String(args.id || '').trim()
941
+ if (!id) throw new Error('experience.confirm requires id of an auto-claimed reuse record')
942
+ const records = readJsonl(experienceReusePath)
943
+ const index = records.findIndex((record) => record && record.id === id)
944
+ if (index < 0) {
945
+ throw new Error(`No experience reuse record found with id ${id}`)
946
+ }
947
+ const record = records[index]
948
+ if (record.source !== 'auto_claim') {
949
+ throw new Error('experience.confirm only applies to source=auto_claim reuse records')
950
+ }
951
+ const outcomeImproved =
952
+ args.outcomeImproved === undefined || args.outcomeImproved === null
953
+ ? record.outcomeImproved === true
954
+ : args.outcomeImproved === true || args.outcomeImproved === 'true'
955
+ const updated = {
956
+ ...record,
957
+ behaviorChanged: true,
958
+ outcomeImproved,
959
+ confirmed: true,
960
+ confirmedAt: new Date().toISOString(),
961
+ confirmedBy: String(args.confirmedBy || 'agent').trim() || 'agent',
962
+ notes: args.notes ? String(args.notes).trim() : record.notes || null,
963
+ }
964
+ records[index] = updated
965
+ writeJsonl(experienceReusePath, records)
966
+
967
+ const report = loadPhase0(dataDir, updated.project)
968
+ return {
969
+ confirmed: true,
970
+ evidence: updated,
971
+ phase0: summarizePhase0(report),
972
+ }
973
+ }
974
+
975
+ function listExperienceReuse(args = {}) {
976
+ const project = args.project || projectName()
977
+ const status = String(args.status || 'all').trim().toLowerCase()
978
+ const targetAgent = String(args.targetAgent || '').trim().toLowerCase()
979
+ const limit = Math.min(Math.max(Number(args.limit) || 20, 1), 100)
980
+
981
+ let records = readJsonl(experienceReusePath)
982
+ if (project) records = records.filter((record) => record.project === project)
983
+ if (targetAgent) {
984
+ records = records.filter(
985
+ (record) => String(record.targetAgent || '').toLowerCase() === targetAgent,
986
+ )
987
+ }
988
+ const matcher = REUSE_STATUS_FILTERS[status]
989
+ if (matcher) records = records.filter(matcher)
990
+ records.sort((a, b) => {
991
+ const at = new Date(a.timestamp || 0).getTime()
992
+ const bt = new Date(b.timestamp || 0).getTime()
993
+ return bt - at
994
+ })
995
+
996
+ const visible = records.slice(0, limit).map((record) => ({
997
+ id: record.id,
998
+ source: record.source,
999
+ sourceAgent: record.sourceAgent,
1000
+ targetAgent: record.targetAgent,
1001
+ experienceId: record.experienceId,
1002
+ reuse: record.reuse === true || record.reuse === 'true',
1003
+ behaviorChanged: record.behaviorChanged === true || record.behaviorChanged === 'true',
1004
+ outcomeImproved: record.outcomeImproved === true || record.outcomeImproved === 'true',
1005
+ confirmed: record.confirmed === true,
1006
+ confirmedBy: record.confirmedBy || null,
1007
+ traceId: record.traceId || null,
1008
+ timestamp: record.timestamp,
1009
+ project: record.project,
1010
+ notes:
1011
+ typeof record.notes === 'string' && record.notes ? record.notes.slice(0, 300) : null,
1012
+ }))
1013
+
1014
+ return {
1015
+ project: project || null,
1016
+ status,
1017
+ count: visible.length,
1018
+ total: records.length,
1019
+ records: visible,
1020
+ }
1021
+ }
1022
+
1023
+ function registerAgent(args = {}) {
1024
+ const agentId = String(args.agentId || '').trim()
1025
+ if (!agentId) throw new Error('agent.register requires a non-empty agentId')
1026
+ const project = args.project || projectName()
1027
+ const hostType = args.hostType || 'mcp'
1028
+ const capabilities = Array.isArray(args.capabilities) ? args.capabilities : []
1029
+ const now = new Date().toISOString()
1030
+ const agents = readJsonl(agentsPath)
1031
+ const existing = agents.find((a) => a.agentId === agentId && a.project === project)
1032
+ let result
1033
+ if (existing) {
1034
+ existing.lastSeenAt = now
1035
+ existing.sessionCount = (existing.sessionCount || 1) + 1
1036
+ existing.hostType = hostType
1037
+ if (capabilities.length > 0) existing.capabilities = capabilities
1038
+ result = existing
1039
+ } else {
1040
+ result = {
1041
+ id: createId('agent'),
1042
+ agentId,
1043
+ hostType,
1044
+ capabilities,
1045
+ registeredAt: now,
1046
+ lastSeenAt: now,
1047
+ sessionCount: 1,
1048
+ project,
1049
+ }
1050
+ agents.push(result)
1051
+ }
1052
+ writeJsonl(agentsPath, agents)
1053
+ return { id: result.id, agentId: result.agentId, registered: !existing, sessionCount: result.sessionCount, hostType: result.hostType, capabilities: result.capabilities }
1054
+ }
1055
+
1056
+ function listAgents(args = {}) {
1057
+ const project = args.project || null
1058
+ let agents = readJsonl(agentsPath)
1059
+ if (project) agents = agents.filter((a) => a.project === project)
1060
+ return {
1061
+ count: agents.length,
1062
+ agents: agents.map((a) => ({
1063
+ id: a.id, agentId: a.agentId, hostType: a.hostType,
1064
+ capabilities: a.capabilities, registeredAt: a.registeredAt,
1065
+ lastSeenAt: a.lastSeenAt, sessionCount: a.sessionCount,
1066
+ taskCount: a.taskCount || 0, successCount: a.successCount || 0, failureCount: a.failureCount || 0,
1067
+ project: a.project,
1068
+ })),
1069
+ }
1070
+ }
1071
+
1072
+ function reportAgent(args = {}) {
1073
+ const targetAgent = args.agentId || null
1074
+ const project = args.project || projectName()
1075
+ const agents = readJsonl(agentsPath)
1076
+ const filtered = agents.filter((a) =>
1077
+ (!targetAgent || a.agentId === targetAgent) && (!project || a.project === project)
1078
+ )
1079
+ const traces = readJsonl(tracePath)
1080
+ const memories = readJsonl(memoryPath)
1081
+ const reuses = readJsonl(experienceReusePath)
1082
+ const reports = filtered.map((agent) => {
1083
+ const agentTraces = traces.filter((t) => t.agent === agent.agentId)
1084
+ const outcomes = agentTraces.filter((t) => t.event_type === 'task_outcome')
1085
+ const successes = outcomes.filter((t) => t.outcome === 'success').length
1086
+ const failures = outcomes.filter((t) => t.outcome === 'failure').length
1087
+ const agentMemories = memories.filter((m) => m.source === agent.agentId)
1088
+ const agentReuses = reuses.filter((r) => r.sourceAgent === agent.agentId || r.targetAgent === agent.agentId)
1089
+ const verified = agentReuses.filter((r) => r.confirmed && r.reuse && r.behaviorChanged && r.outcomeImproved)
1090
+ const regTasks = agent.taskCount || 0
1091
+ const regSuccess = agent.successCount || 0
1092
+ const regFail = agent.failureCount || 0
1093
+ const taskTotal = regTasks > 0 ? regTasks : outcomes.length
1094
+ const taskSuccess = regTasks > 0 ? regSuccess : successes
1095
+ const taskFail = regTasks > 0 ? regFail : failures
1096
+ return {
1097
+ agentId: agent.agentId,
1098
+ hostType: agent.hostType,
1099
+ sessionCount: agent.sessionCount,
1100
+ registeredAt: agent.registeredAt,
1101
+ lastSeenAt: agent.lastSeenAt,
1102
+ taskOutcomes: { total: taskTotal, success: taskSuccess, failure: taskFail, successRate: taskTotal > 0 ? Math.round((taskSuccess / taskTotal) * 100) : 0 },
1103
+ memories: agentMemories.length,
1104
+ experienceReuses: { total: agentReuses.length, verified: verified.length },
1105
+ active: (Date.now() - new Date(agent.lastSeenAt).getTime()) < 24 * 60 * 60 * 1000,
1106
+ }
1107
+ })
1108
+ return { project, count: reports.length, reports }
1109
+ }
1110
+
1111
+ function routeTask(args = {}) {
1112
+ const task = String(args.task || '').trim()
1113
+ if (!task) throw new Error('task.route requires a non-empty task')
1114
+ const project = args.project || projectName()
1115
+ const scope = normalizeScope(args.scope)
1116
+ const limit = Math.min(Math.max(Number(args.limit) || 5, 1), 10)
1117
+
1118
+ const memories = readJsonl(memoryPath).filter((record) => record.archived !== true)
1119
+ const memoryById = new Map(memories.map((record) => [record.id, record]))
1120
+ const evidence = loadEvidenceWeights()
1121
+
1122
+ // Match verified reuse experiences whose source memory is relevant to the task.
1123
+ const routeByMemory = new Map()
1124
+ for (const record of readJsonl(experienceReusePath)) {
1125
+ if (!REUSE_STATUS_FILTERS.verified(record)) continue
1126
+ const memory = memoryById.get(record.experienceId)
1127
+ if (!memory || !matchesProjectScope(memory, project, scope)) continue
1128
+ const score = scoreRecord(memory, task, project)
1129
+ if (score <= 0) continue
1130
+ let entry = routeByMemory.get(record.experienceId)
1131
+ if (!entry) {
1132
+ entry = {
1133
+ experienceId: record.experienceId,
1134
+ memory,
1135
+ weight: 0,
1136
+ confirmed: false,
1137
+ sourceAgents: new Set(),
1138
+ targetAgents: new Set(),
1139
+ reuseCount: 0,
1140
+ }
1141
+ routeByMemory.set(record.experienceId, entry)
1142
+ }
1143
+ entry.reuseCount += 1
1144
+ if (record.confirmed === true) entry.confirmed = true
1145
+ if (record.sourceAgent) entry.sourceAgents.add(record.sourceAgent)
1146
+ if (record.targetAgent) entry.targetAgents.add(record.targetAgent)
1147
+ entry.weight = Math.max(entry.weight, score + (entry.confirmed ? 2 : 1.5))
1148
+ }
1149
+
1150
+ const routes = [...routeByMemory.values()]
1151
+ .sort((a, b) => b.weight - a.weight)
1152
+ .slice(0, limit)
1153
+ .map((entry) => ({
1154
+ experienceId: entry.experienceId,
1155
+ reuseCount: entry.reuseCount,
1156
+ confirmed: entry.confirmed,
1157
+ sourceAgents: [...entry.sourceAgents].filter(Boolean),
1158
+ targetAgents: [...entry.targetAgents].filter(Boolean),
1159
+ score: Number(entry.weight.toFixed(2)),
1160
+ memory: {
1161
+ id: entry.memory.id,
1162
+ timestamp: entry.memory.timestamp,
1163
+ kind: entry.memory.kind,
1164
+ content: entry.memory.content,
1165
+ tags: entry.memory.tags || [],
1166
+ project: entry.memory.project || null,
1167
+ scope: entry.memory.scope || 'project',
1168
+ },
1169
+ }))
1170
+
1171
+ // Broader context: top related memories not already routed.
1172
+ const routedIds = new Set(routes.map((route) => route.experienceId))
1173
+ const scoreRelated = (record) =>
1174
+ scoreRecord(record, task, project, evidence) +
1175
+ (scope === 'all' && isGlobalRecord(record) ? 0.5 : 0)
1176
+ const relatedMemories = memories
1177
+ .filter((record) => !routedIds.has(record.id))
1178
+ .filter((record) => matchesProjectScope(record, project, scope))
1179
+ .filter((record) => scoreRelated(record) > 0)
1180
+ .sort((a, b) => scoreRelated(b) - scoreRelated(a))
1181
+ .slice(0, Math.max(limit, 5))
1182
+ .map((record) => {
1183
+ const ev = evidence.get(record.id)
1184
+ return {
1185
+ id: record.id,
1186
+ timestamp: record.timestamp,
1187
+ kind: record.kind,
1188
+ content: record.content,
1189
+ tags: record.tags || [],
1190
+ project: record.project || null,
1191
+ scope: record.scope || 'project',
1192
+ evidence: ev
1193
+ ? { reuseCount: ev.reuseCount, confirmedCount: ev.confirmedCount }
1194
+ : null,
1195
+ }
1196
+ })
1197
+
1198
+ // Feed the query log so a later task_outcome can auto-claim route-driven reuse.
1199
+ if (routes.length > 0 || relatedMemories.length > 0) {
1200
+ const now = Date.now()
1201
+ const entries = loadRecentQueries()
1202
+ entries.push({
1203
+ agent: runtimeAgentId() || 'mcp',
1204
+ project,
1205
+ query: task,
1206
+ resultIds: [...routedIds, ...relatedMemories.map((record) => record.id)].filter(Boolean),
1207
+ resultSources: [...routes.map(() => 'experience'), ...relatedMemories.map((record) => record.source || null)],
1208
+ timestamp: now,
1209
+ expiresAt: now + REUSE_MATCH_WINDOW_MS,
1210
+ })
1211
+ persistRecentQueries(entries)
1212
+ }
1213
+
1214
+ let suggestion
1215
+ if (routes.length > 0) {
1216
+ suggestion =
1217
+ `Route ${routes.length} verified experience(s) to this task; apply the top match first and record the outcome with mio.observer.ingest / mio.experience.reuse.`
1218
+ } else if (relatedMemories.length > 0) {
1219
+ suggestion =
1220
+ 'No verified experience matches yet. Consult the related memories, then record the outcome so this task can seed future routes.'
1221
+ } else {
1222
+ suggestion =
1223
+ 'No matching experience or memory found. Proceed with care and record the outcome to grow the experience base.'
1224
+ }
1225
+
1226
+ return {
1227
+ task,
1228
+ project,
1229
+ scope,
1230
+ count: routes.length,
1231
+ routes,
1232
+ relatedMemories,
1233
+ summary: {
1234
+ verifiedRoutes: routes.length,
1235
+ relatedMemories: relatedMemories.length,
1236
+ suggestion,
1237
+ },
1238
+ }
1239
+ }
1240
+ function phase0Report(args = {}) {
1241
+ const project = args.project || projectName()
1242
+ const report = loadPhase0(dataDir, project)
1243
+ const format = String(args.format || 'json').trim().toLowerCase()
1244
+ if (format === 'markdown') {
1245
+ return {
1246
+ project,
1247
+ format: 'markdown',
1248
+ markdown: renderPhase0Markdown(report),
1249
+ }
1250
+ }
1251
+ return {
1252
+ project,
1253
+ ...report,
1254
+ }
1255
+ }
1256
+
1257
+ const TOOLS = [
1258
+ {
1259
+ name: 'mio.memory.query',
1260
+ description: 'Search local Mio project memory for context, decisions, and historical problems.',
1261
+ inputSchema: {
1262
+ type: 'object',
1263
+ properties: {
1264
+ query: { type: 'string', description: 'Question or topic to recall.' },
1265
+ project: { type: 'string', description: 'Project name filter. Defaults to current directory name.' },
1266
+ limit: { type: 'number', description: 'Maximum results, between 1 and 20. Defaults to 5.' },
1267
+ kind: { type: 'string', description: 'Only return records with this kind (decision, context, problem, note).' },
1268
+ tags: { type: 'array', items: { type: 'string' }, description: 'Only return records containing all of these tags (AND).' },
1269
+ scope: { type: 'string', description: 'Search scope: project (default), global, or all.' },
1270
+ },
1271
+ required: ['query'],
1272
+ },
1273
+ },
1274
+ {
1275
+ name: 'mio.memory.archive',
1276
+ description: 'Archive (or restore) memory records by id. Archived records are excluded from memory.query and memory.analyze.',
1277
+ inputSchema: {
1278
+ type: 'object',
1279
+ properties: {
1280
+ ids: { type: 'array', items: { type: 'string' }, description: 'Memory record ids to archive or restore.' },
1281
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1282
+ restore: { type: 'boolean', description: 'When true, un-archive the given ids instead.' },
1283
+ reason: { type: 'string', description: 'Optional archive reason.' },
1284
+ },
1285
+ required: ['ids'],
1286
+ },
1287
+ },
1288
+ {
1289
+ name: 'mio.memory.migrate',
1290
+ description: 'Migrate memory records between project and global layers (P3). Moving to global makes the record reusable across projects (project set to null); moving to project restores project scoping.',
1291
+ inputSchema: {
1292
+ type: 'object',
1293
+ properties: {
1294
+ ids: { type: 'array', items: { type: 'string' }, description: 'Memory record ids to migrate.' },
1295
+ scope: { type: 'string', description: 'Target layer: global or project.' },
1296
+ project: { type: 'string', description: 'Target project for project scope. Defaults to current repository.' },
1297
+ reason: { type: 'string', description: 'Optional migration reason.' },
1298
+ },
1299
+ required: ['ids', 'scope'],
1300
+ },
1301
+ },
1302
+ {
1303
+ name: 'mio.memory.record',
1304
+ description: 'Record a decision, project context, or historical problem into local Mio memory.',
1305
+ inputSchema: {
1306
+ type: 'object',
1307
+ properties: {
1308
+ content: { type: 'string', description: 'Memory content.' },
1309
+ kind: { type: 'string', description: 'Memory kind, such as decision, context, or problem.' },
1310
+ tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags.' },
1311
+ project: { type: 'string', description: 'Project name. Defaults to current directory name.' },
1312
+ scope: { type: 'string', description: 'Record scope: project (default) or global.' },
1313
+ source: { type: 'string', description: 'Recording source. Defaults to mcp.' },
1314
+ },
1315
+ required: ['content'],
1316
+ },
1317
+ },
1318
+ {
1319
+ name: 'mio.observer.ingest',
1320
+ description: 'Ingest an Agent Trace event such as tool_call, error, retry, or task_outcome.',
1321
+ inputSchema: {
1322
+ type: 'object',
1323
+ properties: {
1324
+ trace_id: { type: 'string', description: 'Stable trace identifier.' },
1325
+ event_type: { type: 'string', description: 'Event type, such as tool_call, error, retry, task_outcome.' },
1326
+ payload: { type: 'object', description: 'Event payload.' },
1327
+ outcome: { type: 'string', description: 'Optional outcome: success, failure, error, aborted, retry.' },
1328
+ agent: { type: 'string', description: 'Agent identifier.' },
1329
+ host: { type: 'string', description: 'Host name. Defaults to mcp.' },
1330
+ project: { type: 'string', description: 'Project name. Defaults to current directory name.' },
1331
+ },
1332
+ required: ['trace_id', 'event_type'],
1333
+ },
1334
+ },
1335
+ {
1336
+ name: 'mio.trace.query',
1337
+ description: 'Query the observer trace log (traces.jsonl): task outcomes, tool errors, and ingested events. Newest first, with counts by event_type and outcome over the full filtered set.',
1338
+ inputSchema: {
1339
+ type: 'object',
1340
+ properties: {
1341
+ event_type: { type: 'string', description: 'Filter by event type (e.g. task_outcome, error, tool_call).' },
1342
+ outcome: { type: 'string', description: 'Filter by outcome (success, failure, error, aborted).' },
1343
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository; pass empty string for all projects.' },
1344
+ agent: { type: 'string', description: 'Filter by agent identifier (e.g. codex, claude-code, cli).' },
1345
+ host: { type: 'string', description: 'Filter by host identifier.' },
1346
+ since: { type: 'string', description: 'Only traces at or after this time (ISO 8601 or epoch ms).' },
1347
+ until: { type: 'string', description: 'Only traces at or before this time (ISO 8601 or epoch ms).' },
1348
+ limit: { type: 'number', description: 'Maximum traces to return (1-200). Defaults to 20.' },
1349
+ include_payload: { type: 'boolean', description: 'Include full payload objects (default true). Set false for compact listings.' },
1350
+ },
1351
+ },
1352
+ },
1353
+ {
1354
+ name: 'mio.digest.generate',
1355
+ description: 'Generate an actionable digest from recent traces/memory/reuse data: task throughput and success rates per agent, project activity, error hotspots, reuse evidence, and rule-based suggestions. Returns the report object with a markdown field.',
1356
+ inputSchema: {
1357
+ type: 'object',
1358
+ properties: {
1359
+ days: { type: 'number', description: 'Look-back window in days. Defaults to 7.' },
1360
+ project: { type: 'string', description: 'Restrict the digest to one project. Defaults to all projects.' },
1361
+ },
1362
+ },
1363
+ },
1364
+ {
1365
+ name: 'mio.observer.subscribe',
1366
+ description: 'Subscribe to observer events (project, event types, optional topic). New matching events are delivered via mio.observer.digest.',
1367
+ inputSchema: {
1368
+ type: 'object',
1369
+ properties: {
1370
+ eventTypes: { type: 'array', items: { type: 'string' }, description: 'Event types to watch, e.g. error, retry, task_outcome. Empty means all.' },
1371
+ project: { type: 'string', description: 'Project name. Defaults to current repository.' },
1372
+ topic: { type: 'string', description: 'Optional keyword; only events whose payload mentions it match.' },
1373
+ ttlDays: { type: 'number', description: 'Subscription lifetime in days. Defaults to 30.' },
1374
+ },
1375
+ },
1376
+ },
1377
+ {
1378
+ name: 'mio.observer.digest',
1379
+ description: 'Return new observer events matching active subscriptions since the last digest, and advance the cursor.',
1380
+ inputSchema: {
1381
+ type: 'object',
1382
+ properties: {
1383
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1384
+ eventTypes: { type: 'array', items: { type: 'string' }, description: 'Optional extra event type filter.' },
1385
+ limit: { type: 'number', description: 'Maximum events to return, 1-100. Defaults to 20.' },
1386
+ },
1387
+ },
1388
+ },
1389
+ {
1390
+ name: 'mio.policy.check',
1391
+ description: 'Check historical risk for an action before executing it, returning risk level, outcome counts, and recent failure examples.',
1392
+ inputSchema: {
1393
+ type: 'object',
1394
+ properties: {
1395
+ action: { type: 'string', description: 'The action or tool operation to check.' },
1396
+ project: { type: 'string', description: 'Project name filter. Defaults to current directory name.' },
1397
+ context: { type: 'string', description: 'Optional additional context.' },
1398
+ },
1399
+ required: ['action'],
1400
+ },
1401
+ },
1402
+ {
1403
+ name: 'mio.memory.analyze',
1404
+ description: 'Analyze local Mio memory quality: kind distribution, duplicate groups, and low-quality records.',
1405
+ inputSchema: {
1406
+ type: 'object',
1407
+ properties: {
1408
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1409
+ limit: { type: 'number', description: 'Maximum duplicates/low-quality examples to return, 1-20. Defaults to 5.' },
1410
+ },
1411
+ },
1412
+ },
1413
+ {
1414
+ name: 'mio.experience.reuse',
1415
+ description: 'Record Phase 0 evidence of cross-agent experience reuse.',
1416
+ inputSchema: {
1417
+ type: 'object',
1418
+ properties: {
1419
+ sourceAgent: { type: 'string', description: 'Agent that produced the experience.' },
1420
+ targetAgent: { type: 'string', description: 'Agent that reused the experience.' },
1421
+ experienceId: { type: 'string', description: 'Stable experience or memory id.' },
1422
+ reuse: { type: 'boolean', description: 'True when memory.query returned historical experience and it was reused.' },
1423
+ behaviorChanged: { type: 'boolean', description: 'True when target Agent behavior changed because of the reused experience.' },
1424
+ outcomeImproved: { type: 'boolean', description: 'True when the task outcome improved.' },
1425
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1426
+ notes: { type: 'string', description: 'Optional evidence notes.' },
1427
+ },
1428
+ required: ['sourceAgent', 'targetAgent', 'experienceId', 'reuse', 'behaviorChanged', 'outcomeImproved'],
1429
+ },
1430
+ },
1431
+ {
1432
+ name: 'mio.experience.confirm',
1433
+ description: 'Confirm an auto-claimed reuse record as verified reuse evidence.',
1434
+ inputSchema: {
1435
+ type: 'object',
1436
+ properties: {
1437
+ id: { type: 'string', description: 'Id of the auto-claimed reuse record returned by mio.observer.ingest.' },
1438
+ confirmedBy: { type: 'string', description: 'Who confirmed the reuse: agent or human. Defaults to agent.' },
1439
+ outcomeImproved: { type: 'boolean', description: 'Override: true when the reused experience improved the task outcome. Defaults to the auto-claim value.' },
1440
+ notes: { type: 'string', description: 'Optional confirmation notes.' },
1441
+ },
1442
+ required: ['id'],
1443
+ },
1444
+ },
1445
+ {
1446
+ name: 'mio.experience.list',
1447
+ description: 'List Phase 0 experience reuse evidence, optionally filtered by status or target agent.',
1448
+ inputSchema: {
1449
+ type: 'object',
1450
+ properties: {
1451
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1452
+ status: { type: 'string', description: 'Filter: pending (auto-claim awaiting confirmation), confirmed, verified, auto_claim, agent_report, all. Defaults to all.' },
1453
+ targetAgent: { type: 'string', description: 'Filter records by target agent.' },
1454
+ limit: { type: 'number', description: 'Maximum records to return, 1-100. Defaults to 20.' },
1455
+ },
1456
+ },
1457
+ },
1458
+ {
1459
+ name: 'mio.phase0.report',
1460
+ description: 'Generate the current Phase 0 cross-agent validation report, as JSON or rendered Markdown.',
1461
+ inputSchema: {
1462
+ type: 'object',
1463
+ properties: {
1464
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1465
+ format: { type: 'string', description: 'Output format: json or markdown. Defaults to json.' },
1466
+ },
1467
+ },
1468
+ },
1469
+ {
1470
+ name: 'mio.task.route',
1471
+ description: 'Route an incoming task to the most relevant verified experiences and related memories, turning recall into decision influence (P1).',
1472
+ inputSchema: {
1473
+ type: 'object',
1474
+ properties: {
1475
+ task: { type: 'string', description: 'Task description to route, e.g. \'fix IPC communication bug\'.' },
1476
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1477
+ scope: { type: 'string', description: 'Search scope: project (default), global, or all.' },
1478
+ limit: { type: 'number', description: 'Maximum routes, between 1 and 10. Defaults to 5.' },
1479
+ },
1480
+ required: ['task'],
1481
+ },
1482
+ },
1483
+ {
1484
+ name: 'mio.agent.register',
1485
+ description: 'Register or update an agent in the Mio Agent Registry. Upserts by agentId+project; updates lastSeenAt and sessionCount.',
1486
+ inputSchema: {
1487
+ type: 'object',
1488
+ properties: {
1489
+ agentId: { type: 'string', description: 'Unique agent identifier (e.g. codex, opencode).' },
1490
+ hostType: { type: 'string', description: 'Host type: mcp, observer, or plugin. Defaults to mcp.' },
1491
+ capabilities: { type: 'array', items: { type: 'string' }, description: 'Agent capabilities.' },
1492
+ project: { type: 'string', description: 'Project name. Defaults to current directory name.' },
1493
+ },
1494
+ required: ['agentId'],
1495
+ },
1496
+ },
1497
+ {
1498
+ name: 'mio.agent.list',
1499
+ description: 'List all registered agents, optionally filtered by project.',
1500
+ inputSchema: {
1501
+ type: 'object',
1502
+ properties: {
1503
+ project: { type: 'string', description: 'Project name filter. Omit for all agents.' },
1504
+ },
1505
+ },
1506
+ },
1507
+ {
1508
+ name: 'mio.agent.report',
1509
+ description: 'Performance report for one or all agents, aggregating task outcomes, memory, and experience reuse.',
1510
+ inputSchema: {
1511
+ type: 'object',
1512
+ properties: {
1513
+ agentId: { type: 'string', description: 'Agent to report on. Omit for all agents.' },
1514
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1515
+ },
1516
+ },
1517
+ },
1599
1518
  {
1600
1519
  name: 'mio.evolution.report',
1601
1520
  description: 'Generate cross-agent evolution report: ecosystem summary, agent performance comparison, cross-agent patterns, memory health, and optimization suggestions (ADR-017 Evolution plane).',
1602
- inputSchema: {
1603
- type: 'object',
1604
- properties: {
1605
- project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1606
- period: { type: 'string', description: 'Time window: 24h, 7d, 30d, or all (default).' },
1607
- },
1521
+ inputSchema: {
1522
+ type: 'object',
1523
+ properties: {
1524
+ project: { type: 'string', description: 'Project name filter. Defaults to current repository.' },
1525
+ period: { type: 'string', description: 'Time window: 24h, 7d, 30d, or all (default).' },
1526
+ },
1608
1527
  },
1609
1528
  },
1610
1529
  {
@@ -1707,57 +1626,463 @@ const TOOLS = [
1707
1626
  name: 'mio.task.record_outcome',
1708
1627
  description: 'Record task outcome with agent registry update and auto-claim experience reuse in one atomic call. Combines observer.ingest + agent stats + auto-claim for a complete task lifecycle closure.',
1709
1628
  inputSchema: {
1710
- type: 'object',
1711
- properties: {
1712
- outcome: { type: 'string', description: 'Task outcome: success, failure, or aborted.' },
1713
- task: { type: 'string', description: 'Brief task description.' },
1714
- summary: { type: 'string', description: 'Optional task summary.' },
1715
- verification: { type: 'string', description: 'Optional verification details.' },
1716
- agentId: { type: 'string', description: 'Agent identifier. Defaults to MIO_CONTEXT agentId.' },
1717
- project: { type: 'string', description: 'Project name. Defaults to current repository.' },
1718
- traceId: { type: 'string', description: 'Optional custom trace ID. Auto-generated if omitted.' },
1719
- },
1720
- required: ['outcome'],
1721
- },
1722
- },
1723
- ]
1724
-
1725
- async function callTool(name, args = {}) {
1726
- switch (name) {
1727
- case 'mio.memory.query':
1728
- return queryMemory(args)
1729
- case 'mio.memory.record':
1730
- return recordMemory(args)
1731
- case 'mio.memory.archive':
1732
- return archiveMemory(args)
1733
- case 'mio.memory.migrate':
1734
- return migrateMemory(args)
1735
- case 'mio.observer.ingest':
1736
- return ingestObservation(args)
1737
- case 'mio.observer.subscribe':
1738
- return subscribeObserver(args)
1739
- case 'mio.observer.digest':
1740
- return observerDigest(args)
1741
- case 'mio.policy.check':
1742
- return policyCheck(args)
1743
- case 'mio.memory.analyze':
1744
- return analyzeMemory(args)
1745
- case 'mio.experience.reuse':
1746
- return recordExperienceReuse(args)
1747
- case 'mio.experience.confirm':
1748
- return confirmExperienceReuse(args)
1749
- case 'mio.experience.list':
1750
- return listExperienceReuse(args)
1751
- case 'mio.phase0.report':
1752
- return phase0Report(args)
1753
- case 'mio.task.route':
1754
- return routeTask(args)
1755
- case 'mio.agent.register':
1756
- return registerAgent(args)
1757
- case 'mio.agent.list':
1758
- return listAgents(args)
1759
- case 'mio.agent.report':
1760
- return reportAgent(args)
1629
+ type: 'object',
1630
+ properties: {
1631
+ outcome: { type: 'string', description: 'Task outcome: success, failure, or aborted.' },
1632
+ task: { type: 'string', description: 'Brief task description.' },
1633
+ summary: { type: 'string', description: 'Optional task summary.' },
1634
+ verification: { type: 'string', description: 'Optional verification details.' },
1635
+ agentId: { type: 'string', description: 'Agent identifier. Defaults to MIO_CONTEXT agentId.' },
1636
+ project: { type: 'string', description: 'Project name. Defaults to current repository.' },
1637
+ traceId: { type: 'string', description: 'Optional custom trace ID. Auto-generated if omitted.' },
1638
+ },
1639
+ required: ['outcome'],
1640
+ },
1641
+ },
1642
+ {
1643
+ name: 'mio.creativity.status',
1644
+ description: 'Show creativity engine status: hypothesis counts, active/validated/rejected, recent top ideas.',
1645
+ inputSchema: { type: 'object', properties: {} },
1646
+ },
1647
+ {
1648
+ name: 'mio.creativity.list',
1649
+ description: 'List creativity hypotheses with optional status filter.',
1650
+ inputSchema: {
1651
+ type: 'object',
1652
+ properties: {
1653
+ status: { type: 'string', description: 'Filter by status: active, validated, rejected, draft.' },
1654
+ limit: { type: 'number', description: 'Max results. Default 20.' },
1655
+ },
1656
+ },
1657
+ },
1658
+ {
1659
+ name: 'mio.creativity.generate',
1660
+ description: 'Generate new creative hypotheses by combining concept sources via LLM. Returns ideas with novelty/feasibility/impact scores.',
1661
+ inputSchema: {
1662
+ type: 'object',
1663
+ properties: {
1664
+ sources: {
1665
+ type: 'array',
1666
+ description: 'Concept sources to combine. Each has name, content, type (knowledge/behavior/insight/failure), weight.',
1667
+ items: {
1668
+ type: 'object',
1669
+ properties: {
1670
+ name: { type: 'string' },
1671
+ content: { type: 'string' },
1672
+ type: { type: 'string' },
1673
+ weight: { type: 'number' },
1674
+ },
1675
+ required: ['name', 'content'],
1676
+ },
1677
+ },
1678
+ strategy: { type: 'string', description: 'Generation strategy: explore (cross-domain), signal (provocative), stable (conservative). Auto-selected if omitted.' },
1679
+ },
1680
+ required: ['sources'],
1681
+ },
1682
+ },
1683
+ {
1684
+ name: 'mio.creativity.ferment',
1685
+ description: 'Ferment (review and refine) active hypotheses. Updates scores, can promote/reject ideas.',
1686
+ inputSchema: {
1687
+ type: 'object',
1688
+ properties: {
1689
+ limit: { type: 'number', description: 'Max hypotheses to ferment. Default 5.' },
1690
+ },
1691
+ },
1692
+ },
1693
+
1694
+ // ═══ Observer Research Pipeline ═══
1695
+
1696
+ // ═══ Insight Self-Observation ═══
1697
+
1698
+ ...(insightStore ? [{
1699
+ name: 'mio.insight.status',
1700
+ description: 'Get insight engine status: total insights, unreported count, cooldown.',
1701
+ inputSchema: { type: 'object', properties: {} },
1702
+ },
1703
+ {
1704
+ name: 'mio.insight.list',
1705
+ description: 'List stored insights with optional filters.',
1706
+ inputSchema: {
1707
+ type: 'object',
1708
+ properties: {
1709
+ unreported: { type: 'boolean', description: 'Only unreported insights' },
1710
+ minScore: { type: 'number', description: 'Minimum score filter' },
1711
+ detector: { type: 'string', description: 'Filter by detector name' },
1712
+ limit: { type: 'number', description: 'Max results (default 20)' },
1713
+ },
1714
+ },
1715
+ },
1716
+ {
1717
+ name: 'mio.insight.mark_reported',
1718
+ description: 'Mark insights as reported (acknowledged).',
1719
+ inputSchema: {
1720
+ type: 'object',
1721
+ properties: {
1722
+ ids: { type: 'array', items: { type: 'string' }, description: 'Insight IDs to mark' },
1723
+ },
1724
+ required: ['ids'],
1725
+ },
1726
+ },
1727
+ {
1728
+ name: 'mio.insight.generate',
1729
+ description: 'Run LLM-based insight generation from provided context data.',
1730
+ inputSchema: {
1731
+ type: 'object',
1732
+ properties: {
1733
+ memories: { type: 'array', items: { type: 'object' }, description: 'Memory entries to analyze' },
1734
+ summaries: { type: 'array', items: { type: 'string' }, description: 'Recent summaries' },
1735
+ plans: { type: 'array', items: { type: 'object' }, description: 'Active plans' },
1736
+ },
1737
+ },
1738
+ }] : []),
1739
+
1740
+ // ═══ Observer Research Pipeline ═══
1741
+
1742
+ ...(ObserverStore ? [{
1743
+ name: 'mio.observer.world_model',
1744
+ description: 'Query the Observer world model: entities, events, trends, narratives, uncertainties, and relations.',
1745
+ inputSchema: {
1746
+ type: 'object',
1747
+ properties: {
1748
+ baseDir: { type: 'string', description: 'Observer data directory (default: .local/observer)' },
1749
+ },
1750
+ },
1751
+ },
1752
+ {
1753
+ name: 'mio.observer.trends',
1754
+ description: 'Get recent trend reports from the Observer pipeline.',
1755
+ inputSchema: {
1756
+ type: 'object',
1757
+ properties: {
1758
+ date: { type: 'string', description: 'Specific date (YYYY-MM-DD) or null for latest' },
1759
+ limit: { type: 'number', description: 'Max reports to return (default 7)' },
1760
+ baseDir: { type: 'string', description: 'Observer data directory' },
1761
+ },
1762
+ },
1763
+ },
1764
+ {
1765
+ name: 'mio.observer.research',
1766
+ description: 'List recent deep research results from the Observer pipeline.',
1767
+ inputSchema: {
1768
+ type: 'object',
1769
+ properties: {
1770
+ limit: { type: 'number', description: 'Max results (default 10)' },
1771
+ baseDir: { type: 'string', description: 'Observer data directory' },
1772
+ },
1773
+ },
1774
+ },
1775
+ {
1776
+ name: 'mio.observer.insights',
1777
+ description: 'List Observer-generated insights (5-section structured articles).',
1778
+ inputSchema: {
1779
+ type: 'object',
1780
+ properties: {
1781
+ limit: { type: 'number', description: 'Max insights (default 20)' },
1782
+ baseDir: { type: 'string', description: 'Observer data directory' },
1783
+ },
1784
+ },
1785
+ },
1786
+ {
1787
+ name: 'mio.observer.status',
1788
+ description: 'Get Observer pipeline status: counts of observations, trends, topics, research, insights, essays, and world model entities.',
1789
+ inputSchema: {
1790
+ type: 'object',
1791
+ properties: {
1792
+ baseDir: { type: 'string', description: 'Observer data directory' },
1793
+ },
1794
+ },
1795
+ },
1796
+ {
1797
+ name: 'mio.observer.collect',
1798
+ description: 'Force data collection from all configured sources (RSS, Bilibili, HackerNews, GitHub, Douyin). Returns collected observations.',
1799
+ inputSchema: {
1800
+ type: 'object',
1801
+ properties: {
1802
+ sources: { type: 'array', items: { type: 'string' }, description: 'Specific sources to collect (default: all)' },
1803
+ keywords: { type: 'array', items: { type: 'string' }, description: 'Keyword filter (OR match)' },
1804
+ limit: { type: 'number', description: 'Max items per source (default 20)' },
1805
+ baseDir: { type: 'string', description: 'Observer data directory' },
1806
+ },
1807
+ },
1808
+ },
1809
+ {
1810
+ name: 'mio.observer.ferment',
1811
+ description: 'Run fermentation engine: find recurring themes across recent observations and optionally write an essay.',
1812
+ inputSchema: {
1813
+ type: 'object',
1814
+ properties: {
1815
+ session: { type: 'string', description: 'Session label: morning/afternoon/night (default: afternoon)' },
1816
+ baseDir: { type: 'string', description: 'Observer data directory' },
1817
+ },
1818
+ },
1819
+ },
1820
+ {
1821
+ name: 'mio.observer.essays',
1822
+ description: 'List published or draft essays from the Observer.',
1823
+ inputSchema: {
1824
+ type: 'object',
1825
+ properties: {
1826
+ type: { type: 'string', description: 'published or draft (default: published)' },
1827
+ limit: { type: 'number', description: 'Max essays (default 10)' },
1828
+ baseDir: { type: 'string', description: 'Observer data directory' },
1829
+ },
1830
+ },
1831
+ },
1832
+ {
1833
+ name: 'mio.observer.dag',
1834
+ description: 'Get DAG state machine status: today\'s task, recent summaries, retryable tasks.',
1835
+ inputSchema: {
1836
+ type: 'object',
1837
+ properties: {
1838
+ days: { type: 'number', description: 'Days to look back (default 7)' },
1839
+ baseDir: { type: 'string', description: 'Observer data directory' },
1840
+ },
1841
+ },
1842
+ }] : []),
1843
+ ]
1844
+
1845
+ // ═══ Insight Self-Observation Handlers ═══
1846
+
1847
+ function insightStatus() {
1848
+ if (!insightStore) throw new Error('@akemi-mio/insight not installed')
1849
+ const all = insightStore.getAll()
1850
+ const unreported = insightStore.getUnreported()
1851
+ return {
1852
+ total: all.length,
1853
+ unreported: unreported.length,
1854
+ reported: all.length - unreported.length,
1855
+ highValue: insightStore.getHighValueUnreported(50, 0.7).length,
1856
+ }
1857
+ }
1858
+
1859
+ function insightList(args = {}) {
1860
+ if (!insightStore) throw new Error('@akemi-mio/insight not installed')
1861
+ let insights = insightStore.getAll()
1862
+ if (args.unreported) insights = insightStore.getUnreported()
1863
+ if (args.minScore) insights = insights.filter(i => i.score >= args.minScore)
1864
+ if (args.detector) insights = insights.filter(i => i.detector === args.detector)
1865
+ if (args.limit) insights = insights.slice(-args.limit)
1866
+ return insights
1867
+ }
1868
+
1869
+ function insightMarkReported(args = {}) {
1870
+ if (!insightStore) throw new Error('@akemi-mio/insight not installed')
1871
+ if (!args.ids || !Array.isArray(args.ids)) throw new Error('ids array required')
1872
+ for (const id of args.ids) insightStore.markReported(id)
1873
+ return { marked: args.ids.length }
1874
+ }
1875
+
1876
+ async function insightGenerate(args = {}) {
1877
+ if (!InsightGenerator) throw new Error('@akemi-mio/insight not installed')
1878
+ const generator = new InsightGenerator({ chatJson })
1879
+ const ctx = {
1880
+ memoryEntries: (args.memories || []).map(m => ({
1881
+ type: m.kind || m.type || 'note',
1882
+ content: m.content || '',
1883
+ createdAt: m.createdAt || m.timestamp || Date.now(),
1884
+ })),
1885
+ summaries: args.summaries || [],
1886
+ interactionCount: 0,
1887
+ plans: (args.plans || []).map(p => ({
1888
+ title: p.title || p.name || '',
1889
+ status: p.status || 'unknown',
1890
+ updatedAt: p.updatedAt || Date.now(),
1891
+ steps: p.steps || [],
1892
+ createdAt: p.createdAt || Date.now(),
1893
+ })),
1894
+ eventCount: 0,
1895
+ }
1896
+ const insights = await generator.generate(ctx)
1897
+ if (insightStore) {
1898
+ for (const i of insights) insightStore.addMany([i])
1899
+ }
1900
+ return { generated: insights.length, insights }
1901
+ }
1902
+
1903
+ // ═══ Observer Research Pipeline Handlers ═══
1904
+
1905
+ function getObserverStore(baseDir) {
1906
+ if (!ObserverStore) throw new Error('@akemi-mio/observer not installed')
1907
+ return new ObserverStore(baseDir || path.join(process.cwd(), '.local', 'observer'))
1908
+ }
1909
+
1910
+ function getObserverBaseDir(args) {
1911
+ return args.baseDir || path.join(process.cwd(), '.local', 'observer')
1912
+ }
1913
+
1914
+ function readJsonSafe(filePath) {
1915
+ if (!fs.existsSync(filePath)) return null
1916
+ try { return JSON.parse(fs.readFileSync(filePath, 'utf8')) } catch { return null }
1917
+ }
1918
+
1919
+ function readJsonlSafe(filePath) {
1920
+ if (!fs.existsSync(filePath)) return []
1921
+ try {
1922
+ return fs.readFileSync(filePath, 'utf8').trim().split('\n').filter(Boolean)
1923
+ .map(l => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
1924
+ } catch { return [] }
1925
+ }
1926
+
1927
+ function observerWorldModel(args = {}) {
1928
+ const baseDir = getObserverBaseDir(args)
1929
+ const wmDir = path.join(baseDir, 'world_model')
1930
+ return {
1931
+ entities: readJsonSafe(path.join(wmDir, 'entities.json')) || [],
1932
+ events: readJsonSafe(path.join(wmDir, 'events.json')) || [],
1933
+ trends: readJsonSafe(path.join(wmDir, 'trends.json')) || [],
1934
+ narratives: readJsonSafe(path.join(wmDir, 'narratives.json')) || [],
1935
+ }
1936
+ }
1937
+
1938
+ function observerTrends(args = {}) {
1939
+ const baseDir = getObserverBaseDir(args)
1940
+ const trendsDir = path.join(baseDir, 'trends')
1941
+ if (!fs.existsSync(trendsDir)) return []
1942
+ if (args.date) {
1943
+ const report = readJsonSafe(path.join(trendsDir, `${args.date}.json`))
1944
+ return report ? [report] : []
1945
+ }
1946
+ const files = fs.readdirSync(trendsDir).filter(f => f.endsWith('.json')).sort().reverse()
1947
+ return files.slice(0, args.limit || 7).map(f => readJsonSafe(path.join(trendsDir, f))).filter(Boolean)
1948
+ }
1949
+
1950
+ function observerResearch(args = {}) {
1951
+ const baseDir = getObserverBaseDir(args)
1952
+ const researchDir = path.join(baseDir, 'research')
1953
+ if (!fs.existsSync(researchDir)) return []
1954
+ const files = fs.readdirSync(researchDir).filter(f => f.endsWith('.json')).sort().reverse()
1955
+ return files.slice(0, args.limit || 10).map(f => readJsonSafe(path.join(researchDir, f))).filter(Boolean)
1956
+ }
1957
+
1958
+ function observerInsights(args = {}) {
1959
+ const baseDir = getObserverBaseDir(args)
1960
+ const insightsDir = path.join(baseDir, 'insights')
1961
+ if (!fs.existsSync(insightsDir)) return []
1962
+ const files = fs.readdirSync(insightsDir).filter(f => f.endsWith('.json')).sort().reverse()
1963
+ return files.slice(0, args.limit || 20).map(f => readJsonSafe(path.join(insightsDir, f))).filter(Boolean)
1964
+ }
1965
+
1966
+ function observerStatus(args = {}) {
1967
+ const baseDir = getObserverBaseDir(args)
1968
+ const dirs = ['observations', 'trends', 'topics', 'research', 'insights', 'world_model', 'essays']
1969
+ const status = {}
1970
+ for (const d of dirs) {
1971
+ const dir = path.join(baseDir, d)
1972
+ if (fs.existsSync(dir)) {
1973
+ status[d] = fs.readdirSync(dir).filter(f => !f.startsWith('.')).length
1974
+ } else {
1975
+ status[d] = 0
1976
+ }
1977
+ }
1978
+ return status
1979
+ }
1980
+
1981
+ function observerCollect(args = {}) {
1982
+ if (!ObserverService) throw new Error('@akemi-mio/observer not installed')
1983
+ const baseDir = getObserverBaseDir(args)
1984
+ const service = new ObserverService({ baseDir, collectorConfig: {} })
1985
+ const sources = args.sources || ['bilibili', 'hackernews', 'github', 'douyin', 'rss']
1986
+ const allObs = []
1987
+ for (const src of sources) {
1988
+ try {
1989
+ const collectFn = service.collectBySource ? service.collectBySource : service.collect
1990
+ if (collectFn) {
1991
+ const result = collectFn.call(service, [src], args.keywords || [], args.limit || 20)
1992
+ if (Array.isArray(result)) allObs.push(...result)
1993
+ else if (result && typeof result === 'object') {
1994
+ for (const [key, items] of Object.entries(result)) allObs.push(...items)
1995
+ }
1996
+ }
1997
+ } catch (e) {
1998
+ allObs.push({ source: src, error: e.message })
1999
+ }
2000
+ }
2001
+ return { collected: allObs.length, observations: allObs }
2002
+ }
2003
+
2004
+ function observerFerment(args = {}) {
2005
+ if (!ObserverService) throw new Error('@akemi-mio/observer not installed')
2006
+ const baseDir = getObserverBaseDir(args)
2007
+ const service = new ObserverService({ baseDir, collectorConfig: {} })
2008
+ const session = args.session || 'afternoon'
2009
+ try {
2010
+ const fermentation = service.getFermentation()
2011
+ if (fermentation && fermentation.ferment) return fermentation.ferment(session)
2012
+ return { status: 'fermentation engine available but no ferment method' }
2013
+ } catch (e) {
2014
+ return { error: e.message }
2015
+ }
2016
+ }
2017
+
2018
+ function observerEssays(args = {}) {
2019
+ const baseDir = getObserverBaseDir(args)
2020
+ const type = args.type || 'published'
2021
+ const essaysDir = path.join(baseDir, 'essays', type)
2022
+ if (!fs.existsSync(essaysDir)) return []
2023
+ const files = fs.readdirSync(essaysDir).filter(f => f.endsWith('.md')).sort().reverse()
2024
+ return files.slice(0, args.limit || 10).map(f => {
2025
+ const content = fs.readFileSync(path.join(essaysDir, f), 'utf8')
2026
+ return { file: f, type, content, created: fs.statSync(path.join(essaysDir, f)).birthtime.toISOString() }
2027
+ })
2028
+ }
2029
+
2030
+ function observerDag(args = {}) {
2031
+ const baseDir = getObserverBaseDir(args)
2032
+ const days = args.days || 7
2033
+ const summaries = []
2034
+ const todayDate = new Date()
2035
+ for (let i = 0; i < days; i++) {
2036
+ const d = new Date(todayDate)
2037
+ d.setDate(d.getDate() - i)
2038
+ const dateStr = d.toISOString().slice(0, 10)
2039
+ const filePath = path.join(baseDir, 'summaries', `${dateStr}.jsonl`)
2040
+ const items = readJsonlSafe(filePath)
2041
+ if (items.length) summaries.push({ date: dateStr, summaries: items })
2042
+ }
2043
+ return { summaries, summaryCount: summaries.reduce((a, s) => a + s.summaries.length, 0) }
2044
+ }
2045
+
2046
+ async function callTool(name, args = {}) {
2047
+ switch (name) {
2048
+ case 'mio.memory.query':
2049
+ return queryMemory(args)
2050
+ case 'mio.memory.record':
2051
+ return recordMemory(args)
2052
+ case 'mio.memory.archive':
2053
+ return archiveMemory(args)
2054
+ case 'mio.memory.migrate':
2055
+ return migrateMemory(args)
2056
+ case 'mio.observer.ingest':
2057
+ return ingestObservation(args)
2058
+ case 'mio.observer.subscribe':
2059
+ return subscribeObserver(args)
2060
+ case 'mio.observer.digest':
2061
+ return observerDigest(args)
2062
+ case 'mio.digest.generate':
2063
+ return digestEngine.generate({ days: args.days, project: args.project })
2064
+ case 'mio.trace.query':
2065
+ return queryTraces(args)
2066
+ case 'mio.policy.check':
2067
+ return policyCheck(args)
2068
+ case 'mio.memory.analyze':
2069
+ return analyzeMemory(args)
2070
+ case 'mio.experience.reuse':
2071
+ return recordExperienceReuse(args)
2072
+ case 'mio.experience.confirm':
2073
+ return confirmExperienceReuse(args)
2074
+ case 'mio.experience.list':
2075
+ return listExperienceReuse(args)
2076
+ case 'mio.phase0.report':
2077
+ return phase0Report(args)
2078
+ case 'mio.task.route':
2079
+ return routeTask(args)
2080
+ case 'mio.agent.register':
2081
+ return registerAgent(args)
2082
+ case 'mio.agent.list':
2083
+ return listAgents(args)
2084
+ case 'mio.agent.report':
2085
+ return reportAgent(args)
1761
2086
  case 'mio.evolution.report':
1762
2087
  return evolutionReport(args)
1763
2088
  case 'mio.evolution.status':
@@ -1778,323 +2103,357 @@ async function callTool(name, args = {}) {
1778
2103
  return evolutionCutover.applyCutover(args)
1779
2104
  case 'mio.task.record_outcome':
1780
2105
  return recordTaskOutcome(args)
1781
- default:
1782
- throw new Error(`Unknown tool: ${name}`)
1783
- }
1784
- }
1785
-
1786
- function jsonRpcResult(id, result) {
1787
- return { jsonrpc: '2.0', id, result }
1788
- }
1789
-
1790
- function jsonRpcError(id, code, message, data) {
1791
- const error = { code, message }
1792
- if (data !== undefined) error.data = data
1793
- return { jsonrpc: '2.0', id, error }
1794
- }
1795
-
1796
- function send(message) {
1797
- if (message) process.stdout.write(`${JSON.stringify(message)}\n`)
1798
- }
1799
-
1800
- async function handleMessage(message) {
1801
- if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return
1802
- if (message.method && message.method.startsWith('notifications/')) return
1803
- if (message.id === undefined) return
1804
-
1805
- try {
1806
- if (message.method === 'initialize') {
1807
- send(
1808
- jsonRpcResult(message.id, {
1809
- protocolVersion: PROTOCOL_VERSION,
1810
- capabilities: { tools: {} },
1811
- serverInfo: SERVER_INFO,
1812
- })
1813
- )
1814
- return
1815
- }
1816
- if (message.method === 'ping') {
1817
- send(jsonRpcResult(message.id, {}))
1818
- return
1819
- }
1820
- if (message.method === 'tools/list') {
1821
- send(jsonRpcResult(message.id, { tools: TOOLS }))
1822
- return
1823
- }
1824
- if (message.method === 'tools/call') {
1825
- const name = message.params && message.params.name
1826
- const args = (message.params && message.params.arguments) || {}
1827
- const result = await callTool(name, args)
1828
- send(
1829
- jsonRpcResult(message.id, {
1830
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
1831
- isError: false,
1832
- })
1833
- )
1834
- return
1835
- }
1836
- send(jsonRpcError(message.id, -32601, `Method not found: ${message.method}`))
1837
- } catch (error) {
1838
- send(jsonRpcError(message.id, -32603, error.message || String(error)))
1839
- }
1840
- }
1841
-
1842
- const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity })
1843
-
1844
- rl.on('line', (line) => {
1845
- let message
1846
- try {
1847
- message = JSON.parse(line)
1848
- } catch (_) {
1849
- return
1850
- }
1851
- handleMessage(message).catch((error) => {
1852
- send(jsonRpcError(message && message.id, -32603, error.message || String(error)))
1853
- })
1854
- })
1855
-
1856
- rl.on('close', () => {
1857
- if (require.main === module) {
1858
- process.exit(0)
1859
- }
1860
- })
1861
-
1862
-
1863
- function evolutionReport(args = {}) {
1864
- const project = args.project || projectName()
1865
- const period = String(args.period || 'all').trim()
1866
- const now = Date.now()
1867
- const periodMs = period === '24h' ? 86400000 : period === '7d' ? 604800000 : period === '30d' ? 2592000000 : Infinity
1868
- const cutoff = periodMs === Infinity ? 0 : now - periodMs
1869
-
1870
- const memories = readJsonl(memoryPath).filter((m) => !project || m.project === project || !m.project)
1871
- const traces = readJsonl(tracePath).filter((t) => !project || t.project === project)
1872
- const reuses = readJsonl(experienceReusePath).filter((r) => !project || r.project === project)
1873
- const agents = readJsonl(agentsPath).filter((a) => !project || a.project === project)
1874
- const queries = readJsonl(queryPath).filter((q) => !project || q.project === project)
1875
-
1876
- const filteredTraces = cutoff ? traces.filter((t) => new Date(t.timestamp).getTime() >= cutoff) : traces
1877
- const filteredMemories = cutoff ? memories.filter((m) => new Date(m.timestamp).getTime() >= cutoff) : memories
1878
-
1879
- // Ecosystem summary
1880
- const agentIds = new Set()
1881
- filteredTraces.forEach((t) => { if (t.agent) agentIds.add(t.agent) })
1882
- agents.forEach((a) => agentIds.add(a.agentId))
1883
- const outcomes = filteredTraces.filter((t) => t.event_type === 'task_outcome')
1884
- const successes = outcomes.filter((t) => t.outcome === 'success').length
1885
- const failures = outcomes.filter((t) => t.outcome === 'failure').length
1886
- const verifiedReuses = reuses.filter((r) => r.confirmed && r.reuse && r.behaviorChanged && r.outcomeImproved)
1887
- const pendingReuses = reuses.filter((r) => r.source === 'auto_claim' && !r.confirmed)
1888
-
1889
- const ecosystem = {
1890
- agents: agentIds.size,
1891
- totalTasks: outcomes.length,
1892
- successRate: outcomes.length > 0 ? Math.round((successes / outcomes.length) * 100) : 0,
1893
- totalMemories: filteredMemories.length,
1894
- totalReuses: reuses.length,
1895
- verifiedReuses: verifiedReuses.length,
1896
- pendingReuses: pendingReuses.length,
1897
- }
1898
-
1899
- // Agent performance comparison
1900
- const agentPerf = []
1901
- for (const agentId of agentIds) {
1902
- const agentTraces = filteredTraces.filter((t) => t.agent === agentId)
1903
- const agentOutcomes = agentTraces.filter((t) => t.event_type === 'task_outcome')
1904
- const agentSuccesses = agentOutcomes.filter((t) => t.outcome === 'success').length
1905
- const agentFailures = agentOutcomes.filter((t) => t.outcome === 'failure').length
1906
- const agentMemories = filteredMemories.filter((m) => m.source === agentId)
1907
- const agentVerified = reuses.filter((r) =>
1908
- (r.sourceAgent === agentId || r.targetAgent === agentId) && r.confirmed && r.reuse && r.behaviorChanged && r.outcomeImproved
1909
- )
1910
- const reg = agents.find((a) => a.agentId === agentId)
1911
- agentPerf.push({
1912
- agentId,
1913
- tasks: {
1914
- total: agentOutcomes.length,
1915
- success: agentSuccesses,
1916
- failure: agentFailures,
1917
- successRate: agentOutcomes.length > 0 ? Math.round((agentSuccesses / agentOutcomes.length) * 100) : 0,
1918
- },
1919
- memories: agentMemories.length,
1920
- verifiedReuses: agentVerified.length,
1921
- registered: !!reg,
1922
- lastActive: reg ? reg.lastSeenAt : (agentTraces.length > 0 ? agentTraces[agentTraces.length - 1].timestamp : null),
1923
- })
1924
- }
1925
- agentPerf.sort((a, b) => b.tasks.successRate - a.tasks.successRate || b.tasks.total - a.tasks.total)
1926
-
1927
- // Cross-agent patterns
1928
- const crossPatterns = []
1929
- const reuseByPair = {}
1930
- for (const r of reuses) {
1931
- const key = r.sourceAgent + '->' + r.targetAgent
1932
- if (!reuseByPair[key]) reuseByPair[key] = { source: r.sourceAgent, target: r.targetAgent, total: 0, verified: 0, improved: 0 }
1933
- reuseByPair[key].total++
1934
- if (r.confirmed) reuseByPair[key].verified++
1935
- if (r.outcomeImproved) reuseByPair[key].improved++
1936
- }
1937
- for (const [key, pair] of Object.entries(reuseByPair)) {
1938
- if (pair.source !== pair.target) {
1939
- crossPatterns.push({
1940
- type: 'reuse_path',
1941
- from: pair.source,
1942
- to: pair.target,
1943
- total: pair.total,
1944
- verified: pair.verified,
1945
- improved: pair.improved,
1946
- })
1947
- }
1948
- }
1949
- crossPatterns.sort((a, b) => b.verified - a.verified || b.total - a.total)
1950
-
1951
- // Memory health
1952
- const byKind = {}
1953
- let shortContent = 0
1954
- let missingKind = 0
1955
- for (const m of filteredMemories) {
1956
- const kind = m.kind || 'unknown'
1957
- byKind[kind] = (byKind[kind] || 0) + 1
1958
- const content = String(m.content || '').trim()
1959
- if (content.length < 20) shortContent++
1960
- if (!m.kind) missingKind++
1961
- }
1962
- const memoryHealth = {
1963
- total: filteredMemories.length,
1964
- byKind,
1965
- shortContent,
1966
- missingKind,
1967
- qualityScore: filteredMemories.length > 0
1968
- ? Math.round(((filteredMemories.length - shortContent - missingKind) / filteredMemories.length) * 100)
1969
- : 100,
1970
- }
1971
-
1972
- // Suggestions engine
1973
- const suggestions = []
1974
-
1975
- // Routing suggestion: compare agent success rates
1976
- if (agentPerf.length >= 2) {
1977
- const best = agentPerf[0]
1978
- const worst = agentPerf[agentPerf.length - 1]
1979
- if (best.tasks.total >= 5 && worst.tasks.total >= 5 && best.tasks.successRate - worst.tasks.successRate >= 15) {
1980
- suggestions.push({
1981
- category: 'routing',
1982
- priority: 'high',
1983
- description: best.agentId + ' has ' + best.tasks.successRate + '% success rate vs ' + worst.agentId + ' at ' + worst.tasks.successRate + '%; prefer routing to ' + best.agentId,
1984
- basedOn: 'task_outcome comparison',
1985
- })
1986
- }
1987
- }
1988
-
1989
- // Pending auto-claim suggestion
1990
- if (pendingReuses.length >= 10) {
1991
- suggestions.push({
1992
- category: 'evidence',
1993
- priority: 'medium',
1994
- description: pendingReuses.length + ' pending auto-claims awaiting confirmation; review cross-agent claims to increase verified reuse count',
1995
- basedOn: 'experience_reuse.jsonl',
1996
- })
1997
- }
1998
-
1999
- // Memory quality suggestion
2000
- if (memoryHealth.qualityScore < 80 && filteredMemories.length > 10) {
2001
- suggestions.push({
2002
- category: 'memory',
2003
- priority: 'medium',
2004
- description: 'Memory quality score is ' + memoryHealth.qualityScore + '%; ' + shortContent + ' short records and ' + missingKind + ' missing kind fields found',
2005
- basedOn: 'memory.jsonl quality analysis',
2006
- })
2007
- }
2008
-
2009
- // Cross-agent value suggestion
2010
- if (crossPatterns.length === 0 && agentIds.size >= 2) {
2011
- suggestions.push({
2012
- category: 'interop',
2013
- priority: 'high',
2014
- description: 'Multiple agents registered but no cross-agent reuse patterns detected; ensure agents query shared memory',
2015
- basedOn: 'experience_reuse.jsonl',
2016
- })
2017
- }
2018
-
2019
- // Active agent suggestion
2020
- const inactiveAgents = agentPerf.filter((a) => {
2021
- if (!a.lastActive) return false
2022
- return (now - new Date(a.lastActive).getTime()) > 7 * 86400000
2023
- })
2024
- if (inactiveAgents.length > 0) {
2025
- suggestions.push({
2026
- category: 'coverage',
2027
- priority: 'low',
2028
- description: inactiveAgents.map((a) => a.agentId).join(', ') + ' inactive for >7 days; consider removal or reactivation',
2029
- basedOn: 'agent registry lastSeenAt',
2030
- })
2031
- }
2032
-
2033
- suggestions.sort((a, b) => {
2034
- const p = { high: 0, medium: 1, low: 2 }
2035
- return (p[a.priority] || 2) - (p[b.priority] || 2)
2036
- })
2037
-
2038
- return {
2039
- project,
2040
- generatedAt: new Date().toISOString(),
2041
- period,
2042
- ecosystem,
2043
- agentPerformance: agentPerf,
2044
- crossAgentPatterns: crossPatterns,
2045
- memoryHealth,
2046
- suggestions,
2047
- }
2048
- }
2049
-
2050
-
2051
- function recordTaskOutcome(args = {}) {
2052
- const outcome = String(args.outcome || '').trim().toLowerCase()
2053
- if (!['success', 'failure', 'aborted'].includes(outcome)) {
2054
- throw new Error('task.record_outcome requires outcome to be success, failure, or aborted')
2055
- }
2056
- const agentId = String(args.agentId || runtimeAgentId() || 'unknown').trim()
2057
- const project = args.project || projectName()
2058
- const task = String(args.task || '').trim()
2059
- const summary = String(args.summary || '').trim()
2060
- const verification = String(args.verification || '').trim()
2061
- const traceId = String(args.traceId || '').trim() || createId('trace:' + agentId + ':' + project)
2062
-
2063
- // 1. Record trace event
2064
- const event = {
2065
- id: createId('trace'),
2066
- timestamp: new Date().toISOString(),
2067
- trace_id: traceId,
2068
- event_type: 'task_outcome',
2069
- outcome,
2070
- payload: { task, summary, verification },
2071
- agent: agentId,
2072
- host: 'mcp',
2073
- project,
2074
- }
2075
- appendJsonl(tracePath, event)
2076
-
2077
- // 2. Auto-claim experience reuse
2078
- const autoClaims = autoClaimExperienceReuse(event)
2079
-
2080
- // 3. Update agent registry
2081
- const now = new Date().toISOString()
2082
- const agents = readJsonl(agentsPath)
2083
- const agent = agents.find((a) => a.agentId === agentId && a.project === project)
2084
- if (agent) {
2085
- agent.lastSeenAt = now
2086
- agent.taskCount = (agent.taskCount || 0) + 1
2087
- agent.successCount = (agent.successCount || 0) + (outcome === 'success' ? 1 : 0)
2088
- agent.failureCount = (agent.failureCount || 0) + (outcome === 'failure' ? 1 : 0)
2089
- writeJsonl(agentsPath, agents)
2090
- }
2091
-
2092
- return {
2093
- recorded: true,
2094
- event: { id: event.id, trace_id: traceId, outcome, agent: agentId, project },
2095
- agentUpdated: !!agent,
2096
- autoClaims: autoClaims.length > 0 ? autoClaims : undefined,
2097
- }
2098
- }
2099
-
2100
- module.exports = { TOOLS, callTool, handleMessage, readJsonl, appendJsonl, rl }
2106
+ case 'mio.creativity.status':
2107
+ return creativityEngine.status()
2108
+ case 'mio.creativity.list':
2109
+ return creativityEngine.list(args)
2110
+ case 'mio.creativity.generate':
2111
+ return creativityEngine.generate(args.sources, args.strategy)
2112
+ case 'mio.creativity.ferment':
2113
+ return creativityEngine.ferment(args.limit)
2114
+ case 'mio.insight.status':
2115
+ return insightStatus()
2116
+ case 'mio.insight.list':
2117
+ return insightList(args)
2118
+ case 'mio.insight.mark_reported':
2119
+ return insightMarkReported(args)
2120
+ case 'mio.insight.generate':
2121
+ return insightGenerate(args)
2122
+ case 'mio.observer.world_model':
2123
+ return observerWorldModel(args)
2124
+ case 'mio.observer.trends':
2125
+ return observerTrends(args)
2126
+ case 'mio.observer.research':
2127
+ return observerResearch(args)
2128
+ case 'mio.observer.insights':
2129
+ return observerInsights(args)
2130
+ case 'mio.observer.status':
2131
+ return observerStatus(args)
2132
+ case 'mio.observer.collect':
2133
+ return observerCollect(args)
2134
+ case 'mio.observer.ferment':
2135
+ return observerFerment(args)
2136
+ case 'mio.observer.essays':
2137
+ return observerEssays(args)
2138
+ case 'mio.observer.dag':
2139
+ return observerDag(args)
2140
+ default:
2141
+ throw new Error(`Unknown tool: ${name}`)
2142
+ }
2143
+ }
2144
+
2145
+ function jsonRpcResult(id, result) {
2146
+ return { jsonrpc: '2.0', id, result }
2147
+ }
2148
+
2149
+ function jsonRpcError(id, code, message, data) {
2150
+ const error = { code, message }
2151
+ if (data !== undefined) error.data = data
2152
+ return { jsonrpc: '2.0', id, error }
2153
+ }
2154
+
2155
+ function send(message) {
2156
+ if (message) process.stdout.write(`${JSON.stringify(message)}\n`)
2157
+ }
2158
+
2159
+ async function handleMessage(message) {
2160
+ if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return
2161
+ if (message.method && message.method.startsWith('notifications/')) return
2162
+ if (message.id === undefined) return
2163
+
2164
+ try {
2165
+ if (message.method === 'initialize') {
2166
+ send(
2167
+ jsonRpcResult(message.id, {
2168
+ protocolVersion: PROTOCOL_VERSION,
2169
+ capabilities: { tools: {} },
2170
+ serverInfo: SERVER_INFO,
2171
+ })
2172
+ )
2173
+ return
2174
+ }
2175
+ if (message.method === 'ping') {
2176
+ send(jsonRpcResult(message.id, {}))
2177
+ return
2178
+ }
2179
+ if (message.method === 'tools/list') {
2180
+ send(jsonRpcResult(message.id, { tools: TOOLS }))
2181
+ return
2182
+ }
2183
+ if (message.method === 'tools/call') {
2184
+ const name = message.params && message.params.name
2185
+ const args = (message.params && message.params.arguments) || {}
2186
+ const result = await callTool(name, args)
2187
+ send(
2188
+ jsonRpcResult(message.id, {
2189
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
2190
+ isError: false,
2191
+ })
2192
+ )
2193
+ return
2194
+ }
2195
+ send(jsonRpcError(message.id, -32601, `Method not found: ${message.method}`))
2196
+ } catch (error) {
2197
+ send(jsonRpcError(message.id, -32603, error.message || String(error)))
2198
+ }
2199
+ }
2200
+
2201
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity })
2202
+
2203
+ rl.on('line', (line) => {
2204
+ let message
2205
+ try {
2206
+ message = JSON.parse(line)
2207
+ } catch (_) {
2208
+ return
2209
+ }
2210
+ handleMessage(message).catch((error) => {
2211
+ send(jsonRpcError(message && message.id, -32603, error.message || String(error)))
2212
+ })
2213
+ })
2214
+
2215
+ rl.on('close', () => {
2216
+ if (require.main === module) {
2217
+ process.exit(0)
2218
+ }
2219
+ })
2220
+
2221
+
2222
+ function evolutionReport(args = {}) {
2223
+ const project = args.project || projectName()
2224
+ const period = String(args.period || 'all').trim()
2225
+ const now = Date.now()
2226
+ const periodMs = period === '24h' ? 86400000 : period === '7d' ? 604800000 : period === '30d' ? 2592000000 : Infinity
2227
+ const cutoff = periodMs === Infinity ? 0 : now - periodMs
2228
+
2229
+ const memories = readJsonl(memoryPath).filter((m) => !project || m.project === project || !m.project)
2230
+ const traces = readJsonl(tracePath).filter((t) => !project || t.project === project)
2231
+ const reuses = readJsonl(experienceReusePath).filter((r) => !project || r.project === project)
2232
+ const agents = readJsonl(agentsPath).filter((a) => !project || a.project === project)
2233
+ const queries = readJsonl(queryPath).filter((q) => !project || q.project === project)
2234
+
2235
+ const filteredTraces = cutoff ? traces.filter((t) => new Date(t.timestamp).getTime() >= cutoff) : traces
2236
+ const filteredMemories = cutoff ? memories.filter((m) => new Date(m.timestamp).getTime() >= cutoff) : memories
2237
+
2238
+ // Ecosystem summary
2239
+ const agentIds = new Set()
2240
+ filteredTraces.forEach((t) => { if (t.agent) agentIds.add(t.agent) })
2241
+ agents.forEach((a) => agentIds.add(a.agentId))
2242
+ const outcomes = filteredTraces.filter((t) => t.event_type === 'task_outcome')
2243
+ const successes = outcomes.filter((t) => t.outcome === 'success').length
2244
+ const failures = outcomes.filter((t) => t.outcome === 'failure').length
2245
+ const verifiedReuses = reuses.filter((r) => r.confirmed && r.reuse && r.behaviorChanged && r.outcomeImproved)
2246
+ const pendingReuses = reuses.filter((r) => r.source === 'auto_claim' && !r.confirmed)
2247
+
2248
+ const ecosystem = {
2249
+ agents: agentIds.size,
2250
+ totalTasks: outcomes.length,
2251
+ successRate: outcomes.length > 0 ? Math.round((successes / outcomes.length) * 100) : 0,
2252
+ totalMemories: filteredMemories.length,
2253
+ totalReuses: reuses.length,
2254
+ verifiedReuses: verifiedReuses.length,
2255
+ pendingReuses: pendingReuses.length,
2256
+ }
2257
+
2258
+ // Agent performance comparison
2259
+ const agentPerf = []
2260
+ for (const agentId of agentIds) {
2261
+ const agentTraces = filteredTraces.filter((t) => t.agent === agentId)
2262
+ const agentOutcomes = agentTraces.filter((t) => t.event_type === 'task_outcome')
2263
+ const agentSuccesses = agentOutcomes.filter((t) => t.outcome === 'success').length
2264
+ const agentFailures = agentOutcomes.filter((t) => t.outcome === 'failure').length
2265
+ const agentMemories = filteredMemories.filter((m) => m.source === agentId)
2266
+ const agentVerified = reuses.filter((r) =>
2267
+ (r.sourceAgent === agentId || r.targetAgent === agentId) && r.confirmed && r.reuse && r.behaviorChanged && r.outcomeImproved
2268
+ )
2269
+ const reg = agents.find((a) => a.agentId === agentId)
2270
+ agentPerf.push({
2271
+ agentId,
2272
+ tasks: {
2273
+ total: agentOutcomes.length,
2274
+ success: agentSuccesses,
2275
+ failure: agentFailures,
2276
+ successRate: agentOutcomes.length > 0 ? Math.round((agentSuccesses / agentOutcomes.length) * 100) : 0,
2277
+ },
2278
+ memories: agentMemories.length,
2279
+ verifiedReuses: agentVerified.length,
2280
+ registered: !!reg,
2281
+ lastActive: reg ? reg.lastSeenAt : (agentTraces.length > 0 ? agentTraces[agentTraces.length - 1].timestamp : null),
2282
+ })
2283
+ }
2284
+ agentPerf.sort((a, b) => b.tasks.successRate - a.tasks.successRate || b.tasks.total - a.tasks.total)
2285
+
2286
+ // Cross-agent patterns
2287
+ const crossPatterns = []
2288
+ const reuseByPair = {}
2289
+ for (const r of reuses) {
2290
+ const key = r.sourceAgent + '->' + r.targetAgent
2291
+ if (!reuseByPair[key]) reuseByPair[key] = { source: r.sourceAgent, target: r.targetAgent, total: 0, verified: 0, improved: 0 }
2292
+ reuseByPair[key].total++
2293
+ if (r.confirmed) reuseByPair[key].verified++
2294
+ if (r.outcomeImproved) reuseByPair[key].improved++
2295
+ }
2296
+ for (const [key, pair] of Object.entries(reuseByPair)) {
2297
+ if (pair.source !== pair.target) {
2298
+ crossPatterns.push({
2299
+ type: 'reuse_path',
2300
+ from: pair.source,
2301
+ to: pair.target,
2302
+ total: pair.total,
2303
+ verified: pair.verified,
2304
+ improved: pair.improved,
2305
+ })
2306
+ }
2307
+ }
2308
+ crossPatterns.sort((a, b) => b.verified - a.verified || b.total - a.total)
2309
+
2310
+ // Memory health
2311
+ const byKind = {}
2312
+ let shortContent = 0
2313
+ let missingKind = 0
2314
+ for (const m of filteredMemories) {
2315
+ const kind = m.kind || 'unknown'
2316
+ byKind[kind] = (byKind[kind] || 0) + 1
2317
+ const content = String(m.content || '').trim()
2318
+ if (content.length < 20) shortContent++
2319
+ if (!m.kind) missingKind++
2320
+ }
2321
+ const memoryHealth = {
2322
+ total: filteredMemories.length,
2323
+ byKind,
2324
+ shortContent,
2325
+ missingKind,
2326
+ qualityScore: filteredMemories.length > 0
2327
+ ? Math.round(((filteredMemories.length - shortContent - missingKind) / filteredMemories.length) * 100)
2328
+ : 100,
2329
+ }
2330
+
2331
+ // Suggestions engine
2332
+ const suggestions = []
2333
+
2334
+ // Routing suggestion: compare agent success rates
2335
+ if (agentPerf.length >= 2) {
2336
+ const best = agentPerf[0]
2337
+ const worst = agentPerf[agentPerf.length - 1]
2338
+ if (best.tasks.total >= 5 && worst.tasks.total >= 5 && best.tasks.successRate - worst.tasks.successRate >= 15) {
2339
+ suggestions.push({
2340
+ category: 'routing',
2341
+ priority: 'high',
2342
+ description: best.agentId + ' has ' + best.tasks.successRate + '% success rate vs ' + worst.agentId + ' at ' + worst.tasks.successRate + '%; prefer routing to ' + best.agentId,
2343
+ basedOn: 'task_outcome comparison',
2344
+ })
2345
+ }
2346
+ }
2347
+
2348
+ // Pending auto-claim suggestion
2349
+ if (pendingReuses.length >= 10) {
2350
+ suggestions.push({
2351
+ category: 'evidence',
2352
+ priority: 'medium',
2353
+ description: pendingReuses.length + ' pending auto-claims awaiting confirmation; review cross-agent claims to increase verified reuse count',
2354
+ basedOn: 'experience_reuse.jsonl',
2355
+ })
2356
+ }
2357
+
2358
+ // Memory quality suggestion
2359
+ if (memoryHealth.qualityScore < 80 && filteredMemories.length > 10) {
2360
+ suggestions.push({
2361
+ category: 'memory',
2362
+ priority: 'medium',
2363
+ description: 'Memory quality score is ' + memoryHealth.qualityScore + '%; ' + shortContent + ' short records and ' + missingKind + ' missing kind fields found',
2364
+ basedOn: 'memory.jsonl quality analysis',
2365
+ })
2366
+ }
2367
+
2368
+ // Cross-agent value suggestion
2369
+ if (crossPatterns.length === 0 && agentIds.size >= 2) {
2370
+ suggestions.push({
2371
+ category: 'interop',
2372
+ priority: 'high',
2373
+ description: 'Multiple agents registered but no cross-agent reuse patterns detected; ensure agents query shared memory',
2374
+ basedOn: 'experience_reuse.jsonl',
2375
+ })
2376
+ }
2377
+
2378
+ // Active agent suggestion
2379
+ const inactiveAgents = agentPerf.filter((a) => {
2380
+ if (!a.lastActive) return false
2381
+ return (now - new Date(a.lastActive).getTime()) > 7 * 86400000
2382
+ })
2383
+ if (inactiveAgents.length > 0) {
2384
+ suggestions.push({
2385
+ category: 'coverage',
2386
+ priority: 'low',
2387
+ description: inactiveAgents.map((a) => a.agentId).join(', ') + ' inactive for >7 days; consider removal or reactivation',
2388
+ basedOn: 'agent registry lastSeenAt',
2389
+ })
2390
+ }
2391
+
2392
+ suggestions.sort((a, b) => {
2393
+ const p = { high: 0, medium: 1, low: 2 }
2394
+ return (p[a.priority] || 2) - (p[b.priority] || 2)
2395
+ })
2396
+
2397
+ return {
2398
+ project,
2399
+ generatedAt: new Date().toISOString(),
2400
+ period,
2401
+ ecosystem,
2402
+ agentPerformance: agentPerf,
2403
+ crossAgentPatterns: crossPatterns,
2404
+ memoryHealth,
2405
+ suggestions,
2406
+ }
2407
+ }
2408
+
2409
+
2410
+ function recordTaskOutcome(args = {}) {
2411
+ const outcome = String(args.outcome || '').trim().toLowerCase()
2412
+ if (!['success', 'failure', 'aborted'].includes(outcome)) {
2413
+ throw new Error('task.record_outcome requires outcome to be success, failure, or aborted')
2414
+ }
2415
+ const agentId = String(args.agentId || runtimeAgentId() || 'unknown').trim()
2416
+ const project = args.project || projectName()
2417
+ const task = String(args.task || '').trim()
2418
+ const summary = String(args.summary || '').trim()
2419
+ const verification = String(args.verification || '').trim()
2420
+ const traceId = String(args.traceId || '').trim() || createId('trace:' + agentId + ':' + project)
2421
+
2422
+ // 1. Record trace event
2423
+ const event = {
2424
+ id: createId('trace'),
2425
+ timestamp: new Date().toISOString(),
2426
+ trace_id: traceId,
2427
+ event_type: 'task_outcome',
2428
+ outcome,
2429
+ payload: { task, summary, verification },
2430
+ agent: agentId,
2431
+ host: 'mcp',
2432
+ project,
2433
+ }
2434
+ appendJsonl(tracePath, event)
2435
+
2436
+ // 2. Auto-claim experience reuse
2437
+ const autoClaims = autoClaimExperienceReuse(event)
2438
+
2439
+ // 3. Update agent registry
2440
+ const now = new Date().toISOString()
2441
+ const agents = readJsonl(agentsPath)
2442
+ const agent = agents.find((a) => a.agentId === agentId && a.project === project)
2443
+ if (agent) {
2444
+ agent.lastSeenAt = now
2445
+ agent.taskCount = (agent.taskCount || 0) + 1
2446
+ agent.successCount = (agent.successCount || 0) + (outcome === 'success' ? 1 : 0)
2447
+ agent.failureCount = (agent.failureCount || 0) + (outcome === 'failure' ? 1 : 0)
2448
+ writeJsonl(agentsPath, agents)
2449
+ }
2450
+
2451
+ return {
2452
+ recorded: true,
2453
+ event: { id: event.id, trace_id: traceId, outcome, agent: agentId, project },
2454
+ agentUpdated: !!agent,
2455
+ autoClaims: autoClaims.length > 0 ? autoClaims : undefined,
2456
+ }
2457
+ }
2458
+
2459
+ module.exports = { TOOLS, callTool, handleMessage, readJsonl, appendJsonl, rl }