@octopi-agent/engine 0.65.0 → 0.70.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/config-schema/engine.d.ts +84 -0
  2. package/dist/config-schema/engine.js +4 -1
  3. package/dist/config-schema/substrate.d.ts +86 -0
  4. package/dist/config-schema/substrate.js +114 -0
  5. package/dist/config.d.ts +71 -0
  6. package/dist/harness/agent/builder.d.ts +1 -1
  7. package/dist/harness/agent/builder.js +27 -2
  8. package/dist/harness/agent/config-bridge.js +17 -4
  9. package/dist/harness/context/capabilities/summary/gate.js +2 -2
  10. package/dist/harness/context/capabilities/summary/policies.js +5 -5
  11. package/dist/harness/context/capabilities/summary/registry.js +29 -24
  12. package/dist/harness/context/layer-health.js +3 -2
  13. package/dist/harness/context/layers.d.ts +27 -13
  14. package/dist/harness/context/layers.js +76 -66
  15. package/dist/harness/context/system-prompt-assembler.d.ts +3 -0
  16. package/dist/harness/context/system-prompt-assembler.js +11 -1
  17. package/dist/harness/extension/plugin-ecosystem/client-tools/index.d.ts +4 -0
  18. package/dist/harness/extension/plugin-ecosystem/client-tools/index.js +3 -0
  19. package/dist/harness/extension/plugin-ecosystem/client-tools/invoke.d.ts +56 -0
  20. package/dist/harness/extension/plugin-ecosystem/client-tools/invoke.js +281 -0
  21. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.d.ts +98 -0
  22. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.js +250 -0
  23. package/dist/harness/extension/plugin-ecosystem/client-tools/stream.d.ts +124 -0
  24. package/dist/harness/extension/plugin-ecosystem/client-tools/stream.js +372 -0
  25. package/dist/harness/extension/plugin-ecosystem/client-tools/types.d.ts +109 -0
  26. package/dist/harness/extension/plugin-ecosystem/client-tools/types.js +8 -0
  27. package/dist/harness/extension/plugin-ecosystem/index.d.ts +1 -0
  28. package/dist/harness/extension/plugin-ecosystem/index.js +1 -0
  29. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +1 -1
  30. package/dist/harness/extension/plugin-ecosystem/tools/memory.d.ts +11 -1
  31. package/dist/harness/extension/plugin-ecosystem/tools/memory.js +14 -0
  32. package/dist/harness/index.d.ts +4 -3
  33. package/dist/harness/index.js +2 -1
  34. package/dist/harness/knowledge/query-service.js +5 -5
  35. package/dist/harness/knowledge/retriever.js +1 -1
  36. package/dist/harness/knowledge/source-store.d.ts +17 -2
  37. package/dist/harness/knowledge/source-store.js +6 -5
  38. package/dist/harness/memory/cognition-decay.d.ts +36 -0
  39. package/dist/harness/memory/cognition-decay.js +55 -0
  40. package/dist/harness/memory/cognition-gates.d.ts +60 -0
  41. package/dist/harness/memory/cognition-gates.js +191 -0
  42. package/dist/harness/memory/cognition-trigger.d.ts +30 -0
  43. package/dist/harness/memory/cognition-trigger.js +41 -0
  44. package/dist/harness/memory/cognition-types.d.ts +1 -1
  45. package/dist/harness/memory/cognition.d.ts +40 -8
  46. package/dist/harness/memory/cognition.js +432 -79
  47. package/dist/harness/memory/conceptualizer.d.ts +66 -0
  48. package/dist/harness/memory/conceptualizer.js +246 -0
  49. package/dist/harness/memory/index.d.ts +16 -2
  50. package/dist/harness/memory/index.js +11 -1
  51. package/dist/harness/memory/sqlite/agent-db.d.ts +9 -0
  52. package/dist/harness/memory/sqlite/agent-db.js +118 -15
  53. package/dist/harness/memory/sqlite/cognition-store.d.ts +55 -16
  54. package/dist/harness/memory/sqlite/cognition-store.js +591 -144
  55. package/dist/harness/memory/sqlite/wisdom-store.d.ts +33 -14
  56. package/dist/harness/memory/sqlite/wisdom-store.js +257 -44
  57. package/dist/harness/memory/types.d.ts +331 -16
  58. package/dist/harness/memory/types.js +49 -0
  59. package/dist/harness/memory/wisdom-formation.d.ts +101 -0
  60. package/dist/harness/memory/wisdom-formation.js +304 -0
  61. package/dist/harness/memory/wisdom-gates.d.ts +50 -0
  62. package/dist/harness/memory/wisdom-gates.js +204 -0
  63. package/dist/harness/memory/wisdom-policy.d.ts +107 -0
  64. package/dist/harness/memory/wisdom-policy.js +220 -0
  65. package/dist/harness/memory/wisdom-types.d.ts +3 -2
  66. package/dist/harness/memory/wisdom-types.js +2 -2
  67. package/dist/harness/memory/wisdom.d.ts +27 -0
  68. package/dist/harness/memory/wisdom.js +181 -0
  69. package/dist/harness/run/agent/agent.d.ts +9 -0
  70. package/dist/harness/run/agent/agent.js +19 -0
  71. package/dist/harness/run/reliability/run-agent.js +6 -2
  72. package/dist/harness/run/runner.js +2 -1
  73. package/dist/harness/session/index.d.ts +1 -0
  74. package/dist/harness/session/index.js +1 -0
  75. package/dist/harness/session/title.d.ts +86 -0
  76. package/dist/harness/session/title.js +268 -0
  77. package/dist/harness/shared/events/agent-event-map.d.ts +8 -0
  78. package/dist/harness/shared/events/agent-event-map.js +1 -0
  79. package/dist/index.d.ts +3 -1
  80. package/dist/index.js +1 -0
  81. package/dist/subsystems/cognition-steward/conceptualize/SUBSYSTEM.md +43 -0
  82. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +50 -0
  83. package/dist/subsystems/cognition-steward/conceptualize/handler.d.ts +9 -0
  84. package/dist/subsystems/cognition-steward/conceptualize/handler.js +125 -0
  85. package/dist/subsystems/cognition-steward/consolidate/SUBSYSTEM.md +6 -0
  86. package/dist/subsystems/cognition-steward/consolidate/config.yaml +54 -0
  87. package/dist/subsystems/cognition-steward/consolidate/handler.d.ts +12 -0
  88. package/dist/subsystems/cognition-steward/consolidate/handler.js +93 -0
  89. package/dist/subsystems/wisdom-steward/evaluate/config.yaml +50 -0
  90. package/dist/subsystems/wisdom-steward/evaluate/handler.d.ts +18 -0
  91. package/dist/subsystems/wisdom-steward/evaluate/handler.js +91 -0
  92. package/dist/subsystems/wisdom-steward/formation/SUBSYSTEM.md +42 -0
  93. package/dist/subsystems/wisdom-steward/formation/config.yaml +54 -0
  94. package/dist/subsystems/wisdom-steward/formation/handler.d.ts +18 -0
  95. package/dist/subsystems/wisdom-steward/formation/handler.js +212 -0
  96. package/dist/subsystems/wisdom-steward/govern/config.yaml +55 -0
  97. package/dist/subsystems/wisdom-steward/govern/handler.d.ts +17 -0
  98. package/dist/subsystems/wisdom-steward/govern/handler.js +68 -0
  99. package/package.json +2 -2
