@unrdf/knowledge-engine 5.0.1 → 26.4.2

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 (71) hide show
  1. package/package.json +23 -17
  2. package/src/ai-enhanced-search.mjs +371 -0
  3. package/src/anomaly-detector.mjs +226 -0
  4. package/src/artifact-generator.mjs +252 -0
  5. package/src/browser.mjs +1 -1
  6. package/src/chatman/disruption-arithmetic.mjs +140 -0
  7. package/src/chatman/market-dynamics.mjs +140 -0
  8. package/src/chatman/organizational-dynamics.mjs +140 -0
  9. package/src/chatman/strategic-dynamics.mjs +140 -0
  10. package/src/chatman-config-loader.mjs +282 -0
  11. package/src/chatman-engine.mjs +435 -0
  12. package/src/chatman-operator.mjs +343 -0
  13. package/src/dark-field-detector.mjs +332 -0
  14. package/src/formation-theorems.mjs +345 -0
  15. package/src/index.mjs +20 -2
  16. package/src/knowledge-hook-manager.mjs +1 -1
  17. package/src/lockchain-writer-browser.mjs +2 -2
  18. package/src/observability.mjs +40 -4
  19. package/src/query-optimizer.mjs +1 -1
  20. package/src/resolution-layer.mjs +1 -1
  21. package/src/transaction.mjs +11 -9
  22. package/README.md +0 -84
  23. package/src/browser-shims.mjs +0 -343
  24. package/src/canonicalize.mjs +0 -414
  25. package/src/condition-cache.mjs +0 -109
  26. package/src/condition-evaluator.mjs +0 -722
  27. package/src/dark-matter-core.mjs +0 -742
  28. package/src/define-hook.mjs +0 -213
  29. package/src/effect-sandbox-browser.mjs +0 -283
  30. package/src/effect-sandbox-worker.mjs +0 -170
  31. package/src/effect-sandbox.mjs +0 -517
  32. package/src/engines/index.mjs +0 -11
  33. package/src/engines/rdf-engine.mjs +0 -299
  34. package/src/file-resolver.mjs +0 -387
  35. package/src/hook-executor-batching.mjs +0 -277
  36. package/src/hook-executor.mjs +0 -870
  37. package/src/hook-management.mjs +0 -150
  38. package/src/ken-parliment.mjs +0 -119
  39. package/src/ken.mjs +0 -149
  40. package/src/knowledge-engine/builtin-rules.mjs +0 -190
  41. package/src/knowledge-engine/inference-engine.mjs +0 -418
  42. package/src/knowledge-engine/knowledge-engine.mjs +0 -317
  43. package/src/knowledge-engine/pattern-dsl.mjs +0 -142
  44. package/src/knowledge-engine/pattern-matcher.mjs +0 -215
  45. package/src/knowledge-engine/rules.mjs +0 -184
  46. package/src/knowledge-engine.mjs +0 -319
  47. package/src/knowledge-hook-engine.mjs +0 -360
  48. package/src/knowledge-substrate-core.mjs +0 -927
  49. package/src/lite.mjs +0 -222
  50. package/src/lockchain-writer.mjs +0 -602
  51. package/src/monitoring/andon-signals.mjs +0 -775
  52. package/src/parse.mjs +0 -290
  53. package/src/performance-optimizer.mjs +0 -678
  54. package/src/policy-pack.mjs +0 -572
  55. package/src/query-cache.mjs +0 -116
  56. package/src/query.mjs +0 -306
  57. package/src/reason.mjs +0 -350
  58. package/src/schemas.mjs +0 -1063
  59. package/src/security/error-sanitizer.mjs +0 -257
  60. package/src/security/path-validator.mjs +0 -194
  61. package/src/security/sandbox-restrictions.mjs +0 -331
  62. package/src/security-validator.mjs +0 -389
  63. package/src/store-cache.mjs +0 -137
  64. package/src/telemetry.mjs +0 -167
  65. package/src/utils/adaptive-monitor.mjs +0 -746
  66. package/src/utils/circuit-breaker.mjs +0 -513
  67. package/src/utils/edge-case-handler.mjs +0 -503
  68. package/src/utils/memory-manager.mjs +0 -498
  69. package/src/utils/ring-buffer.mjs +0 -282
  70. package/src/validate.mjs +0 -319
  71. package/src/validators/index.mjs +0 -338
