@unrdf/knowledge-engine 5.0.1 → 26.4.3
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/package.json +13 -7
- package/src/ai-enhanced-search.mjs +371 -0
- package/src/anomaly-detector.mjs +226 -0
- package/src/artifact-generator.mjs +251 -0
- package/src/browser.mjs +1 -1
- package/src/chatman/disruption-arithmetic.mjs +140 -0
- package/src/chatman/market-dynamics.mjs +140 -0
- package/src/chatman/organizational-dynamics.mjs +140 -0
- package/src/chatman/strategic-dynamics.mjs +140 -0
- package/src/chatman-config-loader.mjs +282 -0
- package/src/chatman-engine.mjs +431 -0
- package/src/chatman-operator.mjs +342 -0
- package/src/dark-field-detector.mjs +312 -0
- package/src/formation-theorems.mjs +345 -0
- package/src/index.mjs +20 -2
- package/src/knowledge-hook-manager.mjs +1 -1
- package/src/lockchain-writer-browser.mjs +2 -2
- package/src/observability.mjs +40 -4
- package/src/query-optimizer.mjs +1 -1
- package/src/resolution-layer.mjs +1 -1
- package/src/transaction.mjs +11 -9
- package/README.md +0 -84
- package/src/browser-shims.mjs +0 -343
- package/src/canonicalize.mjs +0 -414
- package/src/condition-cache.mjs +0 -109
- package/src/condition-evaluator.mjs +0 -722
- package/src/dark-matter-core.mjs +0 -742
- package/src/define-hook.mjs +0 -213
- package/src/effect-sandbox-browser.mjs +0 -283
- package/src/effect-sandbox-worker.mjs +0 -170
- package/src/effect-sandbox.mjs +0 -517
- package/src/engines/index.mjs +0 -11
- package/src/engines/rdf-engine.mjs +0 -299
- package/src/file-resolver.mjs +0 -387
- package/src/hook-executor-batching.mjs +0 -277
- package/src/hook-executor.mjs +0 -870
- package/src/hook-management.mjs +0 -150
- package/src/ken-parliment.mjs +0 -119
- package/src/ken.mjs +0 -149
- package/src/knowledge-engine/builtin-rules.mjs +0 -190
- package/src/knowledge-engine/inference-engine.mjs +0 -418
- package/src/knowledge-engine/knowledge-engine.mjs +0 -317
- package/src/knowledge-engine/pattern-dsl.mjs +0 -142
- package/src/knowledge-engine/pattern-matcher.mjs +0 -215
- package/src/knowledge-engine/rules.mjs +0 -184
- package/src/knowledge-engine.mjs +0 -319
- package/src/knowledge-hook-engine.mjs +0 -360
- package/src/knowledge-substrate-core.mjs +0 -927
- package/src/lite.mjs +0 -222
- package/src/lockchain-writer.mjs +0 -602
- package/src/monitoring/andon-signals.mjs +0 -775
- package/src/parse.mjs +0 -290
- package/src/performance-optimizer.mjs +0 -678
- package/src/policy-pack.mjs +0 -572
- package/src/query-cache.mjs +0 -116
- package/src/query.mjs +0 -306
- package/src/reason.mjs +0 -350
- package/src/schemas.mjs +0 -1063
- package/src/security/error-sanitizer.mjs +0 -257
- package/src/security/path-validator.mjs +0 -194
- package/src/security/sandbox-restrictions.mjs +0 -331
- package/src/security-validator.mjs +0 -389
- package/src/store-cache.mjs +0 -137
- package/src/telemetry.mjs +0 -167
- package/src/utils/adaptive-monitor.mjs +0 -746
- package/src/utils/circuit-breaker.mjs +0 -513
- package/src/utils/edge-case-handler.mjs +0 -503
- package/src/utils/memory-manager.mjs +0 -498
- package/src/utils/ring-buffer.mjs +0 -282
- package/src/validate.mjs +0 -319
- package/src/validators/index.mjs +0 -338
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Formation Theorems - Blue Ocean Calculus
|
|
3
|
+
* @module knowledge-engine/formation-theorems
|
|
4
|
+
*
|
|
5
|
+
* @description
|
|
6
|
+
* Implements the formation theorems from blue ocean calculus, deriving
|
|
7
|
+
* strategic formations from dark field patterns in the Chatman Equation.
|
|
8
|
+
*
|
|
9
|
+
* Key Theorems:
|
|
10
|
+
* 1. Formation Emergence: Uncontested spaces emerge from dark field
|
|
11
|
+
* 2. Value Innovation: New value curves from pattern recombination
|
|
12
|
+
* 3. Strategic Canvas: Competitive factors mapped to dark field dimensions
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { randomUUID } from 'crypto';
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Formation schema
|
|
20
|
+
*/
|
|
21
|
+
export const FormationSchema = z.object({
|
|
22
|
+
id: z.string().uuid(),
|
|
23
|
+
theorem: z.enum(['emergence', 'value_innovation', 'strategic_canvas', 'four_actions']),
|
|
24
|
+
type: z.enum(['market', 'organizational', 'strategic', 'disruption']),
|
|
25
|
+
input: z.object({
|
|
26
|
+
darkFieldPatterns: z.array(z.string()),
|
|
27
|
+
observablePatterns: z.array(z.string()),
|
|
28
|
+
}),
|
|
29
|
+
output: z.object({
|
|
30
|
+
formation: z.array(z.string()),
|
|
31
|
+
valueProposition: z.string(),
|
|
32
|
+
strategicMoves: z.array(z.string()),
|
|
33
|
+
}),
|
|
34
|
+
confidence: z.number().min(0).max(1),
|
|
35
|
+
derivedAt: z.number(),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Formation options schema
|
|
40
|
+
*/
|
|
41
|
+
export const FormationOptionsSchema = z.object({
|
|
42
|
+
theorem: z
|
|
43
|
+
.enum(['emergence', 'value_innovation', 'strategic_canvas', 'four_actions'])
|
|
44
|
+
.default('emergence'),
|
|
45
|
+
minConfidence: z.number().min(0).max(1).default(0.7),
|
|
46
|
+
maxFormations: z.number().int().positive().default(10),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Formation theorems calculator
|
|
51
|
+
*/
|
|
52
|
+
export class FormationTheorems {
|
|
53
|
+
/**
|
|
54
|
+
* Create a new formation theorems calculator
|
|
55
|
+
* @param {Object} [options] - Calculator options
|
|
56
|
+
* @param {Function} [options.tracer] - OTEL tracer function
|
|
57
|
+
*/
|
|
58
|
+
constructor(options = {}) {
|
|
59
|
+
this.tracer = options.tracer;
|
|
60
|
+
this.metrics = {
|
|
61
|
+
theoremsApplied: 0,
|
|
62
|
+
formationsGenerated: 0,
|
|
63
|
+
averageConfidence: 0,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Apply formation theorem to derive strategic formations
|
|
69
|
+
* @param {Object} artifact - Artifact with observable and dark field
|
|
70
|
+
* @param {Object} [options] - Formation options
|
|
71
|
+
* @returns {Promise<Object>} Formation result
|
|
72
|
+
*/
|
|
73
|
+
async derive(artifact, options = {}) {
|
|
74
|
+
const span = this.tracer?.startSpan?.('chatman.formation.derive');
|
|
75
|
+
const startTime = Date.now();
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
const opts = FormationOptionsSchema.parse(options);
|
|
79
|
+
|
|
80
|
+
span?.setAttribute?.('artifact.type', artifact.type);
|
|
81
|
+
span?.setAttribute?.('theorem', opts.theorem);
|
|
82
|
+
span?.setAttribute?.('dark_field_size', artifact.darkField.patterns.length);
|
|
83
|
+
|
|
84
|
+
const theoremFn = this._getTheoremFunction(opts.theorem);
|
|
85
|
+
const formation = theoremFn(artifact, opts);
|
|
86
|
+
|
|
87
|
+
// Update metrics
|
|
88
|
+
this.metrics.theoremsApplied++;
|
|
89
|
+
this.metrics.formationsGenerated += formation.output.formation.length;
|
|
90
|
+
this.metrics.averageConfidence =
|
|
91
|
+
(this.metrics.averageConfidence * (this.metrics.theoremsApplied - 1) +
|
|
92
|
+
formation.confidence) /
|
|
93
|
+
this.metrics.theoremsApplied;
|
|
94
|
+
|
|
95
|
+
span?.addEvent?.('formation_derived', {
|
|
96
|
+
'formation.id': formation.id,
|
|
97
|
+
'formation.theorem': formation.theorem,
|
|
98
|
+
'formation.confidence': formation.confidence,
|
|
99
|
+
'formation.size': formation.output.formation.length,
|
|
100
|
+
'formation.duration_ms': Date.now() - startTime,
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
return FormationSchema.parse(formation);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
span?.recordException?.(error);
|
|
106
|
+
span?.setStatus?.({ code: 2, message: error.message });
|
|
107
|
+
throw error;
|
|
108
|
+
} finally {
|
|
109
|
+
span?.end?.();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Get theorem function by name
|
|
115
|
+
* @param {string} theorem - Theorem name
|
|
116
|
+
* @returns {Function} Theorem function
|
|
117
|
+
* @private
|
|
118
|
+
*/
|
|
119
|
+
_getTheoremFunction(theorem) {
|
|
120
|
+
const theorems = {
|
|
121
|
+
emergence: this._applyEmergenceTheorem.bind(this),
|
|
122
|
+
value_innovation: this._applyValueInnovationTheorem.bind(this),
|
|
123
|
+
strategic_canvas: this._applyStrategicCanvasTheorem.bind(this),
|
|
124
|
+
four_actions: this._applyFourActionsTheorem.bind(this),
|
|
125
|
+
};
|
|
126
|
+
return theorems[theorem];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Apply emergence theorem - uncontested spaces from dark field
|
|
131
|
+
* @param {Object} artifact - Artifact
|
|
132
|
+
* @param {Object} options - Options
|
|
133
|
+
* @returns {Object} Formation
|
|
134
|
+
* @private
|
|
135
|
+
*/
|
|
136
|
+
_applyEmergenceTheorem(artifact, options) {
|
|
137
|
+
const formation = [];
|
|
138
|
+
const strategicMoves = [];
|
|
139
|
+
|
|
140
|
+
// Identify uncontested spaces in dark field
|
|
141
|
+
const uncontestedPatterns = artifact.darkField.patterns
|
|
142
|
+
.filter((p, i) => i < options.maxFormations)
|
|
143
|
+
.filter(p => p.includes('latent') || p.includes('emergent') || p.includes('hidden'));
|
|
144
|
+
|
|
145
|
+
for (const pattern of uncontestedPatterns) {
|
|
146
|
+
formation.push(`blue_ocean_space:${pattern}`);
|
|
147
|
+
strategicMoves.push(`explore:${pattern}`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const valueProposition = `Create uncontested market space in: ${uncontestedPatterns
|
|
151
|
+
.map(p => p.split(':')[0])
|
|
152
|
+
.join(', ')}`;
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
id: randomUUID(),
|
|
156
|
+
theorem: 'emergence',
|
|
157
|
+
type: artifact.type,
|
|
158
|
+
input: {
|
|
159
|
+
darkFieldPatterns: artifact.darkField.patterns,
|
|
160
|
+
observablePatterns: artifact.observable.patterns,
|
|
161
|
+
},
|
|
162
|
+
output: {
|
|
163
|
+
formation,
|
|
164
|
+
valueProposition,
|
|
165
|
+
strategicMoves,
|
|
166
|
+
},
|
|
167
|
+
confidence: 0.85,
|
|
168
|
+
derivedAt: Date.now(),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Apply value innovation theorem - new value curves from recombination
|
|
174
|
+
* @param {Object} artifact - Artifact
|
|
175
|
+
* @param {Object} options - Options
|
|
176
|
+
* @returns {Object} Formation
|
|
177
|
+
* @private
|
|
178
|
+
*/
|
|
179
|
+
_applyValueInnovationTheorem(artifact, options) {
|
|
180
|
+
const formation = [];
|
|
181
|
+
const strategicMoves = [];
|
|
182
|
+
|
|
183
|
+
// Recombine dark field and observable to create value innovations
|
|
184
|
+
const innovations = artifact.darkField.patterns
|
|
185
|
+
.slice(0, Math.min(5, options.maxFormations))
|
|
186
|
+
.map((darkPattern, i) => {
|
|
187
|
+
const observablePattern =
|
|
188
|
+
artifact.observable.patterns[i % artifact.observable.patterns.length];
|
|
189
|
+
return `${darkPattern}+${observablePattern}`;
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
for (const innovation of innovations) {
|
|
193
|
+
formation.push(`value_innovation:${innovation}`);
|
|
194
|
+
strategicMoves.push(`innovate:${innovation}`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const valueProposition = `Simultaneous differentiation and low cost through: ${innovations.length} value innovations`;
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
id: randomUUID(),
|
|
201
|
+
theorem: 'value_innovation',
|
|
202
|
+
type: artifact.type,
|
|
203
|
+
input: {
|
|
204
|
+
darkFieldPatterns: artifact.darkField.patterns,
|
|
205
|
+
observablePatterns: artifact.observable.patterns,
|
|
206
|
+
},
|
|
207
|
+
output: {
|
|
208
|
+
formation,
|
|
209
|
+
valueProposition,
|
|
210
|
+
strategicMoves,
|
|
211
|
+
},
|
|
212
|
+
confidence: 0.8,
|
|
213
|
+
derivedAt: Date.now(),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Apply strategic canvas theorem - map competitive factors
|
|
219
|
+
* @param {Object} artifact - Artifact
|
|
220
|
+
* @param {Object} options - Options
|
|
221
|
+
* @returns {Object} Formation
|
|
222
|
+
* @private
|
|
223
|
+
*/
|
|
224
|
+
_applyStrategicCanvasTheorem(artifact, options) {
|
|
225
|
+
const formation = [];
|
|
226
|
+
const strategicMoves = [];
|
|
227
|
+
|
|
228
|
+
// Map observable (current factors) vs dark field (new factors)
|
|
229
|
+
const currentFactors = artifact.observable.patterns.slice(0, 5);
|
|
230
|
+
const newFactors = artifact.darkField.patterns
|
|
231
|
+
.filter(p => p.includes('hidden') || p.includes('latent'))
|
|
232
|
+
.slice(0, 5);
|
|
233
|
+
|
|
234
|
+
// Eliminate-Reduce-Raise-Create framework
|
|
235
|
+
strategicMoves.push(`eliminate:${currentFactors[0]}`);
|
|
236
|
+
strategicMoves.push(`reduce:${currentFactors[1]}`);
|
|
237
|
+
strategicMoves.push(`raise:${newFactors[0]}`);
|
|
238
|
+
strategicMoves.push(`create:${newFactors[1]}`);
|
|
239
|
+
|
|
240
|
+
formation.push(`strategic_canvas:eliminate-reduce-raise-create`);
|
|
241
|
+
formation.push(...newFactors.map(f => `new_factor:${f}`));
|
|
242
|
+
|
|
243
|
+
const valueProposition = `Reconstruct market boundaries with ${newFactors.length} new competitive factors`;
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
id: randomUUID(),
|
|
247
|
+
theorem: 'strategic_canvas',
|
|
248
|
+
type: artifact.type,
|
|
249
|
+
input: {
|
|
250
|
+
darkFieldPatterns: artifact.darkField.patterns,
|
|
251
|
+
observablePatterns: artifact.observable.patterns,
|
|
252
|
+
},
|
|
253
|
+
output: {
|
|
254
|
+
formation,
|
|
255
|
+
valueProposition,
|
|
256
|
+
strategicMoves,
|
|
257
|
+
},
|
|
258
|
+
confidence: 0.78,
|
|
259
|
+
derivedAt: Date.now(),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Apply four actions theorem - ERRC framework
|
|
265
|
+
* @param {Object} artifact - Artifact
|
|
266
|
+
* @param {Object} options - Options
|
|
267
|
+
* @returns {Object} Formation
|
|
268
|
+
* @private
|
|
269
|
+
*/
|
|
270
|
+
_applyFourActionsTheorem(artifact, options) {
|
|
271
|
+
const formation = [];
|
|
272
|
+
const strategicMoves = [];
|
|
273
|
+
|
|
274
|
+
const observable = artifact.observable.patterns;
|
|
275
|
+
const darkField = artifact.darkField.patterns;
|
|
276
|
+
|
|
277
|
+
// Eliminate: factors to remove
|
|
278
|
+
const eliminate = observable.slice(0, 2).map(p => `eliminate:${p}`);
|
|
279
|
+
|
|
280
|
+
// Reduce: factors to reduce below industry standard
|
|
281
|
+
const reduce = observable.slice(2, 4).map(p => `reduce:${p}`);
|
|
282
|
+
|
|
283
|
+
// Raise: factors to raise above industry standard
|
|
284
|
+
const raise = darkField
|
|
285
|
+
.filter(p => p.includes('emergent'))
|
|
286
|
+
.slice(0, 2)
|
|
287
|
+
.map(p => `raise:${p}`);
|
|
288
|
+
|
|
289
|
+
// Create: factors never offered by industry
|
|
290
|
+
const create = darkField
|
|
291
|
+
.filter(p => p.includes('hidden') || p.includes('latent'))
|
|
292
|
+
.slice(0, 3)
|
|
293
|
+
.map(p => `create:${p}`);
|
|
294
|
+
|
|
295
|
+
formation.push(...eliminate, ...reduce, ...raise, ...create);
|
|
296
|
+
strategicMoves.push(...eliminate, ...reduce, ...raise, ...create);
|
|
297
|
+
|
|
298
|
+
const valueProposition = `Four Actions Framework: Eliminate ${eliminate.length}, Reduce ${reduce.length}, Raise ${raise.length}, Create ${create.length}`;
|
|
299
|
+
|
|
300
|
+
return {
|
|
301
|
+
id: randomUUID(),
|
|
302
|
+
theorem: 'four_actions',
|
|
303
|
+
type: artifact.type,
|
|
304
|
+
input: {
|
|
305
|
+
darkFieldPatterns: artifact.darkField.patterns,
|
|
306
|
+
observablePatterns: artifact.observable.patterns,
|
|
307
|
+
},
|
|
308
|
+
output: {
|
|
309
|
+
formation,
|
|
310
|
+
valueProposition,
|
|
311
|
+
strategicMoves,
|
|
312
|
+
},
|
|
313
|
+
confidence: 0.82,
|
|
314
|
+
derivedAt: Date.now(),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Get calculator metrics
|
|
320
|
+
* @returns {Object} Metrics
|
|
321
|
+
*/
|
|
322
|
+
getMetrics() {
|
|
323
|
+
return { ...this.metrics };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Reset calculator metrics
|
|
328
|
+
*/
|
|
329
|
+
resetMetrics() {
|
|
330
|
+
this.metrics = {
|
|
331
|
+
theoremsApplied: 0,
|
|
332
|
+
formationsGenerated: 0,
|
|
333
|
+
averageConfidence: 0,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Create a formation theorems calculator instance
|
|
340
|
+
* @param {Object} [options] - Calculator options
|
|
341
|
+
* @returns {FormationTheorems} Calculator instance
|
|
342
|
+
*/
|
|
343
|
+
export function createFormationTheorems(options = {}) {
|
|
344
|
+
return new FormationTheorems(options);
|
|
345
|
+
}
|
package/src/index.mjs
CHANGED
|
@@ -35,12 +35,12 @@ export {
|
|
|
35
35
|
} from './knowledge-substrate-core.mjs';
|
|
36
36
|
|
|
37
37
|
// Storage & Persistence
|
|
38
|
-
export { LockchainWriter, createLockchainWriter } from '
|
|
38
|
+
export { LockchainWriter, createLockchainWriter } from '@unrdf/core/utils/lockchain-writer';
|
|
39
39
|
export { ResolutionLayer } from './resolution-layer.mjs';
|
|
40
40
|
|
|
41
41
|
// Query & Optimization
|
|
42
42
|
export { QueryOptimizer } from './query-optimizer.mjs';
|
|
43
|
-
export { query } from './query.mjs';
|
|
43
|
+
export { query, select, ask, construct, describe, update, getQueryStats } from './query.mjs';
|
|
44
44
|
|
|
45
45
|
// Utilities
|
|
46
46
|
export { parseTurtle, toTurtle, toNQuads, parseJsonLd, toJsonLd } from './parse.mjs';
|
|
@@ -89,5 +89,23 @@ export {
|
|
|
89
89
|
defaultObservabilityManager,
|
|
90
90
|
} from './observability.mjs';
|
|
91
91
|
|
|
92
|
+
// Chatman Equation Integration
|
|
93
|
+
export { ChatmanOperator, createChatmanOperator } from './chatman-operator.mjs';
|
|
94
|
+
export { ArtifactGenerator, createArtifactGenerator } from './artifact-generator.mjs';
|
|
95
|
+
export { DarkFieldDetector, createDarkFieldDetector } from './dark-field-detector.mjs';
|
|
96
|
+
export { FormationTheorems, createFormationTheorems } from './formation-theorems.mjs';
|
|
97
|
+
export {
|
|
98
|
+
ChatmanConfigLoader,
|
|
99
|
+
createChatmanConfigLoader,
|
|
100
|
+
loadChatmanConfig,
|
|
101
|
+
} from './chatman-config-loader.mjs';
|
|
102
|
+
export { ChatmanEngine, createChatmanEngine } from './chatman-engine.mjs';
|
|
103
|
+
|
|
104
|
+
// Chatman Dynamics Rules
|
|
105
|
+
export * from './chatman/market-dynamics.mjs';
|
|
106
|
+
export * from './chatman/organizational-dynamics.mjs';
|
|
107
|
+
export * from './chatman/strategic-dynamics.mjs';
|
|
108
|
+
export * from './chatman/disruption-arithmetic.mjs';
|
|
109
|
+
|
|
92
110
|
// Consolidated Schemas (single source of truth)
|
|
93
111
|
export * from './schemas.mjs';
|
|
@@ -12,7 +12,7 @@ import { createHookExecutor } from './hook-executor.mjs';
|
|
|
12
12
|
import { createConditionEvaluator } from './condition-evaluator.mjs';
|
|
13
13
|
import { PolicyPackManager } from './policy-pack.mjs';
|
|
14
14
|
import { createSecurityValidator } from './security-validator.mjs';
|
|
15
|
-
import { validateManagerConfig,
|
|
15
|
+
import { validateManagerConfig, validateTransactionDelta, validateHookEvent } from './schemas.mjs';
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* Knowledge Hook Manager that extends the transaction system with file-based hooks.
|
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
* verification without Git dependencies.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import { randomUUID, createHash,
|
|
11
|
+
import { randomUUID, createHash, fs } from './browser-shims.mjs';
|
|
12
12
|
import { sha3_256 } from '@noble/hashes/sha3.js';
|
|
13
|
-
import {
|
|
13
|
+
import { _BLAKE3 } from '@noble/hashes/blake3.js';
|
|
14
14
|
import { utf8ToBytes, bytesToHex } from '@noble/hashes/utils.js';
|
|
15
15
|
import { z } from 'zod';
|
|
16
16
|
|
package/src/observability.mjs
CHANGED
|
@@ -8,10 +8,9 @@
|
|
|
8
8
|
* error isolation, and performance tracking.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
11
|
+
import { randomUUID } from 'crypto';
|
|
12
|
+
import { z } from 'zod';
|
|
13
13
|
import { ObservabilityConfigSchema, PerformanceMetricsSchema } from './schemas.mjs';
|
|
14
|
-
import { getRuntimeConfig } from '../context/config.mjs';
|
|
15
14
|
|
|
16
15
|
/**
|
|
17
16
|
* OpenTelemetry observability manager
|
|
@@ -38,6 +37,9 @@ export class ObservabilityManager {
|
|
|
38
37
|
this.activeSpans = new Map();
|
|
39
38
|
this.initialized = false;
|
|
40
39
|
this._lastMetrics = null; // for smoothing fallback
|
|
40
|
+
this.samplingRate = config.samplingRate ?? 0.1; // Default 10% sampling
|
|
41
|
+
this.logSamplingRate = config.logSamplingRate ?? 0.01; // Default 1% DEBUG log sampling
|
|
42
|
+
this._debugLogCounter = 0;
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
/**
|
|
@@ -84,12 +86,17 @@ export class ObservabilityManager {
|
|
|
84
86
|
exportTimeoutMillis: this.config.exportTimeoutMillis,
|
|
85
87
|
});
|
|
86
88
|
|
|
87
|
-
//
|
|
89
|
+
// Create sampler for head-based sampling
|
|
90
|
+
const { TraceIdRatioBasedSampler } = await import('@opentelemetry/sdk-trace-base');
|
|
91
|
+
const sampler = new TraceIdRatioBasedSampler(this.samplingRate);
|
|
92
|
+
|
|
93
|
+
// Initialize SDK with sampling
|
|
88
94
|
const sdk = new NodeSDK({
|
|
89
95
|
resource,
|
|
90
96
|
traceExporter: this.config.enableTracing ? traceExporter : undefined,
|
|
91
97
|
metricReader: this.config.enableMetrics ? metricReader : undefined,
|
|
92
98
|
instrumentations: this.config.enableTracing ? [getNodeAutoInstrumentations()] : [],
|
|
99
|
+
sampler: this.config.enableTracing ? sampler : undefined,
|
|
93
100
|
});
|
|
94
101
|
|
|
95
102
|
await sdk.start();
|
|
@@ -499,6 +506,35 @@ export class ObservabilityManager {
|
|
|
499
506
|
return values[Math.max(0, index)];
|
|
500
507
|
}
|
|
501
508
|
|
|
509
|
+
/**
|
|
510
|
+
* Log with sampling (DEBUG logs sampled, WARN/ERROR always logged)
|
|
511
|
+
* @param {string} level - Log level (DEBUG, INFO, WARN, ERROR)
|
|
512
|
+
* @param {string} message - Log message
|
|
513
|
+
* @param {Object} [context] - Additional context
|
|
514
|
+
*/
|
|
515
|
+
log(level, message, context = {}) {
|
|
516
|
+
const upperLevel = level.toUpperCase();
|
|
517
|
+
|
|
518
|
+
// Always log WARN and ERROR
|
|
519
|
+
if (upperLevel === 'WARN' || upperLevel === 'ERROR') {
|
|
520
|
+
console[upperLevel === 'ERROR' ? 'error' : 'warn'](`[${upperLevel}] ${message}`, context);
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// Sample DEBUG logs
|
|
525
|
+
if (upperLevel === 'DEBUG') {
|
|
526
|
+
this._debugLogCounter++;
|
|
527
|
+
const sampleThreshold = Math.floor(1 / this.logSamplingRate);
|
|
528
|
+
if (this._debugLogCounter % sampleThreshold === 0) {
|
|
529
|
+
console.log(`[DEBUG:SAMPLED] ${message}`, context);
|
|
530
|
+
}
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// INFO and other levels always logged
|
|
535
|
+
console.log(`[${upperLevel}] ${message}`, context);
|
|
536
|
+
}
|
|
537
|
+
|
|
502
538
|
/**
|
|
503
539
|
* Shutdown observability
|
|
504
540
|
* @returns {Promise<void>}
|
package/src/query-optimizer.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import { sha3_256 } from '@noble/hashes/sha3.js';
|
|
|
11
11
|
import { utf8ToBytes, bytesToHex } from '@noble/hashes/utils.js';
|
|
12
12
|
import { randomUUID } from 'crypto';
|
|
13
13
|
import { z } from 'zod';
|
|
14
|
-
import LRUCache from 'lru-cache';
|
|
14
|
+
import { LRUCache } from 'lru-cache';
|
|
15
15
|
import { trace, metrics, SpanStatusCode } from '@opentelemetry/api';
|
|
16
16
|
|
|
17
17
|
/**
|
package/src/resolution-layer.mjs
CHANGED
|
@@ -447,7 +447,7 @@ export class ResolutionLayer {
|
|
|
447
447
|
* @returns {number} Confidence score
|
|
448
448
|
* @private
|
|
449
449
|
*/
|
|
450
|
-
_calculateConfidence(proposals,
|
|
450
|
+
_calculateConfidence(proposals, resolvedDelta) {
|
|
451
451
|
if (proposals.length === 0) return 0;
|
|
452
452
|
|
|
453
453
|
let totalConfidence = 0;
|
package/src/transaction.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { sha3_256 } from '@noble/hashes/sha3.js';
|
|
|
8
8
|
import { blake3 } from '@noble/hashes/blake3.js';
|
|
9
9
|
import { utf8ToBytes, bytesToHex } from '@noble/hashes/utils.js';
|
|
10
10
|
import { canonicalize } from './canonicalize.mjs';
|
|
11
|
-
import { createLockchainWriter } from '
|
|
11
|
+
import { createLockchainWriter } from '@unrdf/core/utils/lockchain-writer';
|
|
12
12
|
import { createResolutionLayer } from './resolution-layer.mjs';
|
|
13
13
|
import { createObservabilityManager } from './observability.mjs';
|
|
14
14
|
import { randomUUID } from 'crypto';
|
|
@@ -19,16 +19,18 @@ const tracer = trace.getTracer('unrdf');
|
|
|
19
19
|
|
|
20
20
|
// Import consolidated schemas
|
|
21
21
|
import {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
_TransactionHookResultSchema,
|
|
26
|
-
_HashSchema,
|
|
27
|
-
_TransactionReceiptSchemaNew,
|
|
28
|
-
TransactionOptionsSchema,
|
|
29
|
-
ManagerOptionsSchema,
|
|
22
|
+
TransactionDeltaSchema as DeltaSchema,
|
|
23
|
+
TransactionReceiptSchema,
|
|
24
|
+
HookResultSchema as TransactionHookResultSchema,
|
|
30
25
|
} from './schemas.mjs';
|
|
31
26
|
|
|
27
|
+
// Define missing schemas locally
|
|
28
|
+
const QuadSchema = z.any();
|
|
29
|
+
const TransactionHookSchema = z.any();
|
|
30
|
+
const HashSchema = z.string();
|
|
31
|
+
const TransactionOptionsSchema = z.any();
|
|
32
|
+
const ManagerOptionsSchema = z.any();
|
|
33
|
+
|
|
32
34
|
// Zod schemas for validation
|
|
33
35
|
// QuadSchema now imported from schemas.mjs
|
|
34
36
|
|
package/README.md
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
# @unrdf/knowledge-engine
|
|
2
|
-
|
|
3
|
-
 
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
**Rule Engine, Inference, and Pattern Matching** *(Optional Extension)*
|
|
7
|
-
|
|
8
|
-
Apply business rules and inference to RDF data. Includes reasoning engine and pattern matching.
|
|
9
|
-
|
|
10
|
-
## Installation
|
|
11
|
-
|
|
12
|
-
```bash
|
|
13
|
-
pnpm add @unrdf/knowledge-engine
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
## 📚 Examples
|
|
17
|
-
|
|
18
|
-
See these examples that demonstrate @unrdf/knowledge-engine:
|
|
19
|
-
|
|
20
|
-
- **[knowledge-engine-example.mjs](../../examples/knowledge-engine-example.mjs)** - Complete AI semantic analysis demo (1 hour)
|
|
21
|
-
- **[ai-semantic-example.mjs](../../examples/ai-semantic-example.mjs)** - Embedding-based semantic search
|
|
22
|
-
- **[comprehensive-feature-test.mjs](../../examples/comprehensive-feature-test.mjs)** - Knowledge engine integration
|
|
23
|
-
|
|
24
|
-
**Want AI-powered queries?** Start with [knowledge-engine-example.mjs](../../examples/knowledge-engine-example.mjs).
|
|
25
|
-
|
|
26
|
-
## Quick Start
|
|
27
|
-
|
|
28
|
-
```javascript
|
|
29
|
-
import { inferPatterns, createRuleSet } from '@unrdf/knowledge-engine'
|
|
30
|
-
|
|
31
|
-
// Define rules
|
|
32
|
-
const rules = createRuleSet([
|
|
33
|
-
{
|
|
34
|
-
name: 'infer-person',
|
|
35
|
-
pattern: '?x rdf:type foaf:Person',
|
|
36
|
-
then: '?x rdfs:label ?name'
|
|
37
|
-
}
|
|
38
|
-
])
|
|
39
|
-
|
|
40
|
-
// Apply inference
|
|
41
|
-
const inferred = await inferPatterns(store, rules)
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
## Features
|
|
45
|
-
|
|
46
|
-
- ✅ Forward chaining inference
|
|
47
|
-
- ✅ Rule definition and execution
|
|
48
|
-
- ✅ Pattern matching on RDF data
|
|
49
|
-
- ✅ Built-in ontology reasoning (RDF, RDFS, OWL)
|
|
50
|
-
- ✅ Custom rule sets
|
|
51
|
-
- ✅ Performance optimization
|
|
52
|
-
|
|
53
|
-
## Use Cases
|
|
54
|
-
|
|
55
|
-
- **Business rules**: Apply domain rules to RDF
|
|
56
|
-
- **Data enrichment**: Infer new facts from existing data
|
|
57
|
-
- **Ontology reasoning**: RDFS and OWL inference
|
|
58
|
-
- **Data quality**: Detect and fix inconsistencies
|
|
59
|
-
- **Knowledge extraction**: Mine patterns from data
|
|
60
|
-
|
|
61
|
-
## Documentation
|
|
62
|
-
|
|
63
|
-
- **[API Reference](./docs/API.md)** - Complete API documentation
|
|
64
|
-
- **[User Guide](./docs/GUIDE.md)** - Rule definition and usage
|
|
65
|
-
- **[Examples](./examples/)** - Code examples
|
|
66
|
-
- **[Contributing](./docs/CONTRIBUTING.md)** - How to contribute
|
|
67
|
-
|
|
68
|
-
## Status
|
|
69
|
-
|
|
70
|
-
**Optional Extension** - Not required for core UNRDF functionality.
|
|
71
|
-
Use only if you need rule-based inference.
|
|
72
|
-
|
|
73
|
-
## Depends On
|
|
74
|
-
|
|
75
|
-
- `@unrdf/core` - RDF substrate
|
|
76
|
-
- `@unrdf/streaming` - Change subscriptions
|
|
77
|
-
|
|
78
|
-
## VOC Usage
|
|
79
|
-
|
|
80
|
-
- VOC-3: ML Agent (pattern matching)
|
|
81
|
-
|
|
82
|
-
## License
|
|
83
|
-
|
|
84
|
-
MIT
|