@@ -1,188 +1,635 @@
1
1
  /**
2
- * SqliteConceptGraph — SQLite 认知图谱
2
+ * SqliteConceptGraph — SQLite 认知图谱(生产路径)
3
+ *
4
+ * 契约见 arch/cognition-graph-formation.md:
5
+ * 结构同一性合并、持证边、衰减、扩散激活、merge_candidates、causal_candidate。
3
6
  *
4
7
  * @module
5
8
  */
9
+ import { counterEvidenceWeaken, DEFAULT_EDGE_DECAY_FLOOR, DEFAULT_RETRIEVE_STATUSES, hebbianStrengthen, nextEdgeStrength, } from '../cognition-decay.js';
10
+ import { evaluateConceptGate, licenseEdge, normalizeForCue } from '../cognition-gates.js';
6
11
  import { AgentDatabase } from './agent-db.js';
7
12
  import { cosineDistance, parseEmbedding, serializeEmbedding } from './vector-search.js';
13
+ function daysBetween(a, b) {
14
+ return Math.max(0, (b - a) / 86_400_000);
15
+ }
16
+ function normName(name) {
17
+ return name.trim().toLowerCase();
18
+ }
19
+ /** 转义 LIKE 通配符(配合 ESCAPE '\') */
20
+ function escapeLike(s) {
21
+ return s.replace(/[\\%_]/g, (c) => `\\${c}`);
22
+ }
8
23
  export class SqliteConceptGraph {
9
24
  db;
10
25
  embedding;
11
26
  mergeThreshold;
27
+ candidateBandHi;
28
+ stopNodes;
29
+ stopEdges;
30
+ decayFloor;
31
+ causesMinIndependentMemories;
12
32
  constructor(db, options) {
13
33
  this.db = db;
14
34
  this.embedding = options?.embeddingProvider ?? null;
15
- this.mergeThreshold = options?.mergeThreshold ?? 0.25;
35
+ this.mergeThreshold = options?.mergeThreshold ?? 0.2;
36
+ this.candidateBandHi = options?.candidateBandHi ?? 0.35;
37
+ this.stopNodes = options?.stopNodes ?? 10_000;
38
+ this.stopEdges = options?.stopEdges ?? 40_000;
39
+ this.decayFloor = options?.decayFloor ?? DEFAULT_EDGE_DECAY_FLOOR;
40
+ this.causesMinIndependentMemories = options?.causesMinIndependentMemories ?? 2;
16
41
  }
17
- async addConcept(concept) {
18
- // 1. 精确匹配
19
- const existing = this.db.raw.prepare('SELECT id, frequency FROM concepts WHERE LOWER(name) = LOWER(?)').get(concept.name);
20
- if (existing) {
21
- this.db.raw.prepare('UPDATE concepts SET frequency = frequency + 1, updated_at = ? WHERE id = ?').run(Date.now(), existing.id);
22
- return existing.id;
23
- }
24
- // 2. 语义匹配(需要 embedding)
25
- if (this.embedding) {
26
- const vec = await this.embedding.embed(concept.name);
27
- const similarId = await this.findSimilarConcept(vec);
28
- if (similarId) {
29
- // 合并:更新 frequency
30
- this.db.raw.prepare('UPDATE concepts SET frequency = frequency + 1, updated_at = ? WHERE id = ?').run(Date.now(), similarId);
31
- return similarId;
32
- }
33
- // 新概念(带 embedding)
34
- const id = AgentDatabase.generateId('cpt');
35
- const now = Date.now();
36
- this.db.raw.prepare(`
37
- INSERT INTO concepts (id, name, description, frequency, memory_ids, properties, embedding, created_at, updated_at)
38
- VALUES (?, ?, ?, 1, '[]', '[]', ?, ?, ?)
39
- `).run(id, concept.name, concept.description ?? null, serializeEmbedding(vec), now, now);
40
- return id;
41
- }
42
- // 新概念(无 embedding)
43
- const id = AgentDatabase.generateId('cpt');
44
- const now = Date.now();
45
- this.db.raw.prepare(`
46
- INSERT INTO concepts (id, name, description, frequency, memory_ids, properties, embedding, created_at, updated_at)
47
- VALUES (?, ?, ?, 1, '[]', '[]', NULL, ?, ?)
48
- `).run(id, concept.name, concept.description ?? null, now, now);
49
- return id;
42
+ get capacityStop() {
43
+ const n = this.db.raw.prepare('SELECT COUNT(*) AS c FROM concepts').get().c;
44
+ const e = this.db.raw.prepare('SELECT COUNT(*) AS c FROM concept_edges').get().c;
45
+ return n >= this.stopNodes || e >= this.stopEdges;
50
46
  }
51
- async addEdge(edge) {
52
- const id = AgentDatabase.generateId('edge');
53
- this.db.raw.prepare(`
54
- INSERT OR IGNORE INTO concept_edges (id, source_id, target_id, relation_type, strength, description, constraints, created_at)
55
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
56
- `).run(id, edge.sourceId, edge.targetId, edge.relationType, edge.strength, edge.description ?? null, JSON.stringify([]), Date.now());
57
- }
58
- async queryRelated(conceptName, depth = 1) {
59
- // 找到起始概念
60
- const start = this.db.raw.prepare('SELECT id FROM concepts WHERE LOWER(name) LIKE LOWER(?)').get(`%${conceptName}%`);
61
- if (!start)
62
- return { nodes: [], edges: [] };
63
- // 递归 CTE 图遍历
64
- const rows = this.db.raw.prepare(`
65
- WITH RECURSIVE graph_walk(node_id, depth) AS (
66
- SELECT ?, 0
67
- UNION
68
- SELECT DISTINCT
69
- CASE WHEN e.source_id = gw.node_id THEN e.target_id ELSE e.source_id END,
70
- gw.depth + 1
71
- FROM graph_walk gw
72
- JOIN concept_edges e ON (e.source_id = gw.node_id OR e.target_id = gw.node_id)
73
- WHERE gw.depth < ?
74
- )
75
- SELECT DISTINCT c.*, gw.depth
76
- FROM graph_walk gw
77
- JOIN concepts c ON c.id = gw.node_id
78
- ORDER BY gw.depth, c.frequency DESC
79
- LIMIT 20
80
- `).all(start.id, depth);
81
- const nodes = rows.map(r => this.rowToNode(r));
82
- const nodeIds = new Set(nodes.map(n => n.id));
83
- // 获取相关的边
84
- const allEdges = this.db.raw.prepare(`
85
- SELECT * FROM concept_edges
86
- WHERE source_id IN (${nodes.map(() => '?').join(',')})
87
- OR target_id IN (${nodes.map(() => '?').join(',')})
88
- `).all(...nodeIds, ...nodeIds);
89
- const edges = allEdges
90
- .filter((e) => nodeIds.has(e.source_id) && nodeIds.has(e.target_id))
91
- .map((e) => this.rowToEdge(e));
92
- return { nodes, edges };
47
+ rowToNode(row) {
48
+ return {
49
+ id: row.id,
50
+ name: row.name,
51
+ kind: row.kind ?? 'construct',
52
+ description: row.description ?? undefined,
53
+ frequency: row.frequency,
54
+ memoryIds: safeJsonArray(row.memory_ids),
55
+ domain: safeJsonArray(row.domain),
56
+ status: row.status ?? 'shadow',
57
+ embedding: row.embedding ? parseEmbedding(row.embedding) : null,
58
+ createdAt: row.created_at,
59
+ updatedAt: row.updated_at,
60
+ };
93
61
  }
94
- async extractFromText(text, memoryId) {
95
- // P0 简单实现:正则提取大写开头的词 + 共现分析
96
- const conceptPattern = /[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*/g;
97
- const matches = text.match(conceptPattern) ?? [];
98
- const conceptIds = [];
99
- for (const match of new Set(matches)) {
100
- if (match.length < 3 || match.length > 50)
62
+ rowToEdge(row) {
63
+ let basis = {
64
+ memoryIds: [],
65
+ cue: '',
66
+ evidenceClass: 'cooccur',
67
+ licensedAt: row.created_at,
68
+ };
69
+ try {
70
+ const parsed = JSON.parse(row.basis);
71
+ if (parsed && typeof parsed === 'object') {
72
+ basis = {
73
+ memoryIds: Array.isArray(parsed.memoryIds) ? parsed.memoryIds : [],
74
+ cue: typeof parsed.cue === 'string' ? parsed.cue : '',
75
+ evidenceClass: parsed.evidenceClass ?? 'cooccur',
76
+ licensedAt: typeof parsed.licensedAt === 'number' ? parsed.licensedAt : row.created_at,
77
+ };
78
+ }
79
+ }
80
+ catch {
81
+ // basis 解析失败用默认弱证件
82
+ }
83
+ return {
84
+ id: row.id,
85
+ sourceId: row.source_id,
86
+ targetId: row.target_id,
87
+ relationType: row.relation_type ?? 'related',
88
+ strength: row.strength,
89
+ description: row.description ?? undefined,
90
+ status: row.status ?? 'shadow',
91
+ basis,
92
+ createdAt: row.created_at,
93
+ updatedAt: row.updated_at,
94
+ };
95
+ }
96
+ async admitConcept(input) {
97
+ const gate = evaluateConceptGate(input, { capacityAdmitStop: this.capacityStop });
98
+ if (!gate.ok) {
99
+ return { action: 'rejected', reason: gate.reason, message: gate.message };
100
+ }
101
+ const nameKey = normName(input.name);
102
+ const existing = this.db.raw
103
+ .prepare('SELECT * FROM concepts WHERE LOWER(name) = ?')
104
+ .all(nameKey);
105
+ // 同名多义项:指纹兼容则合并,冲突则新建 + merge_candidate
106
+ const conflicts = [];
107
+ for (const row of existing) {
108
+ const node = this.rowToNode(row);
109
+ const conflict = this.fingerprintConflict(node, input);
110
+ if (conflict) {
111
+ conflicts.push({ node, reason: conflict });
101
112
  continue;
102
- const id = await this.addConcept({ name: match });
103
- // 关联记忆
104
- const row = this.db.raw.prepare('SELECT memory_ids FROM concepts WHERE id = ?').get(id);
105
- if (row) {
106
- const memoryIds = JSON.parse(row.memory_ids);
107
- if (!memoryIds.includes(memoryId)) {
108
- memoryIds.push(memoryId);
109
- this.db.raw.prepare('UPDATE concepts SET memory_ids = ?, updated_at = ? WHERE id = ?')
110
- .run(JSON.stringify(memoryIds), Date.now(), id);
113
+ }
114
+ const memIds = new Set([...node.memoryIds, ...(input.memoryIds ?? [])]);
115
+ this.db.raw
116
+ .prepare('UPDATE concepts SET frequency = frequency + 1, memory_ids = ?, description = COALESCE(description, ?), updated_at = ? WHERE id = ?')
117
+ .run(JSON.stringify([...memIds]), input.description ?? null, Date.now(), node.id);
118
+ return { action: 'merged', id: node.id, reason: 'ok' };
119
+ }
120
+ // embedding 近邻
121
+ if (this.embedding) {
122
+ const vec = await this.embedding.embed(input.name);
123
+ const near = await this.findSimilarConcept(vec);
124
+ if (near) {
125
+ const conflict = this.fingerprintConflict(near.node, input);
126
+ if (!conflict && near.distance <= this.mergeThreshold) {
127
+ const memIds = new Set([...near.node.memoryIds, ...(input.memoryIds ?? [])]);
128
+ this.db.raw
129
+ .prepare('UPDATE concepts SET frequency = frequency + 1, memory_ids = ?, updated_at = ? WHERE id = ?')
130
+ .run(JSON.stringify([...memIds]), Date.now(), near.node.id);
131
+ return { action: 'merged', id: near.node.id, reason: 'ok' };
111
132
  }
133
+ // 近阈带或指纹冲突 → candidate
134
+ const id = this.insertConcept(input, vec);
135
+ const candidateId = this.insertMergeCandidate(near.node.id, id, conflict ?? 'embedding_band', near.distance, conflict ? [conflict] : []);
136
+ return {
137
+ action: 'merge_candidate',
138
+ id,
139
+ candidateId,
140
+ reason: conflict ? 'fingerprint_conflict' : 'ok',
141
+ };
112
142
  }
113
- conceptIds.push(id);
114
- }
115
- // 共现关系
116
- for (let i = 0; i < conceptIds.length; i++) {
117
- for (let j = i + 1; j < conceptIds.length; j++) {
118
- await this.addEdge({
119
- sourceId: conceptIds[i],
120
- targetId: conceptIds[j],
121
- relationType: 'related',
122
- strength: 0.5,
123
- });
143
+ const id = this.insertConcept(input, vec);
144
+ if (conflicts.length) {
145
+ const candidateId = this.insertMergeCandidate(conflicts[0].node.id, id, conflicts[0].reason, null, [conflicts[0].reason]);
146
+ return { action: 'merge_candidate', id, candidateId, reason: 'fingerprint_conflict' };
124
147
  }
148
+ return { action: 'created', id, reason: 'ok' };
149
+ }
150
+ const id = this.insertConcept(input, null);
151
+ if (conflicts.length) {
152
+ const candidateId = this.insertMergeCandidate(conflicts[0].node.id, id, conflicts[0].reason, null, [conflicts[0].reason]);
153
+ return { action: 'merge_candidate', id, candidateId, reason: 'fingerprint_conflict' };
125
154
  }
155
+ return { action: 'created', id, reason: 'ok' };
126
156
  }
127
- async getFullGraph() {
128
- const nodes = this.db.raw.prepare('SELECT * FROM concepts').all()
129
- .map(r => this.rowToNode(r));
130
- const edges = this.db.raw.prepare('SELECT * FROM concept_edges').all()
131
- .map(r => this.rowToEdge(r));
132
- return { nodes, edges };
157
+ fingerprintConflict(existing, input) {
158
+ if (existing.kind !== input.kind && existing.kind !== 'construct' && input.kind !== 'construct') {
159
+ return `kind:${existing.kind}≠${input.kind}`;
160
+ }
161
+ if (existing.kind !== input.kind)
162
+ return `kind:${existing.kind}≠${input.kind}`;
163
+ const a = new Set(existing.domain);
164
+ const b = new Set(input.domain ?? []);
165
+ if (a.size > 0 && b.size > 0) {
166
+ const overlap = [...b].some((d) => a.has(d));
167
+ if (!overlap)
168
+ return 'domain_disjoint';
169
+ }
170
+ return null;
171
+ }
172
+ insertConcept(input, vec) {
173
+ const id = AgentDatabase.generateId('cpt');
174
+ const now = Date.now();
175
+ this.db.raw
176
+ .prepare(`INSERT INTO concepts (id, name, kind, description, frequency, memory_ids, domain, status, embedding, created_at, updated_at)
177
+ VALUES (?, ?, ?, ?, 1, ?, ?, 'shadow', ?, ?, ?)`)
178
+ .run(id, input.name.trim(), input.kind, input.description ?? null, JSON.stringify(input.memoryIds ?? []), JSON.stringify(input.domain ?? []), vec ? serializeEmbedding(vec) : null, now, now);
179
+ return id;
180
+ }
181
+ insertMergeCandidate(leftId, rightId, reason, distance, fingerprintDiff) {
182
+ const id = AgentDatabase.generateId('mrg');
183
+ this.db.raw
184
+ .prepare(`INSERT INTO concept_merge_candidates
185
+ (id, left_id, right_id, reason, distance, fingerprint_diff, status, created_at)
186
+ VALUES (?, ?, ?, ?, ?, ?, 'open', ?)`)
187
+ .run(id, leftId, rightId, reason, distance, JSON.stringify(fingerprintDiff), Date.now());
188
+ return id;
133
189
  }
134
- /**
135
- * 查找语义相似的概念(用于去重)
136
- */
137
190
  async findSimilarConcept(embedding) {
138
- const rows = this.db.raw.prepare('SELECT id, embedding FROM concepts WHERE embedding IS NOT NULL').all();
139
- let bestId = null;
140
- let bestDistance = Infinity;
191
+ const rows = this.db.raw
192
+ .prepare('SELECT * FROM concepts WHERE embedding IS NOT NULL')
193
+ .all();
194
+ let best = null;
141
195
  for (const row of rows) {
142
196
  const vec = parseEmbedding(row.embedding);
143
197
  if (!vec)
144
198
  continue;
145
199
  const distance = cosineDistance(embedding, vec);
146
- if (distance < bestDistance) {
147
- bestDistance = distance;
148
- bestId = row.id;
200
+ if (!best || distance < best.distance) {
201
+ best = { node: this.rowToNode(row), distance };
149
202
  }
150
203
  }
151
- if (bestDistance <= this.mergeThreshold) {
152
- return bestId;
153
- }
204
+ if (best && best.distance <= this.candidateBandHi)
205
+ return best;
154
206
  return null;
155
207
  }
156
- /**
157
- * 关联记忆到概念(从外部调用)
158
- */
159
- linkMemory(conceptId, memoryId) {
160
- const row = this.db.raw.prepare('SELECT memory_ids FROM concepts WHERE id = ?').get(conceptId);
208
+ /** 同 pair(无向)已有 memoryIds:边 basis + causal_candidate */
209
+ collectPairMemoryIds(sourceId, targetId) {
210
+ const ids = new Set();
211
+ const edges = this.db.raw
212
+ .prepare(`SELECT basis FROM concept_edges
213
+ WHERE (source_id = ? AND target_id = ?) OR (source_id = ? AND target_id = ?)`)
214
+ .all(sourceId, targetId, targetId, sourceId);
215
+ for (const e of edges) {
216
+ try {
217
+ const b = JSON.parse(e.basis);
218
+ for (const mid of b.memoryIds ?? [])
219
+ ids.add(mid);
220
+ }
221
+ catch {
222
+ // basis 解析失败不贡献证据
223
+ }
224
+ }
225
+ const aux = this.db.raw
226
+ .prepare(`SELECT memory_ids FROM concept_edges_aux
227
+ WHERE edge_key IN (?, ?)`)
228
+ .all(`${sourceId}->${targetId}`, `${targetId}->${sourceId}`);
229
+ for (const a of aux) {
230
+ for (const mid of safeJsonArray(a.memory_ids))
231
+ ids.add(mid);
232
+ }
233
+ return [...ids];
234
+ }
235
+ async admitEdge(input) {
236
+ // 持证前累积同 pair 已有 memoryIds(跨命题多证据闭环)
237
+ const priorIds = this.collectPairMemoryIds(input.sourceId, input.targetId);
238
+ const memoryIds = [...new Set([...priorIds, ...(input.basis.memoryIds ?? [])])];
239
+ const license = licenseEdge({
240
+ relationType: input.relationType,
241
+ evidenceClass: input.basis.evidenceClass,
242
+ cue: input.basis.cue,
243
+ evidenceText: input.evidenceText,
244
+ memoryIds,
245
+ causesMinIndependentMemories: this.causesMinIndependentMemories,
246
+ });
247
+ if (license.status === 'rejected') {
248
+ return { action: 'rejected', reason: license.reason, message: license.message };
249
+ }
250
+ if (license.status === 'candidate_only') {
251
+ await this.addCausalCandidate({
252
+ sourceId: input.sourceId,
253
+ targetId: input.targetId,
254
+ memoryIds: input.basis.memoryIds,
255
+ cue: input.basis.cue,
256
+ note: license.message,
257
+ });
258
+ return {
259
+ action: 'candidate_only',
260
+ reason: license.reason,
261
+ message: license.message,
262
+ };
263
+ }
264
+ if (!input.sourceId || !input.targetId) {
265
+ return { action: 'rejected', reason: 'invalid_relation', message: 'endpoint id missing' };
266
+ }
267
+ // 端点存在性
268
+ const src = this.db.raw.prepare('SELECT id FROM concepts WHERE id = ?').get(input.sourceId);
269
+ const tgt = this.db.raw.prepare('SELECT id FROM concepts WHERE id = ?').get(input.targetId);
270
+ if (!src || !tgt) {
271
+ return { action: 'rejected', reason: 'invalid_relation', message: 'endpoint missing' };
272
+ }
273
+ const relationType = license.relationType;
274
+ const status = license.status === 'active' ? 'active' : 'shadow';
275
+ const now = Date.now();
276
+ const basis = {
277
+ memoryIds: [...new Set(input.basis.memoryIds ?? [])],
278
+ cue: input.basis.cue ?? '',
279
+ evidenceClass: input.basis.evidenceClass,
280
+ licensedAt: input.basis.licensedAt ?? now,
281
+ };
282
+ const existing = this.db.raw
283
+ .prepare('SELECT * FROM concept_edges WHERE source_id = ? AND target_id = ? AND relation_type = ?')
284
+ .get(input.sourceId, input.targetId, relationType);
285
+ if (existing) {
286
+ const edge = this.rowToEdge(existing);
287
+ const memIds = new Set([...edge.basis.memoryIds, ...basis.memoryIds]);
288
+ const mergedBasis = { ...edge.basis, memoryIds: [...memIds], cue: basis.cue || edge.basis.cue };
289
+ this.db.raw
290
+ .prepare('UPDATE concept_edges SET strength = MAX(strength, ?), basis = ?, status = CASE WHEN ? = \'active\' THEN \'active\' ELSE status END, updated_at = ? WHERE id = ?')
291
+ .run(input.strength, JSON.stringify(mergedBasis), status, now, existing.id);
292
+ return {
293
+ action: license.status === 'demoted' ? 'demoted' : status,
294
+ edgeId: existing.id,
295
+ relationType,
296
+ reason: license.reason,
297
+ };
298
+ }
299
+ const edgeId = AgentDatabase.generateId('edge');
300
+ this.db.raw
301
+ .prepare(`INSERT INTO concept_edges
302
+ (id, source_id, target_id, relation_type, strength, description, status, basis, created_at, updated_at)
303
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
304
+ .run(edgeId, input.sourceId, input.targetId, relationType, Math.min(1, Math.max(0, input.strength)), input.description ?? null, status, JSON.stringify(basis), now, now);
305
+ return {
306
+ action: license.status === 'demoted' ? 'demoted' : status,
307
+ edgeId,
308
+ relationType,
309
+ reason: license.reason,
310
+ };
311
+ }
312
+ async addCausalCandidate(input) {
313
+ const edgeKey = `${input.sourceId}->${input.targetId}`;
314
+ this.db.raw
315
+ .prepare(`INSERT INTO concept_edges_aux (id, edge_key, kind, memory_ids, cue, note, created_at)
316
+ VALUES (?, ?, 'causal_candidate', ?, ?, ?, ?)`)
317
+ .run(AgentDatabase.generateId('causal'), edgeKey, JSON.stringify(input.memoryIds ?? []), normalizeForCue(input.cue), input.note ?? null, Date.now());
318
+ }
319
+ async listMergeCandidates(limit = 50) {
320
+ const rows = this.db.raw
321
+ .prepare(`SELECT * FROM concept_merge_candidates WHERE status = 'open' ORDER BY created_at DESC LIMIT ?`)
322
+ .all(limit);
323
+ return rows.map((r) => ({
324
+ id: r.id,
325
+ leftId: r.left_id,
326
+ rightId: r.right_id,
327
+ reason: r.reason,
328
+ distance: r.distance,
329
+ fingerprintDiff: safeJsonArray(r.fingerprint_diff),
330
+ status: r.status,
331
+ createdAt: r.created_at,
332
+ resolvedAt: r.resolved_at ?? undefined,
333
+ resolvedAction: r.resolved_action ?? undefined,
334
+ }));
335
+ }
336
+ async resolveMerge(id, action) {
337
+ const row = this.db.raw
338
+ .prepare('SELECT * FROM concept_merge_candidates WHERE id = ?')
339
+ .get(id);
161
340
  if (!row)
162
341
  return;
163
- const memoryIds = JSON.parse(row.memory_ids);
164
- if (!memoryIds.includes(memoryId)) {
165
- memoryIds.push(memoryId);
166
- this.db.raw.prepare('UPDATE concepts SET memory_ids = ?, updated_at = ? WHERE id = ?')
167
- .run(JSON.stringify(memoryIds), Date.now(), conceptId);
342
+ const status = action === 'merge' ? 'merged' : action === 'keep_split' ? 'kept_split' : 'dropped';
343
+ if (action !== 'merge') {
344
+ this.db.raw
345
+ .prepare('UPDATE concept_merge_candidates SET status = ?, resolved_at = ?, resolved_action = ? WHERE id = ?')
346
+ .run(status, Date.now(), action, id);
347
+ return;
348
+ }
349
+ const left = this.db.raw.prepare('SELECT * FROM concepts WHERE id = ?').get(row.left_id);
350
+ let right = this.db.raw.prepare('SELECT * FROM concepts WHERE id = ?').get(row.right_id);
351
+ if (!right && row.right_id.startsWith('pending:')) {
352
+ const pendingName = row.right_id.slice('pending:'.length).toLowerCase();
353
+ const candidates = this.db.raw
354
+ .prepare('SELECT * FROM concepts WHERE LOWER(name) = ?')
355
+ .all(pendingName);
356
+ // 同名多义项:取非 left 的第一个
357
+ right = candidates.find((c) => c.id !== row.left_id);
358
+ }
359
+ if (!left || !right || left.id === right.id) {
360
+ this.db.raw
361
+ .prepare('UPDATE concept_merge_candidates SET status = ?, resolved_at = ?, resolved_action = ? WHERE id = ?')
362
+ .run('dropped', Date.now(), 'drop_missing_endpoint', id);
363
+ return;
364
+ }
365
+ const db = this.db.raw;
366
+ db.exec('BEGIN');
367
+ try {
368
+ const memIds = new Set([
369
+ ...safeJsonArray(left.memory_ids),
370
+ ...safeJsonArray(right.memory_ids),
371
+ ]);
372
+ db.prepare('UPDATE concepts SET frequency = frequency + ?, memory_ids = ?, updated_at = ? WHERE id = ?').run(right.frequency, JSON.stringify([...memIds]), Date.now(), left.id);
373
+ // 迁边前:丢掉会变自环的边
374
+ db.prepare('DELETE FROM concept_edges WHERE (source_id = ? AND target_id = ?) OR (source_id = ? AND target_id = ?)')
375
+ .run(left.id, right.id, right.id, left.id);
376
+ // 改写端点(UNIQUE 冲突则保留 left 侧已有边,丢弃 right 侧重复)
377
+ db.prepare(`UPDATE OR IGNORE concept_edges SET source_id = ?, updated_at = ? WHERE source_id = ?`).run(left.id, Date.now(), right.id);
378
+ db.prepare(`UPDATE OR IGNORE concept_edges SET target_id = ?, updated_at = ? WHERE target_id = ?`).run(left.id, Date.now(), right.id);
379
+ // OR IGNORE 未更新的仍是 right 端点 → 删除残留
380
+ db.prepare('DELETE FROM concept_edges WHERE source_id = ? OR target_id = ?').run(right.id, right.id);
381
+ // 迁完后自环清理
382
+ db.prepare('DELETE FROM concept_edges WHERE source_id = target_id').run();
383
+ db.prepare('DELETE FROM concepts WHERE id = ?').run(right.id);
384
+ db.prepare('UPDATE concept_merge_candidates SET status = ?, resolved_at = ?, resolved_action = ? WHERE id = ?').run('merged', Date.now(), 'merge', id);
385
+ db.exec('COMMIT');
386
+ }
387
+ catch (err) {
388
+ db.exec('ROLLBACK');
389
+ throw err instanceof Error
390
+ ? err
391
+ : new Error(`resolveMerge failed: ${String(err)}`);
168
392
  }
169
393
  }
170
- rowToNode(row) {
394
+ async reinforce(input) {
395
+ const e = Math.min(1, Math.max(0, input.evidenceStrength ?? 0.5));
396
+ const now = Date.now();
397
+ for (const id of input.nodeIds ?? []) {
398
+ this.db.raw
399
+ .prepare('UPDATE concepts SET frequency = frequency + 1, updated_at = ? WHERE id = ?')
400
+ .run(now, id);
401
+ }
402
+ for (const id of input.edgeIds ?? []) {
403
+ const row = this.db.raw.prepare('SELECT strength FROM concept_edges WHERE id = ?').get(id);
404
+ if (!row)
405
+ continue;
406
+ const next = hebbianStrengthen(row.strength, e);
407
+ this.db.raw
408
+ .prepare('UPDATE concept_edges SET strength = ?, updated_at = ? WHERE id = ?')
409
+ .run(next, now, id);
410
+ }
411
+ }
412
+ async counterEvidence(input) {
413
+ const row = this.db.raw
414
+ .prepare('SELECT * FROM concept_edges WHERE id = ?')
415
+ .get(input.edgeId);
416
+ if (!row)
417
+ return;
418
+ const edge = this.rowToEdge(row);
419
+ let strength = counterEvidenceWeaken(edge.strength);
420
+ let relationType = edge.relationType;
421
+ if (input.markOpposes)
422
+ relationType = 'opposes';
423
+ let memIds = edge.basis.memoryIds;
424
+ if (input.memoryId) {
425
+ memIds = memIds.filter((m) => m !== input.memoryId);
426
+ }
427
+ this.db.raw
428
+ .prepare('UPDATE concept_edges SET strength = ?, relation_type = ?, basis = ?, updated_at = ? WHERE id = ?')
429
+ .run(strength, relationType, JSON.stringify({ ...edge.basis, memoryIds: memIds }), Date.now(), input.edgeId);
430
+ }
431
+ async promote(ids, to) {
432
+ const now = Date.now();
433
+ for (const id of ids) {
434
+ this.db.raw
435
+ .prepare('UPDATE concepts SET status = ?, updated_at = ? WHERE id = ?')
436
+ .run(to, now, id);
437
+ this.db.raw
438
+ .prepare('UPDATE concept_edges SET status = ?, updated_at = ? WHERE id = ?')
439
+ .run(to, now, id);
440
+ }
441
+ }
442
+ async demote(ids, to) {
443
+ const now = Date.now();
444
+ for (const id of ids) {
445
+ this.db.raw
446
+ .prepare('UPDATE concepts SET status = ?, updated_at = ? WHERE id = ?')
447
+ .run(to, now, id);
448
+ this.db.raw
449
+ .prepare('UPDATE concept_edges SET status = ?, updated_at = ? WHERE id = ?')
450
+ .run(to, now, id);
451
+ }
452
+ }
453
+ async applyDecay(now = Date.now()) {
454
+ const edges = this.db.raw.prepare('SELECT * FROM concept_edges').all();
455
+ let decayedEdges = 0;
456
+ for (const row of edges) {
457
+ const days = daysBetween(row.updated_at, now);
458
+ if (days < 1)
459
+ continue;
460
+ const next = nextEdgeStrength(row.strength, row.relation_type, days);
461
+ if (next < row.strength - 1e-6) {
462
+ this.db.raw
463
+ .prepare('UPDATE concept_edges SET strength = ?, updated_at = ? WHERE id = ?')
464
+ .run(next, now, row.id);
465
+ decayedEdges += 1;
466
+ }
467
+ }
468
+ // GC 无支撑且无有效边的节点
469
+ const liveEdges = this.db.raw
470
+ .prepare(`SELECT source_id, target_id FROM concept_edges WHERE strength > ?`)
471
+ .all(this.decayFloor);
472
+ const connected = new Set();
473
+ for (const e of liveEdges) {
474
+ connected.add(e.source_id);
475
+ connected.add(e.target_id);
476
+ }
477
+ const nodes = this.db.raw.prepare('SELECT id, memory_ids FROM concepts').all();
478
+ let gcNodes = 0;
479
+ for (const n of nodes) {
480
+ if (!connected.has(n.id) && safeJsonArray(n.memory_ids).length === 0) {
481
+ this.db.raw.prepare('DELETE FROM concept_edges WHERE source_id = ? OR target_id = ?').run(n.id, n.id);
482
+ this.db.raw.prepare('DELETE FROM concepts WHERE id = ?').run(n.id);
483
+ gcNodes += 1;
484
+ }
485
+ }
486
+ const gcEdges = this.db.raw
487
+ .prepare(`DELETE FROM concept_edges WHERE source_id NOT IN (SELECT id FROM concepts)
488
+ OR target_id NOT IN (SELECT id FROM concepts)`)
489
+ .run().changes;
490
+ return { decayedEdges, gcNodes, gcEdges };
491
+ }
492
+ async spreadingActivate(seeds, options) {
493
+ const depth = options?.depth ?? 2;
494
+ const delta = options?.delta ?? 0.55;
495
+ const tau = options?.tau ?? 0.08;
496
+ const limit = options?.limit ?? 40;
497
+ const statuses = options?.statuses ?? DEFAULT_RETRIEVE_STATUSES;
498
+ const empty = { nodes: [], edges: [], activation: {}, seeds: [] };
499
+ if (!seeds.length || statuses.length === 0)
500
+ return empty;
501
+ const statusPlace = statuses.map(() => '?').join(',');
502
+ const statusSet = new Set(statuses);
503
+ const seedMap = new Map();
504
+ for (const seed of seeds) {
505
+ const q = `%${escapeLike(seed.toLowerCase())}%`;
506
+ const rows = this.db.raw
507
+ .prepare(`SELECT * FROM concepts WHERE status IN (${statusPlace})
508
+ AND (LOWER(name) LIKE ? ESCAPE '\\' OR LOWER(description) LIKE ? ESCAPE '\\')`)
509
+ .all(...statuses, q, q);
510
+ for (const r of rows)
511
+ seedMap.set(r.id, this.rowToNode(r));
512
+ }
513
+ const seedIds = [...seedMap.keys()];
514
+ if (!seedIds.length)
515
+ return empty;
516
+ const activation = new Map();
517
+ for (const id of seedIds)
518
+ activation.set(id, 1);
519
+ // 邻接:两端都必须在检索 status 集合内(禁止扩散进 shadow)
520
+ const allEdges = this.db.raw
521
+ .prepare(`SELECT e.* FROM concept_edges e
522
+ JOIN concepts s ON s.id = e.source_id
523
+ JOIN concepts t ON t.id = e.target_id
524
+ WHERE s.status IN (${statusPlace}) AND t.status IN (${statusPlace})`)
525
+ .all(...statuses, ...statuses);
526
+ const adj = new Map();
527
+ for (const row of allEdges) {
528
+ const e = this.rowToEdge(row);
529
+ const src = this.db.raw.prepare('SELECT status FROM concepts WHERE id = ?').get(e.sourceId);
530
+ const tgt = this.db.raw.prepare('SELECT status FROM concepts WHERE id = ?').get(e.targetId);
531
+ if (!src || !tgt || !statusSet.has(src.status) || !statusSet.has(tgt.status)) {
532
+ continue;
533
+ }
534
+ if (!adj.has(e.sourceId))
535
+ adj.set(e.sourceId, []);
536
+ if (!adj.has(e.targetId))
537
+ adj.set(e.targetId, []);
538
+ adj.get(e.sourceId).push({ to: e.targetId, w: e.strength });
539
+ adj.get(e.targetId).push({ to: e.sourceId, w: e.strength });
540
+ }
541
+ let frontier = [...seedIds];
542
+ for (let d = 1; d <= depth; d++) {
543
+ const next = [];
544
+ for (const id of frontier) {
545
+ const a = activation.get(id) ?? 0;
546
+ for (const { to, w } of adj.get(id) ?? []) {
547
+ const v = a * w * Math.pow(delta, d);
548
+ const prev = activation.get(to) ?? 0;
549
+ if (v > prev && v >= tau) {
550
+ activation.set(to, Math.max(prev, v));
551
+ next.push(to);
552
+ }
553
+ }
554
+ }
555
+ frontier = next;
556
+ if (frontier.length === 0)
557
+ break;
558
+ }
559
+ const kept = [...activation.entries()]
560
+ .filter(([, a]) => a >= tau)
561
+ .sort((a, b) => b[1] - a[1])
562
+ .slice(0, limit);
563
+ const nodeIds = new Set(kept.map(([id]) => id));
564
+ if (!nodeIds.size)
565
+ return empty;
566
+ const nodes = [];
567
+ for (const id of nodeIds) {
568
+ const row = this.db.raw.prepare('SELECT * FROM concepts WHERE id = ?').get(id);
569
+ if (row)
570
+ nodes.push(this.rowToNode(row));
571
+ }
572
+ const idList = [...nodeIds];
573
+ const placeholders = idList.map(() => '?').join(',');
574
+ const edgeRows = this.db.raw
575
+ .prepare(`SELECT * FROM concept_edges WHERE source_id IN (${placeholders})
576
+ AND target_id IN (${placeholders})`)
577
+ .all(...idList, ...idList);
171
578
  return {
172
- id: row.id,
173
- name: row.name,
174
- description: row.description ?? undefined,
175
- frequency: row.frequency,
176
- memoryIds: JSON.parse(row.memory_ids),
579
+ nodes,
580
+ edges: edgeRows.map((r) => this.rowToEdge(r)),
581
+ activation: Object.fromEntries(kept),
582
+ seeds: seedIds,
177
583
  };
178
584
  }
179
- rowToEdge(row) {
585
+ async getFullGraph() {
586
+ const nodes = this.db.raw.prepare('SELECT * FROM concepts').all().map((r) => this.rowToNode(r));
587
+ const edges = this.db.raw.prepare('SELECT * FROM concept_edges').all().map((r) => this.rowToEdge(r));
588
+ return { nodes, edges };
589
+ }
590
+ async stats() {
591
+ const byStatus = {
592
+ shadow: 0,
593
+ active: 0,
594
+ strengthened: 0,
595
+ };
596
+ const byKind = {
597
+ entity: 0,
598
+ construct: 0,
599
+ method: 0,
600
+ problem: 0,
601
+ constraint: 0,
602
+ };
603
+ for (const row of this.db.raw.prepare('SELECT status, kind FROM concepts').all()) {
604
+ const s = row.status in byStatus ? row.status : 'shadow';
605
+ byStatus[s] += 1;
606
+ if (row.kind in byKind)
607
+ byKind[row.kind] += 1;
608
+ }
609
+ const nodes = this.db.raw.prepare('SELECT COUNT(*) AS c FROM concepts').get().c;
610
+ const edges = this.db.raw.prepare('SELECT COUNT(*) AS c FROM concept_edges').get().c;
611
+ const openMerge = this.db.raw
612
+ .prepare(`SELECT COUNT(*) AS c FROM concept_merge_candidates WHERE status = 'open'`)
613
+ .get().c;
614
+ const causal = this.db.raw
615
+ .prepare(`SELECT COUNT(*) AS c FROM concept_edges_aux WHERE kind = 'causal_candidate'`)
616
+ .get().c;
180
617
  return {
181
- sourceId: row.source_id,
182
- targetId: row.target_id,
183
- relationType: row.relation_type,
184
- strength: row.strength,
185
- description: row.description ?? undefined,
618
+ nodes,
619
+ edges,
620
+ byStatus,
621
+ byKind,
622
+ openMergeCandidates: openMerge,
623
+ causalCandidates: causal,
186
624
  };
187
625
  }
188
626
  }
627
+ function safeJsonArray(raw) {
628
+ try {
629
+ const v = JSON.parse(raw ?? '[]');
630
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
631
+ }
632
+ catch {
633
+ return [];
634
+ }
635
+ }