package/src/schemas.mjs DELETED
@@ -1,1063 +0,0 @@
1
- /**
2
- * @file Zod schemas for knowledge hook validation
3
- * @module schemas
4
- *
5
- * @description
6
- * Comprehensive Zod schemas for validating all knowledge hook components
7
- * including hook definitions, conditions, events, and execution results.
8
- */
9
-
10
- import { z } from 'zod';
11
-
12
- /**
13
- * Schema for hook metadata
14
- */
15
- export const HookMetaSchema = z.object({
16
- name: z
17
- .string()
18
- .min(1)
19
- .max(100)
20
- .regex(
21
- /^[a-zA-Z0-9:_-]+$/,
22
- 'Name must contain only alphanumeric characters, colons, hyphens, and underscores'
23
- ),
24
- description: z.string().min(1).max(500).optional(),
25
- version: z
26
- .string()
27
- .regex(/^\d+\.\d+\.\d+$/, 'Version must be semantic version format')
28
- .optional(),
29
- author: z.string().min(1).max(100).optional(),
30
- tags: z.array(z.string().min(1).max(50)).max(10).optional(),
31
- ontology: z.array(z.string().min(1).max(50)).max(10).optional(),
32
- createdAt: z.coerce.date().optional(),
33
- updatedAt: z.coerce.date().optional(),
34
- });
35
-
36
- /**
37
- * Schema for content-addressed file references
38
- */
39
- export const FileRefSchema = z.object({
40
- uri: z
41
- .string()
42
- .url({ message: 'Must be a valid URI' })
43
- .or(z.string().regex(/^file:\/\/.+/, 'Must be a valid file URI')),
44
- sha256: z
45
- .string()
46
- .length(64)
47
- .regex(/^[a-f0-9]+$/, 'Must be a valid SHA-256 hash')
48
- .optional(),
49
- mediaType: z.string().min(1).max(100).optional(),
50
- size: z.number().int().positive().optional(),
51
- lastModified: z.coerce.date().optional(),
52
- });
53
-
54
- /**
55
- * Schema for SPARQL ASK conditions
56
- * Supports EITHER file reference (ref) OR inline query (query) for convenience
57
- */
58
- export const SparqlAskConditionSchema = z.object({
59
- kind: z.literal('sparql-ask'),
60
- ref: FileRefSchema.optional(),
61
- query: z.string().min(1).optional(),
62
- options: z
63
- .object({
64
- timeout: z.number().int().positive().max(30000).optional(),
65
- strict: z.boolean().optional(),
66
- variables: z.record(z.string()).optional(),
67
- })
68
- .optional(),
69
- });
70
-
71
- /**
72
- * Schema for SPARQL SELECT conditions
73
- * Supports EITHER file reference (ref) OR inline query (query) for convenience
74
- */
75
- export const SparqlSelectConditionSchema = z.object({
76
- kind: z.literal('sparql-select'),
77
- ref: FileRefSchema.optional(),
78
- query: z.string().min(1).optional(),
79
- options: z
80
- .object({
81
- timeout: z.number().int().positive().max(30000).optional(),
82
- limit: z.number().int().positive().max(10000).optional(),
83
- offset: z.number().int().nonnegative().optional(),
84
- strict: z.boolean().optional(),
85
- variables: z.record(z.string()).optional(),
86
- })
87
- .optional(),
88
- });
89
-
90
- /**
91
- * Schema for SHACL validation conditions
92
- * Supports EITHER file reference (ref) OR inline shapes (shapes) for convenience
93
- */
94
- export const ShaclConditionSchema = z.object({
95
- kind: z.literal('shacl'),
96
- ref: FileRefSchema.optional(),
97
- shapes: z.string().min(1).optional(), // Inline Turtle shapes for convenience
98
- options: z
99
- .object({
100
- strict: z.boolean().optional(),
101
- includeDetails: z.boolean().optional(),
102
- maxViolations: z.number().int().positive().max(1000).optional(),
103
- shapesGraph: z.string().url({ message: 'Must be a valid URL' }).optional(),
104
- })
105
- .optional(),
106
- });
107
-
108
- /**
109
- * Schema for DELTA predicate conditions
110
- */
111
- export const DeltaConditionSchema = z.object({
112
- kind: z.literal('delta'),
113
- spec: z.object({
114
- change: z.enum(['any', 'increase', 'decrease', 'modify']),
115
- key: z.array(z.string()).min(1),
116
- threshold: z.number().min(0).max(1).optional(),
117
- baseline: z.string().optional(),
118
- }),
119
- options: z
120
- .object({
121
- timeout: z.number().int().positive().max(30000).optional(),
122
- strict: z.boolean().optional(),
123
- })
124
- .optional(),
125
- });
126
-
127
- /**
128
- * Schema for THRESHOLD predicate conditions
129
- */
130
- export const ThresholdConditionSchema = z.object({
131
- kind: z.literal('threshold'),
132
- spec: z.object({
133
- var: z.string().min(1),
134
- op: z.enum(['>', '>=', '<', '<=', '==', '!=']),
135
- value: z.number(),
136
- aggregate: z.enum(['sum', 'avg', 'min', 'max', 'count']).optional(),
137
- }),
138
- options: z
139
- .object({
140
- timeout: z.number().int().positive().max(30000).optional(),
141
- strict: z.boolean().optional(),
142
- })
143
- .optional(),
144
- });
145
-
146
- /**
147
- * Schema for COUNT predicate conditions
148
- */
149
- export const CountConditionSchema = z.object({
150
- kind: z.literal('count'),
151
- spec: z.object({
152
- op: z.enum(['>', '>=', '<', '<=', '==', '!=']),
153
- value: z.number().int().nonnegative(),
154
- query: z.string().optional(), // SPARQL query for counting
155
- }),
156
- options: z
157
- .object({
158
- timeout: z.number().int().positive().max(30000).optional(),
159
- strict: z.boolean().optional(),
160
- })
161
- .optional(),
162
- });
163
-
164
- /**
165
- * Schema for WINDOW predicate conditions
166
- */
167
- export const WindowConditionSchema = z.object({
168
- kind: z.literal('window'),
169
- spec: z.object({
170
- size: z.number().int().positive(), // Window size in milliseconds
171
- slide: z.number().int().positive().optional(), // Slide interval
172
- aggregate: z.enum(['sum', 'avg', 'min', 'max', 'count']),
173
- query: z.string().optional(), // SPARQL query for windowing
174
- }),
175
- options: z
176
- .object({
177
- timeout: z.number().int().positive().max(30000).optional(),
178
- strict: z.boolean().optional(),
179
- })
180
- .optional(),
181
- });
182
-
183
- /**
184
- * Union schema for all condition types
185
- */
186
- export const ConditionSchema = z.discriminatedUnion('kind', [
187
- SparqlAskConditionSchema,
188
- SparqlSelectConditionSchema,
189
- ShaclConditionSchema,
190
- DeltaConditionSchema,
191
- ThresholdConditionSchema,
192
- CountConditionSchema,
193
- WindowConditionSchema,
194
- ]);
195
-
196
- /**
197
- * Schema for determinism configuration
198
- */
199
- export const DeterminismSchema = z.object({
200
- seed: z.number().int().nonnegative().max(2147483647).default(42),
201
- algorithm: z.enum(['lcg', 'xorshift', 'mersenne']).default('lcg'),
202
- salt: z.string().min(1).max(100).optional(),
203
- });
204
-
205
- /**
206
- * Schema for receipt configuration
207
- */
208
- export const ReceiptSchema = z.object({
209
- anchor: z
210
- .enum(['none', 'blockchain', 'merkle', 'timestamp', 'hash', 'git-notes'])
211
- .default('none'),
212
- format: z.enum(['json', 'jsonld', 'rdf', 'turtle']).default('json'),
213
- includeProof: z.boolean().default(false),
214
- ttl: z.number().int().positive().max(86400).optional(), // Time to live in seconds
215
- });
216
-
217
- /**
218
- * Schema for hook execution context
219
- */
220
- export const HookContextSchema = z.object({
221
- graph: z.any(), // RDF Store instance - validated at runtime
222
- env: z.record(z.any()).optional(),
223
- metadata: z.record(z.any()).optional(),
224
- transactionId: z.string().uuid({ message: 'Must be a valid UUID' }).optional(),
225
- timestamp: z.coerce.date().optional(),
226
- });
227
-
228
- /**
229
- * Schema for hook events
230
- */
231
- export const HookEventSchema = z.object({
232
- name: z.string().min(1).max(100),
233
- payload: z.any(), // Flexible payload structure
234
- context: HookContextSchema,
235
- id: z.string().uuid({ message: 'Must be a valid UUID' }).optional(),
236
- timestamp: z.coerce.date().optional(),
237
- source: z.string().min(1).max(100).optional(),
238
- correlationId: z.string().uuid({ message: 'Must be a valid UUID' }).optional(),
239
- });
240
-
241
- /**
242
- * Schema for hook execution results
243
- */
244
- export const HookResultSchema = z.object({
245
- success: z.boolean(),
246
- result: z.any().optional(),
247
- error: z.string().optional(),
248
- duration: z.number().nonnegative().optional(),
249
- phase: z.enum(['before', 'run', 'after', 'completed', 'failed']).optional(),
250
- cancelled: z.boolean().default(false),
251
- metadata: z.record(z.any()).optional(),
252
- assertions: z
253
- .array(
254
- z.object({
255
- subject: z.string(),
256
- predicate: z.string(),
257
- object: z.string(),
258
- graph: z.string().optional(),
259
- })
260
- )
261
- .optional(),
262
- });
263
-
264
- /**
265
- * Schema for hook channel configuration
266
- */
267
- export const HookChannelSchema = z.object({
268
- graphs: z.array(z.string()).optional(),
269
- view: z.enum(['before', 'after', 'delta']).optional(),
270
- });
271
-
272
- /**
273
- * Schema for complete knowledge hook definition
274
- */
275
- export const KnowledgeHookSchema = z.object({
276
- meta: HookMetaSchema,
277
- channel: HookChannelSchema.optional(),
278
- when: ConditionSchema,
279
- run: z.function(),
280
- before: z.function().optional(),
281
- after: z.function().optional(),
282
- determinism: DeterminismSchema.optional(),
283
- receipt: ReceiptSchema.optional(),
284
- timeout: z.number().int().positive().max(300000).optional(), // 5 minutes max
285
- retries: z.number().int().nonnegative().max(5).optional(),
286
- priority: z.number().int().min(0).max(100).default(50).optional(),
287
- });
288
-
289
- /**
290
- * Schema for transaction delta
291
- */
292
- export const TransactionDeltaSchema = z.object({
293
- additions: z.array(z.any()).default([]), // RDF Quad array
294
- removals: z.array(z.any()).default([]), // RDF Quad array
295
- metadata: z.record(z.any()).optional(),
296
- id: z.string().optional(),
297
- timestamp: z.coerce.date().optional(),
298
- });
299
-
300
- /**
301
- * Schema for transaction receipt
302
- */
303
- export const TransactionReceiptSchema = z.object({
304
- committed: z.boolean(),
305
- delta: TransactionDeltaSchema,
306
- hookResults: z
307
- .array(
308
- z.object({
309
- hookId: z.string(),
310
- result: z.boolean(),
311
- error: z.string().optional(),
312
- duration: z.number().nonnegative().optional(),
313
- })
314
- )
315
- .default([]),
316
- beforeHash: z
317
- .object({
318
- sha3: z.string(),
319
- blake3: z.string(),
320
- })
321
- .optional(),
322
- afterHash: z
323
- .object({
324
- sha3: z.string(),
325
- blake3: z.string(),
326
- })
327
- .optional(),
328
- timestamp: z.coerce.date(),
329
- duration: z.number().nonnegative(),
330
- knowledgeHookResults: z.number().int().nonnegative().default(0),
331
- });
332
-
333
- /**
334
- * Schema for OpenTelemetry configuration
335
- */
336
- export const ObservabilityConfigSchema = z.object({
337
- enableTracing: z.boolean().default(true),
338
- enableMetrics: z.boolean().default(true),
339
- enableLogging: z.boolean().default(true),
340
- serviceName: z
341
- .string()
342
- .min(1)
343
- .max(100)
344
- .regex(/^[a-zA-Z0-9._-]+$/)
345
- .default('unrdf-kgc'),
346
- serviceVersion: z.string().min(1).max(50).default('1.0.0'),
347
- endpoint: z.string().url().optional(),
348
- headers: z.record(z.string()).optional(),
349
- resourceAttributes: z.record(z.string()).optional(),
350
- samplingRatio: z.number().min(0).max(1).default(1.0),
351
- maxQueueSize: z.number().int().positive().default(2048),
352
- maxExportBatchSize: z.number().int().positive().default(512),
353
- exportTimeoutMillis: z.number().int().positive().default(30000),
354
- scheduledDelayMillis: z.number().int().positive().default(5000),
355
- // Optional: advertise the maximum cache size used by the runtime for metrics
356
- cacheMaxSize: z.number().int().nonnegative().optional(),
357
- // Smoothing to reduce false-positive alerts from low samples/spikes
358
- minSamples: z.number().int().positive().default(20),
359
- ewmaAlpha: z.number().min(0).max(1).default(0.3),
360
- });
361
-
362
- /**
363
- * Schema for performance metrics
364
- */
365
- export const PerformanceMetricsSchema = z.object({
366
- transactionLatency: z.object({
367
- p50: z.number().nonnegative(),
368
- p95: z.number().nonnegative(),
369
- p99: z.number().nonnegative(),
370
- max: z.number().nonnegative(),
371
- }),
372
- hookExecutionRate: z.number().nonnegative(), // hooks per minute
373
- errorRate: z.number().min(0).max(1),
374
- memoryUsage: z.object({
375
- rss: z.number().nonnegative(),
376
- heapUsed: z.number().nonnegative(),
377
- heapTotal: z.number().nonnegative(),
378
- external: z.number().nonnegative(),
379
- }),
380
- cacheStats: z.object({
381
- hitRate: z.number().min(0).max(1),
382
- size: z.number().nonnegative(),
383
- maxSize: z.number().nonnegative(),
384
- }),
385
- backpressure: z.object({
386
- queueDepth: z.number().nonnegative(),
387
- watermarks: z.object({
388
- high: z.number().nonnegative(),
389
- low: z.number().nonnegative(),
390
- }),
391
- }),
392
- });
393
-
394
- /**
395
- * Schema for manager configuration
396
- */
397
- export const ManagerConfigSchema = z.object({
398
- basePath: z.string().min(1).default(process.cwd()),
399
- strictMode: z.boolean().default(false),
400
- enableConditionEvaluation: z.boolean().default(true),
401
- maxHooks: z.number().int().positive().max(1000).default(100),
402
- timeout: z.number().int().positive().max(300000).default(30000),
403
- enableCache: z.boolean().default(true),
404
- cacheMaxAge: z.number().int().positive().max(3600000).default(300000), // 5 minutes
405
- enableMetrics: z.boolean().default(true),
406
- logLevel: z.enum(['error', 'warn', 'info', 'debug']).default('info'),
407
- observability: ObservabilityConfigSchema.optional(),
408
- performance: z
409
- .object({
410
- enableProfiling: z.boolean().default(false),
411
- maxConcurrency: z.number().int().positive().default(10),
412
- afterHashOnly: z.boolean().default(false), // KGC PRD fast path
413
- enableCache: z.boolean().default(true),
414
- timeoutMs: z.number().int().positive().default(2000), // KGC PRD: p99 ≤ 2ms
415
- maxHooks: z.number().int().positive().default(10000), // KGC PRD: 10k exec/min
416
- })
417
- .optional(),
418
- });
419
-
420
- /**
421
- * Schema for file resolver configuration
422
- */
423
- export const FileResolverConfigSchema = z.object({
424
- basePath: z.string().min(1).default(process.cwd()),
425
- enableCache: z.boolean().default(true),
426
- cacheMaxAge: z.number().int().positive().max(3600000).default(300000),
427
- maxFileSize: z.number().int().positive().max(10485760).default(1048576), // 1MB default
428
- allowedMediaTypes: z
429
- .array(z.string())
430
- .default([
431
- 'application/sparql-query',
432
- 'text/turtle',
433
- 'application/rdf+xml',
434
- 'application/ld+json',
435
- ]),
436
- timeout: z.number().int().positive().max(30000).default(5000),
437
- });
438
-
439
- /**
440
- * Schema for condition evaluator configuration
441
- */
442
- export const ConditionEvaluatorConfigSchema = z.object({
443
- enableCache: z.boolean().default(true),
444
- cacheMaxAge: z.number().int().positive().max(3600000).default(300000),
445
- timeout: z.number().int().positive().max(30000).default(10000),
446
- maxConcurrent: z.number().int().positive().max(100).default(10),
447
- retries: z.number().int().nonnegative().max(3).default(1),
448
- strict: z.boolean().default(false),
449
- });
450
-
451
- /**
452
- * Schema for hook executor configuration
453
- */
454
- export const HookExecutorConfigSchema = z.object({
455
- timeout: z.number().int().positive().max(300000).default(30000),
456
- maxConcurrent: z.number().int().positive().max(100).default(10),
457
- retries: z.number().int().nonnegative().max(3).default(1),
458
- enableMetrics: z.boolean().default(true),
459
- strict: z.boolean().default(false),
460
- enableAssertions: z.boolean().default(true),
461
- });
462
-
463
- /**
464
- * Validation functions
465
- */
466
-
467
- /**
468
- * Validate a knowledge hook definition
469
- * @param {any} hook - The hook definition to validate
470
- * @returns {Object} Validation result
471
- */
472
- export function validateKnowledgeHook(hook) {
473
- try {
474
- const validated = KnowledgeHookSchema.parse(hook);
475
- return { success: true, data: validated, errors: [] };
476
- } catch (error) {
477
- if (error instanceof z.ZodError) {
478
- return {
479
- success: false,
480
- data: null,
481
- errors: (error.issues || error.errors || []).map(err => ({
482
- path: err.path?.join('.') || 'unknown',
483
- message: err.message || 'Unknown error',
484
- code: err.code || 'unknown',
485
- received: err.received,
486
- expected: err.expected,
487
- })),
488
- };
489
- }
490
- throw error;
491
- }
492
- }
493
-
494
- /**
495
- * Validate a hook event
496
- * @param {any} event - The event to validate
497
- * @returns {Object} Validation result
498
- */
499
- export function validateHookEvent(event) {
500
- try {
501
- const validated = HookEventSchema.parse(event);
502
- return { success: true, data: validated, errors: [] };
503
- } catch (error) {
504
- if (error instanceof z.ZodError) {
505
- return {
506
- success: false,
507
- data: null,
508
- errors: (error.issues || error.errors || []).map(err => ({
509
- path: err.path?.join('.') || 'unknown',
510
- message: err.message || 'Unknown error',
511
- code: err.code || 'unknown',
512
- received: err.received,
513
- expected: err.expected,
514
- })),
515
- };
516
- }
517
- throw error;
518
- }
519
- }
520
-
521
- /**
522
- * Validate a condition
523
- * @param {any} condition - The condition to validate
524
- * @returns {Object} Validation result
525
- */
526
- export function validateCondition(condition) {
527
- try {
528
- const validated = ConditionSchema.parse(condition);
529
- return { success: true, data: validated, errors: [] };
530
- } catch (error) {
531
- if (error instanceof z.ZodError) {
532
- return {
533
- success: false,
534
- data: null,
535
- errors: (error.issues || error.errors || []).map(err => ({
536
- path: err.path?.join('.') || 'unknown',
537
- message: err.message || 'Unknown error',
538
- code: err.code || 'unknown',
539
- received: err.received,
540
- expected: err.expected,
541
- })),
542
- };
543
- }
544
- throw error;
545
- }
546
- }
547
-
548
- /**
549
- * Validate manager configuration
550
- * @param {any} config - The configuration to validate
551
- * @returns {Object} Validation result
552
- */
553
- export function validateManagerConfig(config) {
554
- try {
555
- const validated = ManagerConfigSchema.parse(config);
556
- return { success: true, data: validated, errors: [] };
557
- } catch (error) {
558
- if (error instanceof z.ZodError) {
559
- return {
560
- success: false,
561
- data: null,
562
- errors:
563
- error.errors?.map(err => ({
564
- path: err.path?.join('.') || 'unknown',
565
- message: err.message || 'Unknown error',
566
- code: err.code || 'unknown',
567
- })) || [],
568
- };
569
- }
570
- throw error;
571
- }
572
- }
573
-
574
- /**
575
- * Validate transaction delta
576
- * @param {any} delta - The delta to validate
577
- * @returns {Object} Validation result
578
- */
579
- export function validateTransactionDelta(delta) {
580
- try {
581
- const validated = TransactionDeltaSchema.parse(delta);
582
- return { success: true, data: validated, errors: [] };
583
- } catch (error) {
584
- if (error instanceof z.ZodError) {
585
- return {
586
- success: false,
587
- data: null,
588
- errors:
589
- error.errors?.map(err => ({
590
- path: err.path?.join('.') || 'unknown',
591
- message: err.message || 'Unknown error',
592
- code: err.code || 'unknown',
593
- })) || [],
594
- };
595
- }
596
- throw error;
597
- }
598
- }
599
-
600
- /**
601
- * Type-safe hook definition creator
602
- * @param {any} definition - The hook definition
603
- * @returns {Object} Validated and frozen hook definition
604
- */
605
- export function createKnowledgeHook(definition) {
606
- try {
607
- const validation = validateKnowledgeHook(definition);
608
-
609
- if (!validation.success) {
610
- console.error('Validation errors:', validation.errors);
611
- console.error('Definition:', definition);
612
- const errorMessages =
613
- validation.errors
614
- ?.map(err => {
615
- let msg = `${err.path}: ${err.message}`;
616
- if (err.received !== undefined) {
617
- msg += ` (received: ${JSON.stringify(err.received)})`;
618
- }
619
- if (err.expected !== undefined) {
620
- msg += ` (expected: ${err.expected})`;
621
- }
622
- return msg;
623
- })
624
- .join(', ') || 'Unknown validation error';
625
- throw new TypeError(`Invalid knowledge hook definition: ${errorMessages}`);
626
- }
627
-
628
- // Apply defaults and freeze
629
- const normalized = {
630
- ...validation.data,
631
- determinism: { seed: 42, ...validation.data.determinism },
632
- receipt: { anchor: 'none', ...validation.data.receipt },
633
- priority: validation.data.priority ?? 50,
634
- };
635
-
636
- return Object.freeze(normalized);
637
- } catch (error) {
638
- if (error instanceof TypeError) {
639
- throw error;
640
- }
641
- console.error('Unexpected error in createKnowledgeHook:', error);
642
- throw new TypeError(`Invalid knowledge hook definition: ${error.message}`);
643
- }
644
- }
645
-
646
- /**
647
- * Type-safe event creator
648
- * @param {any} event - The event definition
649
- * @returns {Object} Validated event
650
- */
651
- export function createHookEvent(event) {
652
- const validation = validateHookEvent(event);
653
-
654
- if (!validation.success) {
655
- const errorMessages =
656
- validation.errors
657
- ?.map(err => {
658
- let msg = `${err.path}: ${err.message}`;
659
- if (err.received !== undefined) {
660
- msg += ` (received: ${JSON.stringify(err.received)})`;
661
- }
662
- if (err.expected !== undefined) {
663
- msg += ` (expected: ${err.expected})`;
664
- }
665
- return msg;
666
- })
667
- .join(', ') || 'Unknown validation error';
668
- throw new TypeError(`Invalid hook event: ${errorMessages}`);
669
- }
670
-
671
- // Apply defaults
672
- const normalized = {
673
- ...validation.data,
674
- id: validation.data.id ?? crypto.randomUUID(),
675
- timestamp: validation.data.timestamp ?? new Date().toISOString(),
676
- };
677
-
678
- return normalized;
679
- }
680
-
681
- /**
682
- * Type-safe condition creator
683
- * @param {any} condition - The condition definition
684
- * @returns {Object} Validated condition
685
- */
686
- export function createCondition(condition) {
687
- const validation = validateCondition(condition);
688
-
689
- if (!validation.success) {
690
- const errorMessages =
691
- validation.errors
692
- ?.map(err => {
693
- let msg = `${err.path}: ${err.message}`;
694
- if (err.received !== undefined) {
695
- msg += ` (received: ${JSON.stringify(err.received)})`;
696
- }
697
- if (err.expected !== undefined) {
698
- msg += ` (expected: ${err.expected})`;
699
- }
700
- return msg;
701
- })
702
- .join(', ') || 'Unknown validation error';
703
- throw new TypeError(`Invalid condition: ${errorMessages}`);
704
- }
705
-
706
- return validation.data;
707
- }
708
-
709
- // ========================================
710
- // Consolidated Schemas from Other Files
711
- // ========================================
712
-
713
- /**
714
- * Schema for RDF quads (from transaction.mjs)
715
- */
716
- export const QuadSchema = z
717
- .object({
718
- subject: z.any(), // RDF/JS Term
719
- predicate: z.any(), // RDF/JS Term
720
- object: z.any(), // RDF/JS Term
721
- graph: z.any().optional(), // RDF/JS Term
722
- equals: z.function().optional(),
723
- })
724
- .passthrough(); // Allow additional properties for RDF/JS Quad objects
725
-
726
- /**
727
- * Schema for delta (from transaction.mjs)
728
- */
729
- export const DeltaSchema = z.object({
730
- additions: z.array(QuadSchema),
731
- removals: z.array(QuadSchema),
732
- });
733
-
734
- /**
735
- * Schema for transaction hooks (from transaction.mjs)
736
- */
737
- export const TransactionHookSchema = z.object({
738
- id: z.string().min(1),
739
- mode: z.enum(['pre', 'post']),
740
- condition: z.function(),
741
- effect: z.union([z.literal('veto'), z.function()]),
742
- });
743
-
744
- /**
745
- * Schema for hook results (from transaction.mjs)
746
- */
747
- export const TransactionHookResultSchema = z.object({
748
- hookId: z.string(),
749
- mode: z.enum(['pre', 'post']),
750
- result: z.boolean(),
751
- error: z.string().optional(),
752
- });
753
-
754
- /**
755
- * Schema for hash values (from transaction.mjs)
756
- */
757
- export const HashSchema = z.object({
758
- sha3: z.string(),
759
- blake3: z.string(),
760
- });
761
-
762
- /**
763
- * Schema for transaction receipt (from transaction.mjs)
764
- */
765
- export const TransactionReceiptSchemaNew = z.object({
766
- id: z.string(),
767
- delta: DeltaSchema,
768
- committed: z.boolean(),
769
- hookResults: z.array(TransactionHookResultSchema),
770
- beforeHash: HashSchema,
771
- afterHash: HashSchema,
772
- timestamp: z.number(),
773
- durationMs: z.number(),
774
- actor: z.string().optional(),
775
- hookErrors: z.array(z.string()),
776
- error: z.string().optional(),
777
- });
778
-
779
- /**
780
- * Schema for transaction options (from transaction.mjs)
781
- */
782
- export const TransactionOptionsSchema = z.object({
783
- skipHooks: z.boolean().default(false),
784
- timeoutMs: z.number().positive().default(30000),
785
- actor: z.string().optional(),
786
- });
787
-
788
- /**
789
- * Schema for manager options (from transaction.mjs)
790
- */
791
- export const ManagerOptionsSchema = z.object({
792
- basePath: z.string().min(1).default(process.cwd()),
793
- strictMode: z.boolean().default(false),
794
- enableConditionEvaluation: z.boolean().default(true),
795
- maxHooks: z.number().int().positive().max(1000).default(100),
796
- timeout: z.number().int().positive().max(300000).default(30000),
797
- enableCache: z.boolean().default(true),
798
- cacheMaxAge: z.number().int().positive().max(3600000).default(300000), // 5 minutes
799
- enableMetrics: z.boolean().default(true),
800
- logLevel: z.enum(['error', 'warn', 'info', 'debug']).default('info'),
801
- });
802
-
803
- /**
804
- * Schema for query plans (from query-optimizer.mjs)
805
- */
806
- export const QueryPlanSchema = z.object({
807
- id: z.string(),
808
- query: z.string(),
809
- type: z.enum(['sparql-ask', 'sparql-select', 'shacl']),
810
- hash: z.string(),
811
- plan: z.object({
812
- operations: z.array(
813
- z.object({
814
- type: z.string(),
815
- cost: z.number(),
816
- selectivity: z.number(),
817
- dependencies: z.array(z.string()).optional(),
818
- })
819
- ),
820
- estimatedCost: z.number(),
821
- estimatedRows: z.number(),
822
- indexes: z.array(z.string()).optional(),
823
- }),
824
- createdAt: z.number(),
825
- lastUsed: z.number(),
826
- hitCount: z.number().default(0),
827
- });
828
-
829
- /**
830
- * Schema for index definitions (from query-optimizer.mjs)
831
- */
832
- export const IndexSchema = z.object({
833
- id: z.string(),
834
- name: z.string(),
835
- type: z.enum(['predicate', 'subject', 'object', 'graph', 'composite']),
836
- fields: z.array(z.string()),
837
- selectivity: z.number().min(0).max(1),
838
- size: z.number().nonnegative(),
839
- createdAt: z.number(),
840
- lastUpdated: z.number(),
841
- });
842
-
843
- /**
844
- * Schema for delta-aware evaluation context (from query-optimizer.mjs)
845
- */
846
- export const DeltaAwareContextSchema = z.object({
847
- delta: z.object({
848
- additions: z.array(z.any()),
849
- removals: z.array(z.any()),
850
- }),
851
- affectedSubjects: z.set(z.string()).optional(),
852
- affectedPredicates: z.set(z.string()).optional(),
853
- affectedObjects: z.set(z.string()).optional(),
854
- affectedGraphs: z.set(z.string()).optional(),
855
- });
856
-
857
- /**
858
- * Schema for agent proposals (from resolution-layer.mjs)
859
- */
860
- export const AgentProposalSchema = z.object({
861
- id: z.string().uuid(),
862
- agentId: z.string().min(1),
863
- delta: z.object({
864
- additions: z.array(z.any()),
865
- removals: z.array(z.any()),
866
- metadata: z.record(z.any()).optional(),
867
- }),
868
- confidence: z.number().min(0).max(1),
869
- priority: z.number().int().min(0).max(100).default(50),
870
- timestamp: z.number(),
871
- metadata: z.record(z.any()).optional(),
872
- dependencies: z.array(z.string()).optional(),
873
- conflicts: z.array(z.string()).optional(),
874
- });
875
-
876
- /**
877
- * Schema for resolution strategies (from resolution-layer.mjs)
878
- */
879
- export const ResolutionStrategySchema = z.object({
880
- type: z.enum(['voting', 'merging', 'crdt', 'consensus', 'priority', 'random']),
881
- parameters: z.record(z.any()).optional(),
882
- timeout: z.number().int().positive().max(300000).default(30000),
883
- quorum: z.number().min(0).max(1).default(0.5),
884
- maxRetries: z.number().int().nonnegative().max(10).default(3),
885
- });
886
-
887
- /**
888
- * Schema for resolution results (from resolution-layer.mjs)
889
- */
890
- export const ResolutionResultSchema = z.object({
891
- id: z.string().uuid(),
892
- strategy: z.string(),
893
- proposals: z.array(AgentProposalSchema),
894
- resolvedDelta: z.object({
895
- additions: z.array(z.any()),
896
- removals: z.array(z.any()),
897
- metadata: z.record(z.any()).optional(),
898
- }),
899
- confidence: z.number().min(0).max(1),
900
- consensus: z.boolean(),
901
- conflicts: z
902
- .array(
903
- z.object({
904
- type: z.enum(['addition', 'removal', 'metadata']),
905
- proposals: z.array(z.string()),
906
- resolution: z.string(),
907
- })
908
- )
909
- .optional(),
910
- timestamp: z.number(),
911
- duration: z.number().nonnegative(),
912
- });
913
-
914
- /**
915
- * Schema for sandbox configuration (from effect-sandbox.mjs)
916
- */
917
- export const SandboxConfigSchema = z.object({
918
- type: z.enum(['vm2', 'worker', 'isolate']).default('worker'),
919
- timeout: z.number().int().positive().max(300000).default(30000),
920
- memoryLimit: z
921
- .number()
922
- .int()
923
- .positive()
924
- .max(1024 * 1024 * 1024)
925
- .default(64 * 1024 * 1024), // 64MB
926
- cpuLimit: z.number().int().positive().max(100).default(50), // 50% CPU
927
- allowedModules: z.array(z.string()).default([]),
928
- allowedGlobals: z.array(z.string()).default(['console', 'Date', 'Math', 'JSON']),
929
- enableNetwork: z.boolean().default(false),
930
- enableFileSystem: z.boolean().default(false),
931
- enableProcess: z.boolean().default(false),
932
- strictMode: z.boolean().default(true),
933
- });
934
-
935
- /**
936
- * Schema for sandbox execution context (from effect-sandbox.mjs)
937
- */
938
- export const SandboxContextSchema = z.object({
939
- event: z.any(),
940
- store: z.any(),
941
- delta: z.any(),
942
- metadata: z.record(z.any()).optional(),
943
- allowedFunctions: z.array(z.string()).default(['emitEvent', 'log', 'assert']),
944
- });
945
-
946
- /**
947
- * Schema for sandbox execution result (from effect-sandbox.mjs)
948
- */
949
- export const SandboxResultSchema = z.object({
950
- success: z.boolean(),
951
- result: z.any().optional(),
952
- error: z.string().optional(),
953
- duration: z.number().nonnegative(),
954
- memoryUsed: z.number().nonnegative().optional(),
955
- cpuUsed: z.number().nonnegative().optional(),
956
- assertions: z
957
- .array(
958
- z.object({
959
- subject: z.string(),
960
- predicate: z.string(),
961
- object: z.string(),
962
- graph: z.string().optional(),
963
- })
964
- )
965
- .optional(),
966
- events: z.array(z.any()).optional(),
967
- });
968
-
969
- /**
970
- * Schema for lockchain entries (from lockchain-writer.mjs)
971
- */
972
- export const LockchainEntrySchema = z.object({
973
- id: z.string().uuid(),
974
- timestamp: z.number(),
975
- receipt: z.any(), // Transaction receipt
976
- signature: z.object({
977
- algorithm: z.string(),
978
- value: z.string(),
979
- publicKey: z.string().optional(),
980
- }),
981
- previousHash: z.string().optional().nullable(),
982
- merkleRoot: z.string().optional(),
983
- gitCommit: z.string().optional(),
984
- gitRef: z.string().optional(),
985
- });
986
-
987
- /**
988
- * Schema for lockchain configuration (from lockchain-writer.mjs)
989
- */
990
- export const LockchainConfigSchema = z.object({
991
- gitRepo: z.string().default(process.cwd()),
992
- refName: z.string().default('refs/notes/lockchain'),
993
- signingKey: z.string().optional(),
994
- algorithm: z.enum(['ed25519', 'ecdsa', 'rsa']).default('ed25519'),
995
- batchSize: z.number().int().positive().default(10),
996
- enableMerkle: z.boolean().default(true),
997
- enableGitAnchoring: z.boolean().default(true),
998
- storagePath: z.string().optional(),
999
- });
1000
-
1001
- /**
1002
- * Schema for policy pack metadata (from policy-pack.mjs)
1003
- */
1004
- export const PolicyPackMetaSchema = z.object({
1005
- name: z.string().min(1).max(100),
1006
- version: z.string().regex(/^\d+\.\d+\.\d+$/),
1007
- description: z.string().min(1).max(500).optional(),
1008
- author: z.string().min(1).max(100).optional(),
1009
- license: z.string().min(1).max(100).optional(),
1010
- homepage: z.string().url().optional(),
1011
- repository: z.string().url().optional(),
1012
- keywords: z.array(z.string().min(1).max(50)).max(20).optional(),
1013
- ontology: z.array(z.string().min(1).max(50)).max(10).optional(),
1014
- dependencies: z.array(z.string()).optional(),
1015
- createdAt: z.coerce.date().optional(),
1016
- updatedAt: z.coerce.date().optional(),
1017
- });
1018
-
1019
- /**
1020
- * Schema for policy pack configuration (from policy-pack.mjs)
1021
- */
1022
- export const PolicyPackConfigSchema = z.object({
1023
- basePath: z.string().min(1).default(process.cwd()),
1024
- manifestPath: z.string().default('./policy-pack.json'),
1025
- hooksPath: z.string().default('./hooks'),
1026
- activateOnLoad: z.boolean().default(false),
1027
- enableValidation: z.boolean().default(true),
1028
- maxHooks: z.number().int().positive().max(100).default(50),
1029
- timeout: z.number().int().positive().max(300000).default(30000),
1030
- strictMode: z.boolean().default(false),
1031
- });
1032
-
1033
- /**
1034
- * Schema for policy pack manifest (from policy-pack.mjs)
1035
- */
1036
- export const PolicyPackManifestSchema = z.object({
1037
- meta: PolicyPackMetaSchema,
1038
- hooks: z.array(
1039
- z.object({
1040
- file: z.string().min(1),
1041
- condition: z.object({
1042
- kind: z.enum(['sparql-ask', 'sparql-select', 'shacl']),
1043
- ref: FileRefSchema,
1044
- }),
1045
- priority: z.number().int().min(0).max(100).default(50).optional(),
1046
- enabled: z.boolean().default(true).optional(),
1047
- })
1048
- ),
1049
- rules: z
1050
- .array(
1051
- z.object({
1052
- id: z.string().min(1),
1053
- description: z.string().min(1).max(500),
1054
- severity: z.enum(['error', 'warn', 'info']).default('info'),
1055
- condition: z.string().min(1),
1056
- appliesTo: z.array(z.string()).optional(),
1057
- excludeFrom: z.array(z.string()).optional(),
1058
- })
1059
- )
1060
- .optional(),
1061
- dependencies: z.array(z.string()).optional(),
1062
- peerDependencies: z.array(z.string()).optional(),
1063
- });