noormme 1.1.0 → 1.2.0
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.
- package/README.md +84 -65
- package/dist/cjs/agentic/ActionJournal.js +13 -9
- package/dist/cjs/agentic/CapabilityManager.js +35 -21
- package/dist/cjs/agentic/CognitiveRepository.js +19 -9
- package/dist/cjs/agentic/ContextBuffer.js +24 -12
- package/dist/cjs/agentic/Cortex.js +11 -4
- package/dist/cjs/agentic/EpisodicMemory.js +7 -5
- package/dist/cjs/agentic/PersonaManager.js +16 -8
- package/dist/cjs/agentic/PolicyEnforcer.js +31 -12
- package/dist/cjs/agentic/ResourceMonitor.js +4 -4
- package/dist/cjs/agentic/SessionCompressor.js +22 -14
- package/dist/cjs/agentic/SessionManager.js +36 -18
- package/dist/cjs/agentic/VectorIndexer.js +22 -18
- package/dist/cjs/agentic/improvement/AblationEngine.js +22 -15
- package/dist/cjs/agentic/improvement/ActionRefiner.js +12 -10
- package/dist/cjs/agentic/improvement/ConflictResolver.js +5 -5
- package/dist/cjs/agentic/improvement/CortexJanitor.js +30 -9
- package/dist/cjs/agentic/improvement/CuriosityEngine.js +27 -23
- package/dist/cjs/agentic/improvement/EvolutionRitual.js +4 -4
- package/dist/cjs/agentic/improvement/EvolutionaryPilot.js +16 -6
- package/dist/cjs/agentic/improvement/GoalArchitect.d.ts +2 -2
- package/dist/cjs/agentic/improvement/GoalArchitect.js +20 -18
- package/dist/cjs/agentic/improvement/GovernanceManager.js +19 -11
- package/dist/cjs/agentic/improvement/HiveLink.js +22 -15
- package/dist/cjs/agentic/improvement/KnowledgeDistiller.js +48 -32
- package/dist/cjs/agentic/improvement/RecursiveReasoner.js +40 -17
- package/dist/cjs/agentic/improvement/ReflectionEngine.js +10 -8
- package/dist/cjs/agentic/improvement/RitualOrchestrator.js +28 -22
- package/dist/cjs/agentic/improvement/RuleEngine.js +22 -17
- package/dist/cjs/agentic/improvement/SelfEvolution.js +24 -18
- package/dist/cjs/agentic/improvement/SelfTestRegistry.js +18 -15
- package/dist/cjs/agentic/improvement/SkillSynthesizer.js +42 -27
- package/dist/cjs/agentic/improvement/SovereignMetrics.js +19 -17
- package/dist/cjs/agentic/improvement/StrategicPlanner.js +120 -55
- package/dist/cjs/agentic/telemetry/CognitiveSynthesizer.js +26 -12
- package/dist/cjs/agentic/telemetry/EventHarvester.js +3 -2
- package/dist/cjs/agentic/telemetry/ResearchAlchemist.js +5 -2
- package/dist/cjs/cache/cache-manager.js +7 -4
- package/dist/cjs/cli/commands/analyze.js +5 -4
- package/dist/cjs/cli/commands/generate.js +81 -44
- package/dist/cjs/cli/commands/init.js +7 -3
- package/dist/cjs/cli/commands/inspect.js +139 -36
- package/dist/cjs/cli/commands/migrate.js +5 -4
- package/dist/cjs/cli/commands/optimize.js +4 -4
- package/dist/cjs/cli/commands/status.js +9 -7
- package/dist/cjs/cli/commands/watch.js +7 -6
- package/dist/cjs/cli/index.js +2 -2
- package/dist/cjs/cli/ui/spinner.d.ts +15 -0
- package/dist/cjs/cli/ui/spinner.js +76 -0
- package/dist/cjs/dialect/database-introspector.js +3 -1
- package/dist/cjs/dialect/postgresql/postgresql-driver.js +3 -1
- package/dist/cjs/dialect/postgresql/postgresql-features.js +18 -8
- package/dist/cjs/dialect/postgresql/postgresql-introspector.js +2 -2
- package/dist/cjs/dialect/sqlite/sqlite-auto-indexer.js +47 -33
- package/dist/cjs/dialect/sqlite/sqlite-auto-optimizer.js +8 -7
- package/dist/cjs/dialect/sqlite/sqlite-driver.js +2 -2
- package/dist/cjs/dialect/sqlite/sqlite-introspector.js +15 -12
- package/dist/cjs/edge-runtime/edge-config.js +21 -19
- package/dist/cjs/errors/NoormError.js +22 -20
- package/dist/cjs/helpers/agent-schema.js +2 -0
- package/dist/cjs/helpers/postgresql.js +7 -4
- package/dist/cjs/helpers/schema-evolution.js +31 -6
- package/dist/cjs/index.d.ts +3 -3
- package/dist/cjs/logging/logger.js +8 -4
- package/dist/cjs/migration/data_migrator.js +12 -11
- package/dist/cjs/migration/database_migration_manager.js +17 -13
- package/dist/cjs/migration/schema_differ.js +22 -14
- package/dist/cjs/migration/schema_introspector.js +8 -8
- package/dist/cjs/migration/type_mapper.js +68 -67
- package/dist/cjs/noormme.js +52 -37
- package/dist/cjs/performance/index.js +5 -5
- package/dist/cjs/performance/query-optimizer.js +26 -21
- package/dist/cjs/performance/services/cache-service.js +26 -16
- package/dist/cjs/performance/services/connection-factory.js +28 -23
- package/dist/cjs/performance/services/metrics-collector.js +41 -36
- package/dist/cjs/performance/utils/query-parser.js +15 -16
- package/dist/cjs/relationships/relationship-engine.js +10 -8
- package/dist/cjs/repository/repository-factory.js +97 -38
- package/dist/cjs/schema/core/coordinators/schema-discovery.coordinator.js +1 -3
- package/dist/cjs/schema/core/discovery/relationship-discovery.js +16 -16
- package/dist/cjs/schema/core/discovery/table-metadata-discovery.js +9 -9
- package/dist/cjs/schema/core/discovery/view-discovery.js +5 -4
- package/dist/cjs/schema/core/factories/discovery-factory.js +4 -4
- package/dist/cjs/schema/core/utils/name-generator.js +14 -5
- package/dist/cjs/schema/core/utils/type-mapper.js +24 -24
- package/dist/cjs/schema/dialects/postgresql/postgresql-discovery.coordinator.js +8 -7
- package/dist/cjs/schema/dialects/sqlite/discovery/sqlite-constraint-discovery.js +17 -15
- package/dist/cjs/schema/dialects/sqlite/discovery/sqlite-index-discovery.js +8 -8
- package/dist/cjs/schema/dialects/sqlite/introspection/sqlite-schema-introspector.js +6 -11
- package/dist/cjs/schema/dialects/sqlite/sqlite-discovery.coordinator.js +14 -13
- package/dist/cjs/schema/test/basic-schema-test.js +11 -9
- package/dist/cjs/schema/test/dialect-capabilities.test.js +6 -6
- package/dist/cjs/schema/test/discovery-factory.test.js +2 -2
- package/dist/cjs/schema/test/error-handling.test.js +8 -6
- package/dist/cjs/schema/test/integration.test.js +24 -18
- package/dist/cjs/schema/test/schema-discovery-coordinator.test.js +9 -9
- package/dist/cjs/schema/test/simple-schema-test.js +9 -9
- package/dist/cjs/schema/test/sqlite-discovery-coordinator.test.js +64 -48
- package/dist/cjs/schema/test/test-runner.js +3 -3
- package/dist/cjs/sqlite-migration/index.d.ts +2 -2
- package/dist/cjs/sqlite-migration/sqlite-migration-manager.js +21 -17
- package/dist/cjs/sqlite-migration/sqlite-migration-provider.js +38 -34
- package/dist/cjs/testing/test-utils.js +36 -34
- package/dist/cjs/types/index.d.ts +5 -2
- package/dist/cjs/types/index.js +6 -3
- package/dist/cjs/types/type-generator.js +46 -42
- package/dist/cjs/util/safe-sql-helpers.js +1 -1
- package/dist/cjs/util/security-validator.js +20 -9
- package/dist/cjs/utils/errorHelpers.js +20 -10
- package/dist/cjs/watch/schema-watcher.js +22 -23
- package/dist/esm/agentic/ActionJournal.js +13 -9
- package/dist/esm/agentic/CapabilityManager.js +35 -21
- package/dist/esm/agentic/CognitiveRepository.js +19 -9
- package/dist/esm/agentic/ContextBuffer.js +24 -12
- package/dist/esm/agentic/Cortex.js +11 -4
- package/dist/esm/agentic/EpisodicMemory.js +7 -5
- package/dist/esm/agentic/PersonaManager.js +16 -8
- package/dist/esm/agentic/PolicyEnforcer.js +31 -12
- package/dist/esm/agentic/ResourceMonitor.js +4 -4
- package/dist/esm/agentic/SessionCompressor.js +22 -14
- package/dist/esm/agentic/SessionManager.js +36 -18
- package/dist/esm/agentic/VectorIndexer.js +22 -18
- package/dist/esm/agentic/improvement/AblationEngine.js +22 -15
- package/dist/esm/agentic/improvement/ActionRefiner.js +12 -10
- package/dist/esm/agentic/improvement/ConflictResolver.js +5 -5
- package/dist/esm/agentic/improvement/CortexJanitor.js +30 -9
- package/dist/esm/agentic/improvement/CuriosityEngine.js +27 -23
- package/dist/esm/agentic/improvement/EvolutionRitual.js +4 -4
- package/dist/esm/agentic/improvement/EvolutionaryPilot.js +16 -6
- package/dist/esm/agentic/improvement/GoalArchitect.d.ts +2 -2
- package/dist/esm/agentic/improvement/GoalArchitect.js +20 -18
- package/dist/esm/agentic/improvement/GovernanceManager.js +19 -11
- package/dist/esm/agentic/improvement/HiveLink.js +22 -15
- package/dist/esm/agentic/improvement/KnowledgeDistiller.js +48 -32
- package/dist/esm/agentic/improvement/RecursiveReasoner.js +40 -17
- package/dist/esm/agentic/improvement/ReflectionEngine.js +10 -8
- package/dist/esm/agentic/improvement/RitualOrchestrator.js +28 -22
- package/dist/esm/agentic/improvement/RuleEngine.js +22 -17
- package/dist/esm/agentic/improvement/SelfEvolution.js +24 -18
- package/dist/esm/agentic/improvement/SelfTestRegistry.js +18 -15
- package/dist/esm/agentic/improvement/SkillSynthesizer.js +42 -27
- package/dist/esm/agentic/improvement/SovereignMetrics.js +19 -17
- package/dist/esm/agentic/improvement/StrategicPlanner.js +120 -55
- package/dist/esm/agentic/telemetry/CognitiveSynthesizer.js +26 -12
- package/dist/esm/agentic/telemetry/EventHarvester.js +3 -2
- package/dist/esm/agentic/telemetry/ResearchAlchemist.js +5 -2
- package/dist/esm/cache/cache-manager.js +7 -4
- package/dist/esm/cli/commands/analyze.js +5 -4
- package/dist/esm/cli/commands/generate.js +82 -45
- package/dist/esm/cli/commands/init.js +8 -4
- package/dist/esm/cli/commands/inspect.js +140 -37
- package/dist/esm/cli/commands/migrate.js +5 -4
- package/dist/esm/cli/commands/optimize.js +4 -4
- package/dist/esm/cli/commands/status.js +9 -7
- package/dist/esm/cli/commands/watch.js +7 -6
- package/dist/esm/cli/index.js +2 -2
- package/dist/esm/cli/ui/spinner.d.ts +15 -0
- package/dist/esm/cli/ui/spinner.js +70 -0
- package/dist/esm/dialect/database-introspector.js +3 -1
- package/dist/esm/dialect/postgresql/postgresql-driver.js +3 -1
- package/dist/esm/dialect/postgresql/postgresql-features.js +18 -8
- package/dist/esm/dialect/postgresql/postgresql-introspector.js +2 -2
- package/dist/esm/dialect/sqlite/sqlite-auto-indexer.js +47 -33
- package/dist/esm/dialect/sqlite/sqlite-auto-optimizer.js +8 -7
- package/dist/esm/dialect/sqlite/sqlite-driver.js +2 -2
- package/dist/esm/dialect/sqlite/sqlite-introspector.js +15 -12
- package/dist/esm/dynamic/dynamic.js +1 -1
- package/dist/esm/edge-runtime/edge-config.js +21 -19
- package/dist/esm/errors/NoormError.js +22 -20
- package/dist/esm/helpers/agent-schema.js +2 -0
- package/dist/esm/helpers/postgresql.js +7 -4
- package/dist/esm/helpers/schema-evolution.js +31 -6
- package/dist/esm/index.d.ts +3 -3
- package/dist/esm/index.js +2 -2
- package/dist/esm/logging/logger.js +8 -4
- package/dist/esm/migration/data_migrator.js +12 -11
- package/dist/esm/migration/database_migration_manager.js +18 -14
- package/dist/esm/migration/schema_differ.js +22 -14
- package/dist/esm/migration/schema_introspector.js +8 -8
- package/dist/esm/migration/type_mapper.js +68 -67
- package/dist/esm/noormme.js +52 -37
- package/dist/esm/performance/index.js +5 -5
- package/dist/esm/performance/query-optimizer.js +26 -21
- package/dist/esm/performance/services/cache-service.js +26 -16
- package/dist/esm/performance/services/connection-factory.js +28 -23
- package/dist/esm/performance/services/metrics-collector.js +41 -36
- package/dist/esm/performance/utils/query-parser.js +15 -16
- package/dist/esm/raw-builder/sql.js +1 -1
- package/dist/esm/relationships/relationship-engine.js +10 -8
- package/dist/esm/repository/repository-factory.js +98 -39
- package/dist/esm/schema/builders/alter-table-add-index-builder.js +1 -1
- package/dist/esm/schema/builders/create-index-builder.js +2 -2
- package/dist/esm/schema/core/coordinators/schema-discovery.coordinator.js +1 -3
- package/dist/esm/schema/core/discovery/relationship-discovery.js +16 -16
- package/dist/esm/schema/core/discovery/table-metadata-discovery.js +9 -9
- package/dist/esm/schema/core/discovery/view-discovery.js +5 -4
- package/dist/esm/schema/core/factories/discovery-factory.js +4 -4
- package/dist/esm/schema/core/utils/name-generator.js +14 -5
- package/dist/esm/schema/core/utils/type-mapper.js +24 -24
- package/dist/esm/schema/dialects/postgresql/postgresql-discovery.coordinator.js +8 -7
- package/dist/esm/schema/dialects/sqlite/discovery/sqlite-constraint-discovery.js +17 -15
- package/dist/esm/schema/dialects/sqlite/discovery/sqlite-index-discovery.js +8 -8
- package/dist/esm/schema/dialects/sqlite/introspection/sqlite-schema-introspector.js +6 -11
- package/dist/esm/schema/dialects/sqlite/sqlite-discovery.coordinator.js +14 -13
- package/dist/esm/schema/test/basic-schema-test.js +11 -9
- package/dist/esm/schema/test/dialect-capabilities.test.js +6 -6
- package/dist/esm/schema/test/discovery-factory.test.js +2 -2
- package/dist/esm/schema/test/error-handling.test.js +8 -6
- package/dist/esm/schema/test/integration.test.js +24 -18
- package/dist/esm/schema/test/schema-discovery-coordinator.test.js +9 -9
- package/dist/esm/schema/test/simple-schema-test.js +9 -9
- package/dist/esm/schema/test/sqlite-discovery-coordinator.test.js +64 -48
- package/dist/esm/schema/test/test-runner.js +3 -3
- package/dist/esm/sqlite-migration/index.d.ts +2 -2
- package/dist/esm/sqlite-migration/sqlite-migration-manager.js +21 -17
- package/dist/esm/sqlite-migration/sqlite-migration-provider.js +38 -34
- package/dist/esm/testing/test-utils.js +36 -34
- package/dist/esm/types/index.d.ts +5 -2
- package/dist/esm/types/index.js +6 -3
- package/dist/esm/types/type-generator.js +46 -42
- package/dist/esm/util/safe-sql-helpers.js +1 -1
- package/dist/esm/util/security-validator.js +20 -9
- package/dist/esm/utils/errorHelpers.js +21 -11
- package/dist/esm/watch/schema-watcher.js +22 -23
- package/package.json +40 -44
|
@@ -25,12 +25,12 @@ export class HiveLink {
|
|
|
25
25
|
async broadcastKnowledge(minConfidence = 0.9) {
|
|
26
26
|
console.log(`[HiveLink] Broadcasting knowledge with confidence >= ${minConfidence}`);
|
|
27
27
|
// Find high-confidence items that are "local" (have a source_session_id)
|
|
28
|
-
const items = await this.typedDb
|
|
28
|
+
const items = (await this.typedDb
|
|
29
29
|
.selectFrom(this.knowledgeTable)
|
|
30
30
|
.selectAll()
|
|
31
31
|
.where('confidence', '>=', minConfidence)
|
|
32
32
|
.where('source_session_id', 'is not', null) // Only local items
|
|
33
|
-
.execute();
|
|
33
|
+
.execute());
|
|
34
34
|
let promotedCount = 0;
|
|
35
35
|
for (const item of items) {
|
|
36
36
|
// Check if a global version already exists
|
|
@@ -49,7 +49,7 @@ export class HiveLink {
|
|
|
49
49
|
.updateTable(this.knowledgeTable)
|
|
50
50
|
.set({
|
|
51
51
|
confidence: newConfidence,
|
|
52
|
-
updated_at: new Date()
|
|
52
|
+
updated_at: new Date(),
|
|
53
53
|
})
|
|
54
54
|
.where('id', '=', existingGlobal.id)
|
|
55
55
|
.execute();
|
|
@@ -70,10 +70,10 @@ export class HiveLink {
|
|
|
70
70
|
metadata: JSON.stringify({
|
|
71
71
|
...item.metadata,
|
|
72
72
|
promoted_from: item.id,
|
|
73
|
-
promoted_at: new Date()
|
|
73
|
+
promoted_at: new Date(),
|
|
74
74
|
}),
|
|
75
75
|
created_at: new Date(),
|
|
76
|
-
updated_at: new Date()
|
|
76
|
+
updated_at: new Date(),
|
|
77
77
|
})
|
|
78
78
|
.execute();
|
|
79
79
|
promotedCount++;
|
|
@@ -92,7 +92,7 @@ export class HiveLink {
|
|
|
92
92
|
.updateTable(this.knowledgeTable)
|
|
93
93
|
.set({
|
|
94
94
|
confidence: sql `MIN(1.0, confidence + ${boostFactor})`,
|
|
95
|
-
updated_at: new Date()
|
|
95
|
+
updated_at: new Date(),
|
|
96
96
|
})
|
|
97
97
|
.where('tags', 'like', `%"${domainTag}"%`)
|
|
98
98
|
.where('confidence', '<', 1.0)
|
|
@@ -106,7 +106,8 @@ export class HiveLink {
|
|
|
106
106
|
* High-Throughput Refactor: Batch updates and optimized set-based checks.
|
|
107
107
|
*/
|
|
108
108
|
async broadcastSkills() {
|
|
109
|
-
if (!this.config.evolution?.enableHiveLink &&
|
|
109
|
+
if (!this.config.evolution?.enableHiveLink &&
|
|
110
|
+
this.config.evolution !== undefined) {
|
|
110
111
|
console.log('[HiveLink] Skill broadcasting disabled by config.');
|
|
111
112
|
return 0;
|
|
112
113
|
}
|
|
@@ -117,7 +118,9 @@ export class HiveLink {
|
|
|
117
118
|
// 1. Resolve Verified Skills with "Survival of the Fittest" logic
|
|
118
119
|
const verifiedSkills = await this.cortex.capabilities.getCapabilities('verified');
|
|
119
120
|
for (const skill of verifiedSkills) {
|
|
120
|
-
const meta = typeof skill.metadata === 'string'
|
|
121
|
+
const meta = typeof skill.metadata === 'string'
|
|
122
|
+
? JSON.parse(skill.metadata)
|
|
123
|
+
: skill.metadata || {};
|
|
121
124
|
if (meta.broadcasted)
|
|
122
125
|
continue;
|
|
123
126
|
// Check for competing global versions
|
|
@@ -144,15 +147,16 @@ export class HiveLink {
|
|
|
144
147
|
}
|
|
145
148
|
}
|
|
146
149
|
if (shouldBroadcast) {
|
|
147
|
-
await trx
|
|
150
|
+
await trx
|
|
151
|
+
.updateTable(capTable)
|
|
148
152
|
.set({
|
|
149
153
|
metadata: JSON.stringify({
|
|
150
154
|
...meta,
|
|
151
155
|
broadcasted: true,
|
|
152
156
|
hive_verified: true,
|
|
153
157
|
broadcasted_at: new Date(),
|
|
154
|
-
conflict_resolved: !!competitor
|
|
155
|
-
})
|
|
158
|
+
conflict_resolved: !!competitor,
|
|
159
|
+
}),
|
|
156
160
|
})
|
|
157
161
|
.where('id', '=', skill.id)
|
|
158
162
|
.execute();
|
|
@@ -162,16 +166,19 @@ export class HiveLink {
|
|
|
162
166
|
// 2. Broadcast Blacklisted Skills (Immediate Immune Propagations)
|
|
163
167
|
const blacklisted = await this.cortex.capabilities.getCapabilities('blacklisted');
|
|
164
168
|
for (const skill of blacklisted) {
|
|
165
|
-
const meta = typeof skill.metadata === 'string'
|
|
169
|
+
const meta = typeof skill.metadata === 'string'
|
|
170
|
+
? JSON.parse(skill.metadata)
|
|
171
|
+
: skill.metadata || {};
|
|
166
172
|
if (!meta.broadcasted) {
|
|
167
|
-
await trx
|
|
173
|
+
await trx
|
|
174
|
+
.updateTable(capTable)
|
|
168
175
|
.set({
|
|
169
176
|
metadata: JSON.stringify({
|
|
170
177
|
...meta,
|
|
171
178
|
broadcasted: true,
|
|
172
179
|
hive_blacklisted: true,
|
|
173
|
-
blocked_at: new Date()
|
|
174
|
-
})
|
|
180
|
+
blocked_at: new Date(),
|
|
181
|
+
}),
|
|
175
182
|
})
|
|
176
183
|
.where('id', '=', skill.id)
|
|
177
184
|
.execute();
|
|
@@ -40,8 +40,10 @@ export class KnowledgeDistiller {
|
|
|
40
40
|
.where('entity', '=', entity)
|
|
41
41
|
.where('fact', '=', fact)
|
|
42
42
|
.executeTakeFirst();
|
|
43
|
-
if (quickMatch &&
|
|
44
|
-
|
|
43
|
+
if (quickMatch &&
|
|
44
|
+
quickMatch.status === 'verified' &&
|
|
45
|
+
source !== 'user') {
|
|
46
|
+
return (await this.getKnowledgeByEntity(entity)).find((k) => k.fact === fact);
|
|
45
47
|
}
|
|
46
48
|
}
|
|
47
49
|
this.bloomFilter.add(factHash);
|
|
@@ -57,10 +59,14 @@ export class KnowledgeDistiller {
|
|
|
57
59
|
.executeTakeFirst();
|
|
58
60
|
if (existing) {
|
|
59
61
|
// Merge tags
|
|
60
|
-
const existingTags = existing.tags
|
|
62
|
+
const existingTags = existing.tags
|
|
63
|
+
? JSON.parse(existing.tags)
|
|
64
|
+
: [];
|
|
61
65
|
const mergedTags = Array.from(new Set([...existingTags, ...tags]));
|
|
62
66
|
// Merge metadata
|
|
63
|
-
const existingMeta = existing.metadata
|
|
67
|
+
const existingMeta = existing.metadata
|
|
68
|
+
? JSON.parse(existing.metadata)
|
|
69
|
+
: {};
|
|
64
70
|
// Hallucination Prevention: Tracking contributing sessions
|
|
65
71
|
const sessions = new Set(existingMeta.sessions || []);
|
|
66
72
|
if (sourceSessionId)
|
|
@@ -69,7 +75,7 @@ export class KnowledgeDistiller {
|
|
|
69
75
|
...existingMeta,
|
|
70
76
|
...metadata,
|
|
71
77
|
sessions: Array.from(sessions),
|
|
72
|
-
session_count: sessions.size
|
|
78
|
+
session_count: sessions.size,
|
|
73
79
|
};
|
|
74
80
|
// Source weighting: User verification boosts confidence faster
|
|
75
81
|
const boost = source === 'user' ? 0.2 : 0.05;
|
|
@@ -87,7 +93,7 @@ export class KnowledgeDistiller {
|
|
|
87
93
|
tags: JSON.stringify(mergedTags),
|
|
88
94
|
metadata: JSON.stringify(mergedMeta),
|
|
89
95
|
updated_at: new Date(),
|
|
90
|
-
source_session_id: sourceSessionId ?? existing.source_session_id
|
|
96
|
+
source_session_id: sourceSessionId ?? existing.source_session_id,
|
|
91
97
|
})
|
|
92
98
|
.where('id', '=', existing.id)
|
|
93
99
|
.returningAll()
|
|
@@ -101,7 +107,7 @@ export class KnowledgeDistiller {
|
|
|
101
107
|
...metadata,
|
|
102
108
|
source,
|
|
103
109
|
sessions: sourceSessionId ? [sourceSessionId] : [],
|
|
104
|
-
session_count: sourceSessionId ? 1 : 0
|
|
110
|
+
session_count: sourceSessionId ? 1 : 0,
|
|
105
111
|
};
|
|
106
112
|
const created = await trx
|
|
107
113
|
.insertInto(this.knowledgeTable)
|
|
@@ -114,7 +120,7 @@ export class KnowledgeDistiller {
|
|
|
114
120
|
tags: JSON.stringify(tags),
|
|
115
121
|
metadata: JSON.stringify(initialMeta),
|
|
116
122
|
created_at: new Date(),
|
|
117
|
-
updated_at: new Date()
|
|
123
|
+
updated_at: new Date(),
|
|
118
124
|
})
|
|
119
125
|
.returningAll()
|
|
120
126
|
.executeTakeFirstOrThrow();
|
|
@@ -136,7 +142,9 @@ export class KnowledgeDistiller {
|
|
|
136
142
|
.executeTakeFirst();
|
|
137
143
|
if (!existing)
|
|
138
144
|
return null;
|
|
139
|
-
const metadata = typeof existing.metadata === 'string'
|
|
145
|
+
const metadata = typeof existing.metadata === 'string'
|
|
146
|
+
? JSON.parse(existing.metadata)
|
|
147
|
+
: existing.metadata || {};
|
|
140
148
|
// Hallucination Guard: Cap confidence for non-user sources until cross-session verification
|
|
141
149
|
let maxConfidence = 1.0;
|
|
142
150
|
if (metadata.source !== 'user' && (metadata.session_count || 0) < 3) {
|
|
@@ -154,7 +162,7 @@ export class KnowledgeDistiller {
|
|
|
154
162
|
.set({
|
|
155
163
|
confidence: newConfidence,
|
|
156
164
|
status: newStatus,
|
|
157
|
-
updated_at: new Date()
|
|
165
|
+
updated_at: new Date(),
|
|
158
166
|
})
|
|
159
167
|
.where('id', '=', id)
|
|
160
168
|
.returningAll()
|
|
@@ -172,14 +180,14 @@ export class KnowledgeDistiller {
|
|
|
172
180
|
.where('entity', '=', entity)
|
|
173
181
|
.orderBy('confidence', 'desc');
|
|
174
182
|
const items = (await query.execute());
|
|
175
|
-
const parsed = items.map(i => this.parseKnowledge(i));
|
|
183
|
+
const parsed = items.map((i) => this.parseKnowledge(i));
|
|
176
184
|
let filtered = parsed;
|
|
177
185
|
if (filterTags && filterTags.length > 0) {
|
|
178
|
-
filtered = parsed.filter(item => item.tags?.some(tag => filterTags.includes(tag)));
|
|
186
|
+
filtered = parsed.filter((item) => item.tags?.some((tag) => filterTags.includes(tag)));
|
|
179
187
|
}
|
|
180
188
|
// Record hits asynchronously
|
|
181
189
|
for (const item of filtered) {
|
|
182
|
-
this.recordHit(item.id).catch(err => console.error(`[KnowledgeDistiller] Failed to record hit for ${item.id}:`, err));
|
|
190
|
+
this.recordHit(item.id).catch((err) => console.error(`[KnowledgeDistiller] Failed to record hit for ${item.id}:`, err));
|
|
183
191
|
}
|
|
184
192
|
return filtered;
|
|
185
193
|
}
|
|
@@ -196,14 +204,14 @@ export class KnowledgeDistiller {
|
|
|
196
204
|
return;
|
|
197
205
|
const metadata = typeof existing.metadata === 'string'
|
|
198
206
|
? JSON.parse(existing.metadata)
|
|
199
|
-
:
|
|
207
|
+
: existing.metadata || {};
|
|
200
208
|
metadata.hit_count = (metadata.hit_count || 0) + 1;
|
|
201
209
|
metadata.last_retrieved_at = new Date().toISOString();
|
|
202
210
|
await this.db
|
|
203
211
|
.updateTable(this.knowledgeTable)
|
|
204
212
|
.set({
|
|
205
213
|
metadata: JSON.stringify(metadata),
|
|
206
|
-
updated_at: new Date()
|
|
214
|
+
updated_at: new Date(),
|
|
207
215
|
})
|
|
208
216
|
.where('id', '=', id)
|
|
209
217
|
.execute();
|
|
@@ -213,7 +221,7 @@ export class KnowledgeDistiller {
|
|
|
213
221
|
.values({
|
|
214
222
|
metric_name: `entity_hit_${existing.entity}`,
|
|
215
223
|
metric_value: 1,
|
|
216
|
-
created_at: new Date()
|
|
224
|
+
created_at: new Date(),
|
|
217
225
|
})
|
|
218
226
|
.execute();
|
|
219
227
|
}
|
|
@@ -230,7 +238,7 @@ export class KnowledgeDistiller {
|
|
|
230
238
|
const stn = Math.min(1.0, hitCount / ageInDays);
|
|
231
239
|
// Source Multiplier: User verified facts get 1.0, Assistant-generated 0.7
|
|
232
240
|
const sourceMult = metadata.source === 'user' ? 1.0 : 0.7;
|
|
233
|
-
return
|
|
241
|
+
return item.confidence * 0.4 + stn * 0.4 + sourceMult * 0.2;
|
|
234
242
|
}
|
|
235
243
|
/**
|
|
236
244
|
* Challenge existing knowledge with new evidence.
|
|
@@ -257,12 +265,18 @@ export class KnowledgeDistiller {
|
|
|
257
265
|
let newStatus = parsedItem.status;
|
|
258
266
|
if (parsedItem.confidence > 0.7) {
|
|
259
267
|
newStatus = 'disputed';
|
|
260
|
-
newMeta = {
|
|
268
|
+
newMeta = {
|
|
269
|
+
...newMeta,
|
|
270
|
+
status_reason: `Contradicted by: ${competingFact}`,
|
|
271
|
+
};
|
|
261
272
|
penalty = 0.1;
|
|
262
273
|
}
|
|
263
274
|
else {
|
|
264
275
|
newStatus = 'deprecated';
|
|
265
|
-
newMeta = {
|
|
276
|
+
newMeta = {
|
|
277
|
+
...newMeta,
|
|
278
|
+
status_reason: `Superseded by: ${competingFact}`,
|
|
279
|
+
};
|
|
266
280
|
penalty = 0.4;
|
|
267
281
|
}
|
|
268
282
|
const newConfidence = Math.max(0, parsedItem.confidence - penalty);
|
|
@@ -272,7 +286,7 @@ export class KnowledgeDistiller {
|
|
|
272
286
|
confidence: newConfidence,
|
|
273
287
|
status: newStatus,
|
|
274
288
|
metadata: JSON.stringify(newMeta),
|
|
275
|
-
updated_at: new Date()
|
|
289
|
+
updated_at: new Date(),
|
|
276
290
|
})
|
|
277
291
|
.where('id', '=', parsedItem.id)
|
|
278
292
|
.execute();
|
|
@@ -288,7 +302,7 @@ export class KnowledgeDistiller {
|
|
|
288
302
|
// 1. Structural/Syntactic Extraction (NER-style tokenization)
|
|
289
303
|
// Extract capitalized phrases (potential entities), quoted strings, and CamelCase identifiers
|
|
290
304
|
const tokens = item.fact.match(/([A-Z][a-z]+(?:\s[A-Z][a-z]+)*)|("[^"]+")|([a-z]+[A-Z][a-z]+)/g) || [];
|
|
291
|
-
const potentialEntities = Array.from(new Set(tokens.map(t => t.replace(/"/g, '').trim()))).filter(t => t.length > 2 && t !== item.entity);
|
|
305
|
+
const potentialEntities = Array.from(new Set(tokens.map((t) => t.replace(/"/g, '').trim()))).filter((t) => t.length > 2 && t !== item.entity);
|
|
292
306
|
if (potentialEntities.length > 0) {
|
|
293
307
|
const matches = await trx
|
|
294
308
|
.selectFrom(this.knowledgeTable)
|
|
@@ -342,7 +356,7 @@ export class KnowledgeDistiller {
|
|
|
342
356
|
await trxOrDb
|
|
343
357
|
.updateTable(this.linksTable)
|
|
344
358
|
.set({
|
|
345
|
-
metadata: metadata ? JSON.stringify(metadata) : null
|
|
359
|
+
metadata: metadata ? JSON.stringify(metadata) : null,
|
|
346
360
|
})
|
|
347
361
|
.where('id', '=', existing.id)
|
|
348
362
|
.execute();
|
|
@@ -355,7 +369,7 @@ export class KnowledgeDistiller {
|
|
|
355
369
|
target_id: targetId,
|
|
356
370
|
relationship,
|
|
357
371
|
metadata: metadata ? JSON.stringify(metadata) : null,
|
|
358
|
-
created_at: new Date()
|
|
372
|
+
created_at: new Date(),
|
|
359
373
|
})
|
|
360
374
|
.execute();
|
|
361
375
|
}
|
|
@@ -380,10 +394,10 @@ export class KnowledgeDistiller {
|
|
|
380
394
|
.execute();
|
|
381
395
|
return {
|
|
382
396
|
item: this.parseKnowledge(center),
|
|
383
|
-
relations: links.map(l => ({
|
|
397
|
+
relations: links.map((l) => ({
|
|
384
398
|
relationship: l.link_rel,
|
|
385
|
-
target: this.parseKnowledge(l)
|
|
386
|
-
}))
|
|
399
|
+
target: this.parseKnowledge(l),
|
|
400
|
+
})),
|
|
387
401
|
};
|
|
388
402
|
}
|
|
389
403
|
/**
|
|
@@ -436,7 +450,7 @@ export class KnowledgeDistiller {
|
|
|
436
450
|
...secondary.metadata,
|
|
437
451
|
...primary.metadata,
|
|
438
452
|
consolidated_from: secondary.id,
|
|
439
|
-
consolidated_at: new Date().toISOString()
|
|
453
|
+
consolidated_at: new Date().toISOString(),
|
|
440
454
|
};
|
|
441
455
|
const mergedTags = Array.from(new Set([...(primary.tags || []), ...(secondary.tags || [])]));
|
|
442
456
|
await this.db.transaction().execute(async (trx) => {
|
|
@@ -447,7 +461,7 @@ export class KnowledgeDistiller {
|
|
|
447
461
|
confidence: Math.max(primary.confidence, secondary.confidence),
|
|
448
462
|
metadata: JSON.stringify(mergedMeta),
|
|
449
463
|
tags: JSON.stringify(mergedTags),
|
|
450
|
-
updated_at: new Date()
|
|
464
|
+
updated_at: new Date(),
|
|
451
465
|
})
|
|
452
466
|
.where('id', '=', primary.id)
|
|
453
467
|
.execute();
|
|
@@ -461,7 +475,7 @@ export class KnowledgeDistiller {
|
|
|
461
475
|
bloomHash(str) {
|
|
462
476
|
let hash = 0;
|
|
463
477
|
for (let i = 0; i < str.length; i++) {
|
|
464
|
-
hash = (
|
|
478
|
+
hash = (hash << 5) - hash + str.charCodeAt(i);
|
|
465
479
|
hash |= 0; // Format to 32bit int
|
|
466
480
|
}
|
|
467
481
|
return hash;
|
|
@@ -474,10 +488,12 @@ export class KnowledgeDistiller {
|
|
|
474
488
|
confidence: item.confidence,
|
|
475
489
|
status: item.status || 'proposed',
|
|
476
490
|
sourceSessionId: item.source_session_id,
|
|
477
|
-
tags: typeof item.tags === 'string' ? JSON.parse(item.tags) :
|
|
478
|
-
metadata: typeof item.metadata === 'string'
|
|
491
|
+
tags: typeof item.tags === 'string' ? JSON.parse(item.tags) : item.tags || [],
|
|
492
|
+
metadata: typeof item.metadata === 'string'
|
|
493
|
+
? JSON.parse(item.metadata)
|
|
494
|
+
: item.metadata || {},
|
|
479
495
|
createdAt: new Date(item.created_at),
|
|
480
|
-
updatedAt: new Date(item.updated_at)
|
|
496
|
+
updatedAt: new Date(item.updated_at),
|
|
481
497
|
};
|
|
482
498
|
}
|
|
483
499
|
}
|
|
@@ -14,9 +14,23 @@ export class RecursiveReasoner {
|
|
|
14
14
|
['fast', 'slow'],
|
|
15
15
|
['short', 'long'],
|
|
16
16
|
['start', 'stop'],
|
|
17
|
-
['enable', 'disable']
|
|
17
|
+
['enable', 'disable'],
|
|
18
18
|
];
|
|
19
|
-
stopWords = new Set([
|
|
19
|
+
stopWords = new Set([
|
|
20
|
+
'the',
|
|
21
|
+
'a',
|
|
22
|
+
'an',
|
|
23
|
+
'and',
|
|
24
|
+
'or',
|
|
25
|
+
'but',
|
|
26
|
+
'in',
|
|
27
|
+
'on',
|
|
28
|
+
'at',
|
|
29
|
+
'to',
|
|
30
|
+
'for',
|
|
31
|
+
'with',
|
|
32
|
+
'from',
|
|
33
|
+
]);
|
|
20
34
|
constructor(db, config = {}) {
|
|
21
35
|
this.db = db;
|
|
22
36
|
this.config = config;
|
|
@@ -29,12 +43,12 @@ export class RecursiveReasoner {
|
|
|
29
43
|
* Find goals matching a pattern across all sessions
|
|
30
44
|
*/
|
|
31
45
|
async analyzeGlobalProgress(pattern) {
|
|
32
|
-
const goals = await this.typedDb
|
|
46
|
+
const goals = (await this.typedDb
|
|
33
47
|
.selectFrom(this.goalsTable)
|
|
34
48
|
.selectAll()
|
|
35
49
|
.where('description', 'like', `%${pattern}%`)
|
|
36
50
|
.orderBy('created_at', 'desc')
|
|
37
|
-
.execute();
|
|
51
|
+
.execute());
|
|
38
52
|
return goals.map(this.parseGoal);
|
|
39
53
|
}
|
|
40
54
|
/**
|
|
@@ -44,12 +58,14 @@ export class RecursiveReasoner {
|
|
|
44
58
|
async synthesizeLessons() {
|
|
45
59
|
console.log('[RecursiveReasoner] Performing high-throughput weighted token clustering...');
|
|
46
60
|
const reflectionsTable = this.config.reflectionsTable || 'agent_reflections';
|
|
47
|
-
const results = await this.typedDb
|
|
61
|
+
const results = (await this.typedDb
|
|
48
62
|
.selectFrom(reflectionsTable)
|
|
49
63
|
.select('lessons_learned')
|
|
50
64
|
.where('lessons_learned', 'is not', null)
|
|
51
|
-
.execute();
|
|
52
|
-
const rawLessons = results
|
|
65
|
+
.execute());
|
|
66
|
+
const rawLessons = results
|
|
67
|
+
.map((l) => l.lessons_learned)
|
|
68
|
+
.filter(Boolean);
|
|
53
69
|
const clusters = {};
|
|
54
70
|
// Global Token Frequency Pass
|
|
55
71
|
const globalTokenFreq = new Map();
|
|
@@ -112,9 +128,12 @@ export class RecursiveReasoner {
|
|
|
112
128
|
description: `Systemic Best-Practice: ${reasoning}`,
|
|
113
129
|
status: 'pending',
|
|
114
130
|
priority: 5,
|
|
115
|
-
metadata: JSON.stringify({
|
|
131
|
+
metadata: JSON.stringify({
|
|
132
|
+
source_persona: persona.id,
|
|
133
|
+
cross_pollinated: true,
|
|
134
|
+
}),
|
|
116
135
|
created_at: new Date(),
|
|
117
|
-
updated_at: new Date()
|
|
136
|
+
updated_at: new Date(),
|
|
118
137
|
})
|
|
119
138
|
.execute();
|
|
120
139
|
goalsCreated++;
|
|
@@ -127,11 +146,11 @@ export class RecursiveReasoner {
|
|
|
127
146
|
*/
|
|
128
147
|
async detectContradictions() {
|
|
129
148
|
console.log('[RecursiveReasoner] Detecting logical contradictions in systemic goals...');
|
|
130
|
-
const activeGoals = await this.typedDb
|
|
149
|
+
const activeGoals = (await this.typedDb
|
|
131
150
|
.selectFrom(this.goalsTable)
|
|
132
151
|
.selectAll()
|
|
133
152
|
.where('status', '=', 'active')
|
|
134
|
-
.execute();
|
|
153
|
+
.execute());
|
|
135
154
|
const contradictions = [];
|
|
136
155
|
for (let i = 0; i < activeGoals.length; i++) {
|
|
137
156
|
for (let j = i + 1; j < activeGoals.length; j++) {
|
|
@@ -156,7 +175,8 @@ export class RecursiveReasoner {
|
|
|
156
175
|
const t2 = text2.toLowerCase();
|
|
157
176
|
// Check explicit opposites
|
|
158
177
|
for (const [op1, op2] of this.conflictPairs) {
|
|
159
|
-
if ((t1.includes(op1) && t2.includes(op2)) ||
|
|
178
|
+
if ((t1.includes(op1) && t2.includes(op2)) ||
|
|
179
|
+
(t1.includes(op2) && t2.includes(op1))) {
|
|
160
180
|
// Determine the subject of conflict (common words)
|
|
161
181
|
const intersection = this.intersect(this.tokenize(t1), this.tokenize(t2));
|
|
162
182
|
// If they share a subject (e.g. "latency"), it's a conflict
|
|
@@ -170,13 +190,14 @@ export class RecursiveReasoner {
|
|
|
170
190
|
return null;
|
|
171
191
|
}
|
|
172
192
|
tokenize(text) {
|
|
173
|
-
return text
|
|
193
|
+
return text
|
|
194
|
+
.toLowerCase()
|
|
174
195
|
.split(/[\W_]+/)
|
|
175
|
-
.filter(w => w.length > 2 && !this.stopWords.has(w));
|
|
196
|
+
.filter((w) => w.length > 2 && !this.stopWords.has(w));
|
|
176
197
|
}
|
|
177
198
|
intersect(arr1, arr2) {
|
|
178
199
|
const s2 = new Set(arr2);
|
|
179
|
-
return arr1.filter(x => s2.has(x));
|
|
200
|
+
return arr1.filter((x) => s2.has(x));
|
|
180
201
|
}
|
|
181
202
|
parseGoal(g) {
|
|
182
203
|
return {
|
|
@@ -186,9 +207,11 @@ export class RecursiveReasoner {
|
|
|
186
207
|
description: g.description,
|
|
187
208
|
status: g.status,
|
|
188
209
|
priority: g.priority,
|
|
189
|
-
metadata: typeof g.metadata === 'string'
|
|
210
|
+
metadata: typeof g.metadata === 'string'
|
|
211
|
+
? JSON.parse(g.metadata)
|
|
212
|
+
: g.metadata || {},
|
|
190
213
|
createdAt: new Date(g.created_at),
|
|
191
|
-
updatedAt: new Date(g.updated_at)
|
|
214
|
+
updatedAt: new Date(g.updated_at),
|
|
192
215
|
};
|
|
193
216
|
}
|
|
194
217
|
}
|
|
@@ -16,31 +16,33 @@ export class ReflectionEngine {
|
|
|
16
16
|
* Record a reflection for a session
|
|
17
17
|
*/
|
|
18
18
|
async reflect(sessionId, outcome, lessonsLearned, suggestedActions, metadata) {
|
|
19
|
-
const reflection = await this.db
|
|
19
|
+
const reflection = (await this.db
|
|
20
20
|
.insertInto(this.reflectionsTable)
|
|
21
21
|
.values({
|
|
22
22
|
session_id: sessionId,
|
|
23
23
|
outcome,
|
|
24
24
|
lessons_learned: lessonsLearned,
|
|
25
|
-
suggested_actions: suggestedActions
|
|
25
|
+
suggested_actions: suggestedActions
|
|
26
|
+
? JSON.stringify(suggestedActions)
|
|
27
|
+
: null,
|
|
26
28
|
metadata: metadata ? JSON.stringify(metadata) : null,
|
|
27
|
-
created_at: new Date()
|
|
29
|
+
created_at: new Date(),
|
|
28
30
|
})
|
|
29
31
|
.returningAll()
|
|
30
|
-
.executeTakeFirstOrThrow();
|
|
32
|
+
.executeTakeFirstOrThrow());
|
|
31
33
|
return this.parseReflection(reflection);
|
|
32
34
|
}
|
|
33
35
|
/**
|
|
34
36
|
* Get reflections for a specific session
|
|
35
37
|
*/
|
|
36
38
|
async getSessionReflections(sessionId) {
|
|
37
|
-
const reflections = await this.db
|
|
39
|
+
const reflections = (await this.db
|
|
38
40
|
.selectFrom(this.reflectionsTable)
|
|
39
41
|
.selectAll()
|
|
40
42
|
.where('session_id', '=', sessionId)
|
|
41
43
|
.orderBy('created_at', 'desc')
|
|
42
|
-
.execute();
|
|
43
|
-
return reflections.map(r => this.parseReflection(r));
|
|
44
|
+
.execute());
|
|
45
|
+
return reflections.map((r) => this.parseReflection(r));
|
|
44
46
|
}
|
|
45
47
|
/**
|
|
46
48
|
* Get recent lessons learned across all sessions
|
|
@@ -65,7 +67,7 @@ export class ReflectionEngine {
|
|
|
65
67
|
metadata: typeof reflection.metadata === 'string'
|
|
66
68
|
? JSON.parse(reflection.metadata)
|
|
67
69
|
: reflection.metadata,
|
|
68
|
-
createdAt: new Date(reflection.created_at)
|
|
70
|
+
createdAt: new Date(reflection.created_at),
|
|
69
71
|
};
|
|
70
72
|
}
|
|
71
73
|
}
|
|
@@ -19,7 +19,7 @@ export class RitualOrchestrator {
|
|
|
19
19
|
*/
|
|
20
20
|
async scheduleRitual(name, type, frequency, definition, metadata) {
|
|
21
21
|
const nextRun = this.calculateNextRun(frequency);
|
|
22
|
-
const ritual = await this.db
|
|
22
|
+
const ritual = (await this.db
|
|
23
23
|
.insertInto(this.ritualsTable)
|
|
24
24
|
.values({
|
|
25
25
|
name,
|
|
@@ -28,10 +28,10 @@ export class RitualOrchestrator {
|
|
|
28
28
|
definition,
|
|
29
29
|
next_run: nextRun,
|
|
30
30
|
status: 'pending',
|
|
31
|
-
metadata: metadata ? JSON.stringify(metadata) : null
|
|
31
|
+
metadata: metadata ? JSON.stringify(metadata) : null,
|
|
32
32
|
})
|
|
33
33
|
.returningAll()
|
|
34
|
-
.executeTakeFirstOrThrow();
|
|
34
|
+
.executeTakeFirstOrThrow());
|
|
35
35
|
return this.parseRitual(ritual);
|
|
36
36
|
}
|
|
37
37
|
/**
|
|
@@ -40,41 +40,47 @@ export class RitualOrchestrator {
|
|
|
40
40
|
async runPendingRituals() {
|
|
41
41
|
const now = new Date();
|
|
42
42
|
const lockTimeout = new Date(now.getTime() + 600000); // 10 min lock by default
|
|
43
|
-
|
|
44
|
-
const
|
|
43
|
+
const pending = await this.db.transaction().execute(async (trx) => {
|
|
44
|
+
const due = (await trx
|
|
45
45
|
.selectFrom(this.ritualsTable)
|
|
46
46
|
.selectAll()
|
|
47
47
|
.where('next_run', '<=', now)
|
|
48
48
|
.where('status', 'in', ['pending', 'success', 'failure'])
|
|
49
49
|
.where((eb) => eb.or([
|
|
50
50
|
eb('locked_until', '<=', now),
|
|
51
|
-
eb('locked_until', 'is', null)
|
|
51
|
+
eb('locked_until', 'is', null),
|
|
52
52
|
]))
|
|
53
|
-
.execute();
|
|
54
|
-
if (
|
|
55
|
-
return
|
|
56
|
-
|
|
57
|
-
for (const ritual of pending) {
|
|
53
|
+
.execute());
|
|
54
|
+
if (due.length === 0)
|
|
55
|
+
return [];
|
|
56
|
+
for (const ritual of due) {
|
|
58
57
|
// Production Hardening: Distributed Lock
|
|
59
58
|
await trx
|
|
60
59
|
.updateTable(this.ritualsTable)
|
|
61
60
|
.set({ locked_until: lockTimeout })
|
|
62
61
|
.where('id', '=', ritual.id)
|
|
63
62
|
.execute();
|
|
64
|
-
// Execute out-of-transaction to avoid long-held locks if sub-tasks are slow
|
|
65
|
-
// but we await it here for the summary count.
|
|
66
|
-
// In a highly parallel system, this might be sent to a worker queue.
|
|
67
|
-
await this.executeRitual(ritual);
|
|
68
63
|
}
|
|
69
|
-
return
|
|
64
|
+
return due;
|
|
70
65
|
});
|
|
66
|
+
if (pending.length === 0)
|
|
67
|
+
return 0;
|
|
68
|
+
console.log(`[RitualOrchestrator] Found ${pending.length} pending rituals due. Locking for execution...`);
|
|
69
|
+
for (const ritual of pending) {
|
|
70
|
+
// Execute out-of-transaction to avoid long-held locks if sub-tasks are slow
|
|
71
|
+
await this.executeRitual(ritual);
|
|
72
|
+
}
|
|
73
|
+
return pending.length;
|
|
71
74
|
}
|
|
72
75
|
/**
|
|
73
76
|
* Execute a specific ritual
|
|
74
77
|
*/
|
|
75
78
|
async executeRitual(ritual) {
|
|
76
79
|
console.log(`[RitualOrchestrator] Executing ritual: ${ritual.name} (${ritual.type})`);
|
|
77
|
-
const ritualMetadata = {
|
|
80
|
+
const ritualMetadata = {
|
|
81
|
+
...ritual.metadata,
|
|
82
|
+
startedAt: new Date(),
|
|
83
|
+
};
|
|
78
84
|
let success = false;
|
|
79
85
|
try {
|
|
80
86
|
switch (ritual.type) {
|
|
@@ -85,15 +91,15 @@ export class RitualOrchestrator {
|
|
|
85
91
|
.select('id')
|
|
86
92
|
.where('status', '=', 'active')
|
|
87
93
|
.execute();
|
|
88
|
-
const compressionThreshold =
|
|
94
|
+
const compressionThreshold = this.config.contextWindowSize || 20;
|
|
89
95
|
let compressedCount = 0;
|
|
90
96
|
for (const session of activeSessions) {
|
|
91
97
|
const messagesTable = this.config.messagesTable || 'agent_messages';
|
|
92
|
-
const countResult = await this.db
|
|
98
|
+
const countResult = (await this.db
|
|
93
99
|
.selectFrom(messagesTable)
|
|
94
100
|
.select((eb) => eb.fn.countAll().as('count'))
|
|
95
101
|
.where('session_id', '=', session.id)
|
|
96
|
-
.executeTakeFirst();
|
|
102
|
+
.executeTakeFirst());
|
|
97
103
|
const count = Number(countResult?.count || 0);
|
|
98
104
|
if (count > compressionThreshold) {
|
|
99
105
|
await this.cortex.compressor.semanticPruning(session.id);
|
|
@@ -140,7 +146,7 @@ export class RitualOrchestrator {
|
|
|
140
146
|
last_run: new Date(),
|
|
141
147
|
next_run: nextRun,
|
|
142
148
|
locked_until: null, // Unlock
|
|
143
|
-
metadata: JSON.stringify(ritualMetadata)
|
|
149
|
+
metadata: JSON.stringify(ritualMetadata),
|
|
144
150
|
})
|
|
145
151
|
.where('id', '=', ritual.id)
|
|
146
152
|
.execute();
|
|
@@ -174,7 +180,7 @@ export class RitualOrchestrator {
|
|
|
174
180
|
lastRun: r.last_run ? new Date(r.last_run) : undefined,
|
|
175
181
|
nextRun: r.next_run ? new Date(r.next_run) : undefined,
|
|
176
182
|
lockedUntil: r.locked_until ? new Date(r.locked_until) : undefined,
|
|
177
|
-
metadata: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata
|
|
183
|
+
metadata: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata,
|
|
178
184
|
};
|
|
179
185
|
}
|
|
180
186
|
}
|