@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,107 +1,460 @@
1
1
  /**
2
- * InMemoryConceptGraph — 内存认知图谱
2
+ * InMemoryConceptGraph — 内存认知图谱(测试/轻量)
3
3
  *
4
- * P0 基础版:基于关键词的简单概念提取和关系建立。
5
- * P1 增强版:LLM 驱动的深度概念提取。
4
+ * 实现与 SqliteConceptGraph 同一 `ConceptGraphStore` 契约:
5
+ * 结构同一性合并、持证边、衰减、扩散激活。无正则 extractFromText。
6
+ *
7
+ * @module harness/memory/cognition
6
8
  */
7
9
  import { randomUUID } from 'node:crypto';
10
+ import { counterEvidenceWeaken, DEFAULT_EDGE_DECAY_FLOOR, DEFAULT_RETRIEVE_STATUSES, hebbianStrengthen, nextEdgeStrength, } from './cognition-decay.js';
11
+ import { evaluateConceptGate, licenseEdge } from './cognition-gates.js';
12
+ function normName(name) {
13
+ return name.trim().toLowerCase();
14
+ }
15
+ function daysBetween(a, b) {
16
+ return Math.max(0, (b - a) / 86_400_000);
17
+ }
8
18
  export class InMemoryConceptGraph {
9
19
  nodes = new Map();
10
- edges = [];
11
- async addConcept(concept) {
12
- // 检查是否已存在同名概念
13
- for (const [id, node] of this.nodes) {
14
- if (node.name.toLowerCase() === concept.name.toLowerCase()) {
15
- node.frequency++;
16
- return id;
20
+ edges = new Map();
21
+ mergeCandidates = new Map();
22
+ causalCandidates = [];
23
+ get capacityStop() {
24
+ return this.nodes.size >= 10_000 || this.edges.size >= 40_000;
25
+ }
26
+ async admitConcept(input) {
27
+ const gate = evaluateConceptGate(input, {
28
+ capacityAdmitStop: this.capacityStop,
29
+ });
30
+ if (!gate.ok) {
31
+ return { action: 'rejected', reason: gate.reason, message: gate.message };
32
+ }
33
+ const key = normName(input.name);
34
+ const sameName = [...this.nodes.values()].find((n) => normName(n.name) === key);
35
+ if (sameName) {
36
+ const conflict = this.fingerprintConflict(sameName, input);
37
+ if (conflict) {
38
+ const id = this.insertNode(input);
39
+ const candidateId = this.pushMergeCandidate(sameName.id, id, conflict);
40
+ return { action: 'merge_candidate', id, candidateId, reason: 'fingerprint_conflict' };
17
41
  }
42
+ // 指纹兼容 → 合并
43
+ sameName.frequency += 1;
44
+ sameName.updatedAt = Date.now();
45
+ for (const mid of input.memoryIds ?? []) {
46
+ if (!sameName.memoryIds.includes(mid))
47
+ sameName.memoryIds.push(mid);
48
+ }
49
+ if (input.description && !sameName.description) {
50
+ sameName.description = input.description;
51
+ }
52
+ return { action: 'merged', id: sameName.id, reason: 'ok' };
53
+ }
54
+ // embedding 近邻 → merge_candidate(不自动合)
55
+ if (this.nodes.size > 0) {
56
+ // 无 embedding 时跳过;有则由上层 Sqlite 路径处理
57
+ }
58
+ const id = this.insertNode(input);
59
+ return { action: 'created', id, reason: 'ok' };
60
+ }
61
+ insertNode(input) {
62
+ const id = `cpt_${randomUUID().slice(0, 8)}`;
63
+ const now = Date.now();
64
+ this.nodes.set(id, {
65
+ id,
66
+ name: input.name.trim(),
67
+ kind: input.kind,
68
+ description: input.description,
69
+ frequency: 1,
70
+ memoryIds: [...(input.memoryIds ?? [])],
71
+ domain: [...(input.domain ?? [])],
72
+ status: 'shadow',
73
+ embedding: null,
74
+ createdAt: now,
75
+ updatedAt: now,
76
+ });
77
+ return id;
78
+ }
79
+ /** 义项指纹冲突:kind 不同或论域无交集且双方皆非空 */
80
+ fingerprintConflict(existing, input) {
81
+ if (existing.kind !== input.kind)
82
+ return `kind:${existing.kind}≠${input.kind}`;
83
+ const a = new Set(existing.domain);
84
+ const b = new Set(input.domain ?? []);
85
+ if (a.size > 0 && b.size > 0) {
86
+ const overlap = [...b].some((d) => a.has(d));
87
+ if (!overlap)
88
+ return 'domain_disjoint';
18
89
  }
19
- const id = randomUUID().slice(0, 8);
20
- this.nodes.set(id, { ...concept, id, frequency: 1, memoryIds: [] });
90
+ return null;
91
+ }
92
+ pushMergeCandidate(existingId, newId, reason) {
93
+ const id = `mrg_${randomUUID().slice(0, 8)}`;
94
+ this.mergeCandidates.set(id, {
95
+ id,
96
+ leftId: existingId,
97
+ rightId: newId,
98
+ reason,
99
+ distance: null,
100
+ fingerprintDiff: [reason],
101
+ status: 'open',
102
+ createdAt: Date.now(),
103
+ });
21
104
  return id;
22
105
  }
23
- async addEdge(edge) {
24
- // 避免重复边
25
- const exists = this.edges.some(e => e.sourceId === edge.sourceId && e.targetId === edge.targetId && e.relationType === edge.relationType);
26
- if (!exists) {
27
- this.edges.push(edge);
28
- }
29
- }
30
- async queryRelated(conceptName, depth = 1) {
31
- const relatedNodes = new Map();
32
- const relatedEdges = [];
33
- // 找到起始概念
34
- let startId = null;
35
- for (const [id, node] of this.nodes) {
36
- if (node.name.toLowerCase().includes(conceptName.toLowerCase())) {
37
- startId = id;
38
- relatedNodes.set(id, node);
39
- break;
40
- }
106
+ collectPairMemoryIds(sourceId, targetId) {
107
+ const ids = new Set();
108
+ for (const e of this.edges.values()) {
109
+ const pair = (e.sourceId === sourceId && e.targetId === targetId) ||
110
+ (e.sourceId === targetId && e.targetId === sourceId);
111
+ if (!pair)
112
+ continue;
113
+ for (const mid of e.basis.memoryIds)
114
+ ids.add(mid);
41
115
  }
42
- if (!startId)
43
- return { nodes: [], edges: [] };
44
- // BFS 查找相关概念
45
- const queue = [{ id: startId, currentDepth: 0 }];
46
- const visited = new Set([startId]);
47
- while (queue.length > 0) {
48
- const { id, currentDepth } = queue.shift();
49
- if (currentDepth >= depth)
116
+ for (const c of this.causalCandidates) {
117
+ const pair = (c.sourceId === sourceId && c.targetId === targetId) ||
118
+ (c.sourceId === targetId && c.targetId === sourceId);
119
+ if (!pair)
50
120
  continue;
51
- for (const edge of this.edges) {
52
- let neighborId = null;
53
- if (edge.sourceId === id)
54
- neighborId = edge.targetId;
55
- else if (edge.targetId === id)
56
- neighborId = edge.sourceId;
57
- if (neighborId && !visited.has(neighborId)) {
58
- visited.add(neighborId);
59
- const node = this.nodes.get(neighborId);
60
- if (node) {
61
- relatedNodes.set(neighborId, node);
62
- relatedEdges.push(edge);
63
- queue.push({ id: neighborId, currentDepth: currentDepth + 1 });
64
- }
65
- }
121
+ for (const mid of c.memoryIds)
122
+ ids.add(mid);
123
+ }
124
+ return [...ids];
125
+ }
126
+ async admitEdge(input) {
127
+ const priorIds = this.collectPairMemoryIds(input.sourceId, input.targetId);
128
+ const memoryIds = [...new Set([...priorIds, ...(input.basis.memoryIds ?? [])])];
129
+ const license = licenseEdge({
130
+ relationType: input.relationType,
131
+ evidenceClass: input.basis.evidenceClass,
132
+ cue: input.basis.cue,
133
+ evidenceText: input.evidenceText,
134
+ memoryIds,
135
+ });
136
+ if (license.status === 'rejected') {
137
+ return {
138
+ action: 'rejected',
139
+ reason: license.reason,
140
+ message: license.message,
141
+ };
142
+ }
143
+ if (license.status === 'candidate_only') {
144
+ await this.addCausalCandidate({
145
+ sourceId: input.sourceId,
146
+ targetId: input.targetId,
147
+ memoryIds: input.basis.memoryIds,
148
+ cue: input.basis.cue,
149
+ note: license.message,
150
+ });
151
+ return {
152
+ action: 'candidate_only',
153
+ reason: license.reason,
154
+ message: license.message,
155
+ };
156
+ }
157
+ const source = this.nodes.get(input.sourceId);
158
+ const target = this.nodes.get(input.targetId);
159
+ if (!source || !target) {
160
+ return { action: 'rejected', reason: 'invalid_relation', message: 'endpoint missing' };
161
+ }
162
+ const relationType = license.relationType;
163
+ const status = license.status === 'active' ? 'active' : 'shadow';
164
+ const existingKey = [...this.edges.entries()].find(([, e]) => e.sourceId === input.sourceId &&
165
+ e.targetId === input.targetId &&
166
+ e.relationType === relationType);
167
+ const now = Date.now();
168
+ if (existingKey) {
169
+ const [, edge] = existingKey;
170
+ edge.strength = Math.max(edge.strength, input.strength);
171
+ edge.updatedAt = now;
172
+ for (const mid of input.basis.memoryIds) {
173
+ if (!edge.basis.memoryIds.includes(mid))
174
+ edge.basis.memoryIds.push(mid);
66
175
  }
176
+ if (status === 'active' && edge.status === 'shadow')
177
+ edge.status = 'active';
178
+ return {
179
+ action: license.status === 'demoted' ? 'demoted' : status,
180
+ edgeId: edge.id,
181
+ relationType,
182
+ reason: license.reason,
183
+ };
67
184
  }
185
+ const edgeId = `edge_${randomUUID().slice(0, 8)}`;
186
+ const basis = {
187
+ memoryIds: [...input.basis.memoryIds],
188
+ cue: input.basis.cue,
189
+ evidenceClass: input.basis.evidenceClass,
190
+ licensedAt: input.basis.licensedAt ?? now,
191
+ };
192
+ this.edges.set(edgeId, {
193
+ id: edgeId,
194
+ sourceId: input.sourceId,
195
+ targetId: input.targetId,
196
+ relationType,
197
+ strength: Math.min(1, Math.max(0, input.strength)),
198
+ description: input.description,
199
+ status,
200
+ basis,
201
+ createdAt: now,
202
+ updatedAt: now,
203
+ });
68
204
  return {
69
- nodes: Array.from(relatedNodes.values()),
70
- edges: relatedEdges,
205
+ action: license.status === 'demoted' ? 'demoted' : status,
206
+ edgeId,
207
+ relationType,
208
+ reason: license.reason,
71
209
  };
72
210
  }
73
- async extractFromText(text, memoryId) {
74
- // P0 基础版:简单关键词提取
75
- // 提取大写开头的词作为概念候选
76
- const conceptPattern = /[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*/g;
77
- const matches = text.match(conceptPattern) ?? [];
78
- const conceptIds = [];
79
- for (const match of new Set(matches)) {
80
- if (match.length < 3 || match.length > 50)
211
+ async addCausalCandidate(input) {
212
+ this.causalCandidates.push({
213
+ id: `causal_${randomUUID().slice(0, 8)}`,
214
+ ...input,
215
+ createdAt: Date.now(),
216
+ });
217
+ }
218
+ async listMergeCandidates(limit = 50) {
219
+ return [...this.mergeCandidates.values()]
220
+ .filter((c) => c.status === 'open')
221
+ .slice(0, limit);
222
+ }
223
+ async resolveMerge(id, action) {
224
+ const cand = this.mergeCandidates.get(id);
225
+ if (!cand)
226
+ return;
227
+ cand.status =
228
+ action === 'merge' ? 'merged' : action === 'keep_split' ? 'kept_split' : 'dropped';
229
+ cand.resolvedAt = Date.now();
230
+ cand.resolvedAction = action;
231
+ if (action !== 'merge')
232
+ return;
233
+ const left = this.nodes.get(cand.leftId);
234
+ const right = this.nodes.get(cand.rightId);
235
+ if (!left || !right || left.id === right.id)
236
+ return;
237
+ left.frequency += right.frequency;
238
+ for (const mid of right.memoryIds) {
239
+ if (!left.memoryIds.includes(mid))
240
+ left.memoryIds.push(mid);
241
+ }
242
+ // 迁移边;同 pair 同类型去重,丢自环
243
+ const seen = new Set();
244
+ for (const e of [...this.edges.values()]) {
245
+ if (e.sourceId === right.id)
246
+ e.sourceId = left.id;
247
+ if (e.targetId === right.id)
248
+ e.targetId = left.id;
249
+ if (e.sourceId === e.targetId) {
250
+ this.edges.delete(e.id);
251
+ continue;
252
+ }
253
+ const key = `${e.sourceId}|${e.targetId}|${e.relationType}`;
254
+ if (seen.has(key)) {
255
+ this.edges.delete(e.id);
256
+ }
257
+ else {
258
+ seen.add(key);
259
+ }
260
+ }
261
+ this.nodes.delete(right.id);
262
+ }
263
+ async reinforce(input) {
264
+ const e = Math.min(1, Math.max(0, input.evidenceStrength ?? 0.5));
265
+ for (const id of input.nodeIds ?? []) {
266
+ const n = this.nodes.get(id);
267
+ if (n) {
268
+ n.frequency += 1;
269
+ n.updatedAt = Date.now();
270
+ }
271
+ }
272
+ for (const id of input.edgeIds ?? []) {
273
+ const edge = this.edges.get(id);
274
+ if (edge) {
275
+ edge.strength = hebbianStrengthen(edge.strength, e);
276
+ edge.updatedAt = Date.now();
277
+ }
278
+ }
279
+ }
280
+ async counterEvidence(input) {
281
+ const edge = this.edges.get(input.edgeId);
282
+ if (!edge)
283
+ return;
284
+ edge.strength = counterEvidenceWeaken(edge.strength);
285
+ if (input.markOpposes)
286
+ edge.relationType = 'opposes';
287
+ if (input.memoryId && edge.basis.memoryIds.includes(input.memoryId)) {
288
+ edge.basis.memoryIds = edge.basis.memoryIds.filter((m) => m !== input.memoryId);
289
+ }
290
+ edge.updatedAt = Date.now();
291
+ }
292
+ async promote(ids, to) {
293
+ for (const id of ids) {
294
+ const n = this.nodes.get(id);
295
+ if (n) {
296
+ n.status = to;
297
+ n.updatedAt = Date.now();
298
+ }
299
+ const e = this.edges.get(id);
300
+ if (e) {
301
+ e.status = to;
302
+ e.updatedAt = Date.now();
303
+ }
304
+ }
305
+ }
306
+ async demote(ids, to) {
307
+ for (const id of ids) {
308
+ const n = this.nodes.get(id);
309
+ if (n) {
310
+ n.status = to;
311
+ n.updatedAt = Date.now();
312
+ }
313
+ const e = this.edges.get(id);
314
+ if (e) {
315
+ e.status = to;
316
+ e.updatedAt = Date.now();
317
+ }
318
+ }
319
+ }
320
+ async applyDecay(now = Date.now()) {
321
+ let decayedEdges = 0;
322
+ for (const edge of this.edges.values()) {
323
+ const days = daysBetween(edge.updatedAt, now);
324
+ if (days < 1)
325
+ continue;
326
+ const next = nextEdgeStrength(edge.strength, edge.relationType, days);
327
+ if (next < edge.strength - 1e-6) {
328
+ edge.strength = next;
329
+ edge.updatedAt = now;
330
+ decayedEdges += 1;
331
+ }
332
+ }
333
+ // GC:无 memory 支撑且无边
334
+ const connected = new Set();
335
+ for (const e of this.edges.values()) {
336
+ if (e.strength > DEFAULT_EDGE_DECAY_FLOOR) {
337
+ connected.add(e.sourceId);
338
+ connected.add(e.targetId);
339
+ }
340
+ }
341
+ let gcNodes = 0;
342
+ for (const n of [...this.nodes.values()]) {
343
+ if (!connected.has(n.id) && n.memoryIds.length === 0) {
344
+ this.nodes.delete(n.id);
345
+ gcNodes += 1;
346
+ }
347
+ }
348
+ let gcEdges = 0;
349
+ for (const e of [...this.edges.values()]) {
350
+ if (!this.nodes.has(e.sourceId) || !this.nodes.has(e.targetId)) {
351
+ this.edges.delete(e.id);
352
+ gcEdges += 1;
353
+ }
354
+ }
355
+ return { decayedEdges, gcNodes, gcEdges };
356
+ }
357
+ async spreadingActivate(seeds, options) {
358
+ const depth = options?.depth ?? 2;
359
+ const delta = options?.delta ?? 0.55;
360
+ const tau = options?.tau ?? 0.08;
361
+ const limit = options?.limit ?? 40;
362
+ const statuses = new Set(options?.statuses ?? DEFAULT_RETRIEVE_STATUSES);
363
+ const seedIds = [];
364
+ const activation = new Map();
365
+ const seedSet = new Set(seeds.map((s) => normName(s)));
366
+ for (const n of this.nodes.values()) {
367
+ if (!statuses.has(n.status))
81
368
  continue;
82
- const id = await this.addConcept({ name: match });
83
- const node = this.nodes.get(id);
84
- if (node && !node.memoryIds.includes(memoryId)) {
85
- node.memoryIds.push(memoryId);
369
+ const key = normName(n.name);
370
+ const hit = seedSet.has(key) ||
371
+ [...seedSet].some((s) => key.includes(s) || s.includes(key)) ||
372
+ [...seedSet].some((s) => (n.description ?? '').toLowerCase().includes(s));
373
+ if (hit) {
374
+ seedIds.push(n.id);
375
+ activation.set(n.id, 1);
86
376
  }
87
- conceptIds.push(id);
88
377
  }
89
- // 建立共现关系(同一文本中出现的概念之间)
90
- for (let i = 0; i < conceptIds.length; i++) {
91
- for (let j = i + 1; j < conceptIds.length; j++) {
92
- await this.addEdge({
93
- sourceId: conceptIds[i],
94
- targetId: conceptIds[j],
95
- relationType: 'related',
96
- strength: 0.5,
97
- });
378
+ // 扩散
379
+ const adj = new Map();
380
+ for (const e of this.edges.values()) {
381
+ if (!this.nodes.has(e.sourceId) || !this.nodes.has(e.targetId))
382
+ continue;
383
+ const src = this.nodes.get(e.sourceId);
384
+ const tgt = this.nodes.get(e.targetId);
385
+ if (!statuses.has(src.status) || !statuses.has(tgt.status))
386
+ continue;
387
+ if (!adj.has(e.sourceId))
388
+ adj.set(e.sourceId, []);
389
+ if (!adj.has(e.targetId))
390
+ adj.set(e.targetId, []);
391
+ adj.get(e.sourceId).push({ to: e.targetId, w: e.strength });
392
+ adj.get(e.targetId).push({ to: e.sourceId, w: e.strength });
393
+ }
394
+ let frontier = [...seedIds];
395
+ for (let d = 1; d <= depth; d++) {
396
+ const next = [];
397
+ for (const id of frontier) {
398
+ const a = activation.get(id) ?? 0;
399
+ for (const { to, w } of adj.get(id) ?? []) {
400
+ const v = a * w * Math.pow(delta, d);
401
+ const prev = activation.get(to) ?? 0;
402
+ if (v > prev && v >= tau) {
403
+ activation.set(to, Math.max(prev, v));
404
+ next.push(to);
405
+ }
406
+ }
98
407
  }
408
+ frontier = next;
409
+ if (frontier.length === 0)
410
+ break;
99
411
  }
412
+ const kept = [...activation.entries()]
413
+ .filter(([, a]) => a >= tau)
414
+ .sort((a, b) => b[1] - a[1])
415
+ .slice(0, limit);
416
+ const nodeIds = new Set(kept.map(([id]) => id));
417
+ const nodes = [...nodeIds]
418
+ .map((id) => this.nodes.get(id))
419
+ .filter(Boolean);
420
+ const edges = [...this.edges.values()].filter((e) => nodeIds.has(e.sourceId) && nodeIds.has(e.targetId));
421
+ return {
422
+ nodes,
423
+ edges,
424
+ activation: Object.fromEntries(kept),
425
+ seeds: seedIds,
426
+ };
100
427
  }
101
428
  async getFullGraph() {
102
429
  return {
103
- nodes: Array.from(this.nodes.values()),
104
- edges: [...this.edges],
430
+ nodes: [...this.nodes.values()],
431
+ edges: [...this.edges.values()],
432
+ };
433
+ }
434
+ async stats() {
435
+ const byStatus = {
436
+ shadow: 0,
437
+ active: 0,
438
+ strengthened: 0,
439
+ };
440
+ const byKind = {
441
+ entity: 0,
442
+ construct: 0,
443
+ method: 0,
444
+ problem: 0,
445
+ constraint: 0,
446
+ };
447
+ for (const n of this.nodes.values()) {
448
+ byStatus[n.status] += 1;
449
+ byKind[n.kind] += 1;
450
+ }
451
+ return {
452
+ nodes: this.nodes.size,
453
+ edges: this.edges.size,
454
+ byStatus,
455
+ byKind,
456
+ openMergeCandidates: [...this.mergeCandidates.values()].filter((c) => c.status === 'open').length,
457
+ causalCandidates: this.causalCandidates.length,
105
458
  };
106
459
  }
107
460
  }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Conceptualizer — 命题 + 证据语境 → 概念/关系假设 → 门控入库
3
+ *
4
+ * 唯一概念化入口。禁止 session 全文 ETL / 正则 extractFromText。
5
+ * LLM 判义项与关系假设;本模块做结构解析与持证执法。
6
+ *
7
+ * @module harness/memory/conceptualizer
8
+ */
9
+ import type { AdmitConceptResult, AdmitEdgeResult, ConceptGraphStore, ConceptKind, ConceptRelationType, MemoryStatus } from './types.js';
10
+ import { type EdgeLicenseOutcome } from './cognition-gates.js';
11
+ /** 概念化输入包 — 语境切片是消歧必需品 */
12
+ export interface ConceptualizerInput {
13
+ proposition: string;
14
+ memoryId: string;
15
+ memoryType: 'fact' | 'method' | 'norm';
16
+ evidence: string;
17
+ /** 证据周边语境(±N 消息或 anchor span);缺失时拒绝概念化 */
18
+ contextSlice: string;
19
+ memoryStatus?: MemoryStatus;
20
+ /** 用于 cue 校验的拼接文本(默认 evidence + contextSlice) */
21
+ evidenceText?: string;
22
+ }
23
+ /** LLM 原始候选(解析前) */
24
+ export interface RawConceptualizerOutput {
25
+ nodes?: unknown;
26
+ edges?: unknown;
27
+ rejected?: unknown;
28
+ }
29
+ export interface ConceptualizerNodeOut {
30
+ name: string;
31
+ kind: ConceptKind;
32
+ description?: string;
33
+ domain: string[];
34
+ supportCount: number;
35
+ admit: AdmitConceptResult;
36
+ }
37
+ export interface ConceptualizerEdgeOut {
38
+ fromName: string;
39
+ toName: string;
40
+ requestedType: ConceptRelationType;
41
+ license: EdgeLicenseOutcome;
42
+ admit?: AdmitEdgeResult;
43
+ }
44
+ export interface ConceptualizerResult {
45
+ nodes: ConceptualizerNodeOut[];
46
+ edges: ConceptualizerEdgeOut[];
47
+ rejected: Array<{
48
+ name: string;
49
+ reason: string;
50
+ }>;
51
+ }
52
+ /**
53
+ * 从 LLM 文本中提取 JSON 对象(`{nodes,edges}`)。
54
+ *
55
+ * @param text - LLM 输出
56
+ * @returns 解析结果或 null
57
+ */
58
+ export declare function parseConceptualizerJson(text: string): RawConceptualizerOutput | null;
59
+ /**
60
+ * 解析 + 门控 + 入库(store 可选时只评估不写)。
61
+ *
62
+ * @param raw - LLM 结构化输出或原文
63
+ * @param input - 输入包(须含 contextSlice)
64
+ * @param store - ConceptGraphStore;省略则只跑门控
65
+ */
66
+ export declare function conceptualizeAndAdmit(raw: RawConceptualizerOutput | string, input: ConceptualizerInput, store?: ConceptGraphStore): Promise<ConceptualizerResult>;