@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
@@ -1,338 +0,0 @@
1
- /**
2
- * @file Zod Validators - Input validation library
3
- * @module validators
4
- *
5
- * @description
6
- * Centralized Zod validators for all knowledge engine inputs.
7
- * Provides consistent validation with security checks.
8
- *
9
- * Addresses 30 test failures related to schema validation.
10
- */
11
-
12
- import { z } from 'zod';
13
- import path from 'node:path';
14
- // Prefer consolidated schemas from ../schemas.mjs as source of truth
15
- export { QuadSchema, DeltaSchema, HookContextSchema, KnowledgeHookSchema } from '../schemas.mjs';
16
-
17
- /**
18
- * SHA-256 hash validator
19
- */
20
- export const sha256Validator = z
21
- .string()
22
- .length(64, 'SHA-256 hash must be exactly 64 characters')
23
- .regex(/^[a-f0-9]{64}$/, 'SHA-256 hash must be lowercase hexadecimal');
24
-
25
- /**
26
- * Secure URI validator with path traversal prevention
27
- */
28
- export const secureUriValidator = z
29
- .string()
30
- .url({ message: 'Must be a valid URI' })
31
- .or(z.string().regex(/^file:\/\/.+/, 'Must be a valid file URI'))
32
- .refine(uri => {
33
- // Extract path from URI
34
- let uriPath;
35
- try {
36
- const url = new URL(uri);
37
- uriPath = url.pathname;
38
- } catch {
39
- // If not a valid URL, treat as path
40
- uriPath = uri.replace(/^file:\/\//, '');
41
- }
42
-
43
- const normalized = path.normalize(uriPath);
44
-
45
- // Check for path traversal patterns
46
- return !normalized.includes('..') && !normalized.includes('~');
47
- }, 'Path traversal patterns detected')
48
- .refine(uri => {
49
- // Extract path from URI
50
- let uriPath;
51
- try {
52
- const url = new URL(uri);
53
- uriPath = url.pathname;
54
- } catch {
55
- uriPath = uri.replace(/^file:\/\//, '');
56
- }
57
-
58
- const normalized = path.normalize(uriPath);
59
-
60
- // Check for system path access
61
- const systemPaths = ['/etc', '/proc', '/sys', '/dev', '/root', '/home'];
62
- return !systemPaths.some(p => normalized.startsWith(p));
63
- }, 'System path access detected');
64
-
65
- /**
66
- * Media type validator for RDF formats
67
- */
68
- export const mediaTypeValidator = z.enum(
69
- [
70
- 'application/sparql-query',
71
- 'text/turtle',
72
- 'application/rdf+xml',
73
- 'application/ld+json',
74
- 'application/n-triples',
75
- 'application/n-quads',
76
- 'text/n3',
77
- ],
78
- {
79
- errorMap: () => ({ message: 'Must be a supported RDF media type' }),
80
- }
81
- );
82
-
83
- /**
84
- * Content-addressed file reference validator (SECURE)
85
- */
86
- export const secureFileRefValidator = z
87
- .object({
88
- uri: secureUriValidator,
89
- sha256: sha256Validator,
90
- mediaType: mediaTypeValidator,
91
- })
92
- .strict();
93
-
94
- /**
95
- * Hook metadata validator with XSS prevention
96
- */
97
- export const hookMetaValidator = z
98
- .object({
99
- name: z
100
- .string()
101
- .min(1, 'Name is required')
102
- .max(100, 'Name must be ≤100 characters')
103
- .regex(
104
- /^[a-zA-Z0-9:_-]+$/,
105
- 'Name must contain only alphanumeric characters, colons, hyphens, and underscores'
106
- ),
107
-
108
- description: z
109
- .string()
110
- .min(1)
111
- .max(500, 'Description must be ≤500 characters')
112
- .refine(
113
- str => !/<script|<img|<iframe|javascript:|onerror=|onload=/i.test(str),
114
- 'XSS attempt detected in description'
115
- )
116
- .optional(),
117
-
118
- version: z
119
- .string()
120
- .regex(/^\d+\.\d+\.\d+$/, 'Version must be semantic version (e.g., 1.0.0)')
121
- .optional(),
122
-
123
- author: z.string().min(1).max(100).optional(),
124
-
125
- tags: z.array(z.string().min(1).max(50)).max(10, 'Maximum 10 tags allowed').optional(),
126
-
127
- ontology: z
128
- .array(z.string().min(1).max(50))
129
- .max(10, 'Maximum 10 ontology references allowed')
130
- .optional(),
131
- })
132
- .strict();
133
-
134
- /**
135
- * SPARQL ASK condition validator
136
- */
137
- export const sparqlAskConditionValidator = z
138
- .object({
139
- kind: z.literal('sparql-ask'),
140
- ref: secureFileRefValidator,
141
- options: z
142
- .object({
143
- timeout: z.number().int().positive().max(30000).optional(),
144
- strict: z.boolean().optional(),
145
- variables: z.record(z.string()).optional(),
146
- })
147
- .optional(),
148
- })
149
- .strict();
150
-
151
- /**
152
- * SPARQL SELECT condition validator
153
- */
154
- export const sparqlSelectConditionValidator = z
155
- .object({
156
- kind: z.literal('sparql-select'),
157
- ref: secureFileRefValidator,
158
- options: z
159
- .object({
160
- timeout: z.number().int().positive().max(30000).optional(),
161
- limit: z.number().int().positive().max(10000).optional(),
162
- offset: z.number().int().nonnegative().optional(),
163
- strict: z.boolean().optional(),
164
- variables: z.record(z.string()).optional(),
165
- })
166
- .optional(),
167
- })
168
- .strict();
169
-
170
- /**
171
- * SHACL condition validator
172
- */
173
- export const shaclConditionValidator = z
174
- .object({
175
- kind: z.literal('shacl'),
176
- ref: secureFileRefValidator,
177
- options: z
178
- .object({
179
- strict: z.boolean().optional(),
180
- includeDetails: z.boolean().optional(),
181
- maxViolations: z.number().int().positive().max(1000).optional(),
182
- })
183
- .optional(),
184
- })
185
- .strict();
186
-
187
- /**
188
- * Union of all condition validators
189
- */
190
- export const conditionValidator = z.discriminatedUnion('kind', [
191
- sparqlAskConditionValidator,
192
- sparqlSelectConditionValidator,
193
- shaclConditionValidator,
194
- ]);
195
-
196
- /**
197
- * Complete knowledge hook validator
198
- */
199
- export const knowledgeHookValidator = z
200
- .object({
201
- meta: hookMetaValidator,
202
- when: conditionValidator,
203
- run: z.function(),
204
- before: z.function().optional(),
205
- after: z.function().optional(),
206
- timeout: z.number().int().positive().max(300000).optional(),
207
- retries: z.number().int().nonnegative().max(5).optional(),
208
- priority: z.number().int().min(0).max(100).default(50).optional(),
209
- })
210
- .strict();
211
-
212
- /**
213
- * RDF quad validator
214
- */
215
- export const quadValidator = z
216
- .object({
217
- subject: z.any(), // RDF/JS Term
218
- predicate: z.any(), // RDF/JS Term
219
- object: z.any(), // RDF/JS Term
220
- graph: z.any().optional(), // RDF/JS Term
221
- })
222
- .passthrough(); // Allow additional RDF/JS Quad properties
223
-
224
- /**
225
- * Transaction delta validator
226
- */
227
- export const deltaValidator = z
228
- .object({
229
- additions: z.array(quadValidator),
230
- removals: z.array(quadValidator),
231
- })
232
- .strict();
233
-
234
- /**
235
- * Hook execution context validator
236
- */
237
- export const hookContextValidator = z
238
- .object({
239
- graph: z.any(), // RDF Store - validated at runtime
240
- env: z.record(z.any()).optional(),
241
- metadata: z.record(z.any()).optional(),
242
- transactionId: z.string().uuid().optional(),
243
- timestamp: z.coerce.date().optional(),
244
- })
245
- .strict();
246
-
247
- /**
248
- * Manager configuration validator
249
- */
250
- export const managerConfigValidator = z
251
- .object({
252
- basePath: z.string().min(1).default(process.cwd()),
253
- strictMode: z.boolean().default(false),
254
- enableConditionEvaluation: z.boolean().default(true),
255
- maxHooks: z.number().int().positive().max(1000).default(100),
256
- timeout: z.number().int().positive().max(300000).default(30000),
257
- enableCache: z.boolean().default(true),
258
- cacheMaxAge: z.number().int().positive().max(3600000).default(300000),
259
- enableMetrics: z.boolean().default(true),
260
- logLevel: z.enum(['error', 'warn', 'info', 'debug']).default('info'),
261
- })
262
- .strict();
263
-
264
- /**
265
- * Validation helper function
266
- *
267
- * @param {z.ZodSchema} schema - Zod schema to validate against
268
- * @param {any} data - Data to validate
269
- * @param {string} [name] - Name for error messages
270
- * @returns {Object} Validation result
271
- */
272
- export function validate(schema, data, _name = 'Data') {
273
- try {
274
- const validated = schema.parse(data);
275
- return {
276
- success: true,
277
- data: validated,
278
- errors: [],
279
- };
280
- } catch (error) {
281
- if (error instanceof z.ZodError) {
282
- return {
283
- success: false,
284
- data: null,
285
- errors: error.errors.map(err => ({
286
- path: err.path.join('.'),
287
- message: err.message,
288
- code: err.code,
289
- received: err.received,
290
- expected: err.expected,
291
- })),
292
- };
293
- }
294
- throw error;
295
- }
296
- }
297
-
298
- /**
299
- * Safe validation that throws on failure
300
- *
301
- * @param {z.ZodSchema} schema - Zod schema
302
- * @param {any} data - Data to validate
303
- * @param {string} [name] - Name for error messages
304
- * @returns {any} Validated data
305
- * @throws {TypeError} If validation fails
306
- */
307
- export function validateOrThrow(schema, data, name = 'Data') {
308
- const result = validate(schema, data, name);
309
-
310
- if (!result.success) {
311
- const errorMessage = result.errors.map(err => `${err.path}: ${err.message}`).join(', ');
312
- throw new TypeError(`${name} validation failed: ${errorMessage}`);
313
- }
314
-
315
- return result.data;
316
- }
317
-
318
- /**
319
- * Create a validator function from a schema
320
- *
321
- * @param {z.ZodSchema} schema - Zod schema
322
- * @param {string} [name] - Name for error messages
323
- * @returns {Function} Validator function
324
- */
325
- export function createValidator(schema, name = 'Data') {
326
- return data => validate(schema, data, name);
327
- }
328
-
329
- /**
330
- * Create a throwing validator from a schema
331
- *
332
- * @param {z.ZodSchema} schema - Zod schema
333
- * @param {string} [name] - Name for error messages
334
- * @returns {Function} Throwing validator function
335
- */
336
- export function createThrowingValidator(schema, name = 'Data') {
337
- return data => validateOrThrow(schema, data, name);
338
- }