@unrdf/hooks 26.4.3 → 26.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +566 -53
  3. package/examples/atomvm-fibo-hooks-demo.mjs +323 -0
  4. package/examples/delta-monitoring-example.mjs +213 -0
  5. package/examples/fibo-jtbd-governance.mjs +388 -0
  6. package/examples/hook-chains/node_modules/.bin/jiti +0 -0
  7. package/examples/hook-chains/node_modules/.bin/msw +0 -0
  8. package/examples/hook-chains/node_modules/.bin/terser +0 -0
  9. package/examples/hook-chains/node_modules/.bin/tsc +0 -0
  10. package/examples/hook-chains/node_modules/.bin/tsserver +0 -0
  11. package/examples/hook-chains/node_modules/.bin/tsx +0 -0
  12. package/examples/hook-chains/node_modules/.bin/validate-hooks +0 -0
  13. package/examples/hook-chains/node_modules/.bin/vite +0 -0
  14. package/examples/hook-chains/node_modules/.bin/vitest +0 -0
  15. package/examples/hook-chains/node_modules/.bin/yaml +0 -0
  16. package/examples/hook-chains/package.json +2 -2
  17. package/examples/hooks-marketplace.mjs +261 -0
  18. package/examples/n3-reasoning-example.mjs +279 -0
  19. package/examples/policy-hooks/README.md +5 -9
  20. package/examples/policy-hooks/node_modules/.bin/jiti +0 -0
  21. package/examples/policy-hooks/node_modules/.bin/msw +0 -0
  22. package/examples/policy-hooks/node_modules/.bin/terser +0 -0
  23. package/examples/policy-hooks/node_modules/.bin/tsc +0 -0
  24. package/examples/policy-hooks/node_modules/.bin/tsserver +0 -0
  25. package/examples/policy-hooks/node_modules/.bin/tsx +0 -0
  26. package/examples/policy-hooks/node_modules/.bin/validate-hooks +0 -0
  27. package/examples/policy-hooks/node_modules/.bin/vite +0 -0
  28. package/examples/policy-hooks/node_modules/.bin/vitest +0 -0
  29. package/examples/policy-hooks/node_modules/.bin/yaml +0 -0
  30. package/examples/policy-hooks/package.json +2 -2
  31. package/examples/shacl-repair-example.mjs +191 -0
  32. package/examples/window-condition-example.mjs +285 -0
  33. package/package.json +27 -23
  34. package/src/atomvm.mjs +9 -0
  35. package/src/define.mjs +114 -0
  36. package/src/executor.mjs +23 -0
  37. package/src/hooks/atomvm-bridge.mjs +332 -0
  38. package/src/hooks/builtin-hooks.mjs +17 -9
  39. package/src/hooks/condition-evaluator.mjs +681 -77
  40. package/src/hooks/define-hook.mjs +23 -23
  41. package/src/hooks/effect-executor.mjs +618 -0
  42. package/src/hooks/effect-sandbox.mjs +19 -9
  43. package/src/hooks/file-resolver.mjs +155 -1
  44. package/src/hooks/hook-chain-compiler.mjs +10 -1
  45. package/src/hooks/hook-executor.mjs +102 -73
  46. package/src/hooks/knowledge-hook-engine.mjs +133 -7
  47. package/src/hooks/ontology-learner.mjs +190 -0
  48. package/src/hooks/query.mjs +3 -3
  49. package/src/hooks/schemas.mjs +47 -3
  50. package/src/hooks/security/error-sanitizer.mjs +46 -24
  51. package/src/hooks/self-play-autonomics.mjs +464 -0
  52. package/src/hooks/telemetry.mjs +32 -9
  53. package/src/hooks/validate.mjs +100 -33
  54. package/src/index.mjs +2 -0
  55. package/src/lib/admit-hook.mjs +615 -0
  56. package/src/policy-compiler.mjs +12 -2
  57. package/dist/index.d.mts +0 -1738
  58. package/dist/index.d.ts +0 -1738
  59. package/dist/index.mjs +0 -1738
package/LICENSE CHANGED
@@ -19,3 +19,27 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
+
23
+ ---
24
+
25
+ ## Third-Party Licenses
26
+
27
+ This package includes or depends on the following third-party components:
28
+
29
+ ### eyereasoner (eye-js)
30
+ - **License**: MIT
31
+ - **Copyright**: Copyright (c) 2022 Jesse Wright
32
+ - **Repository**: https://github.com/eyereasoner/eye-js
33
+ - **Description**: EYE reasoner for browser and Node.js via WebAssembly
34
+
35
+ ### swipl-wasm (SWI-Prolog WebAssembly)
36
+ - **License**: BSD-2-Clause (Simplified BSD)
37
+ - **Copyright**: Copyright (c) SWI-Prolog contributors
38
+ - **Repository**: https://github.com/nickmcdowall/swipl-wasm
39
+ - **Description**: SWI-Prolog compiled to WebAssembly, bundled by eyereasoner
40
+
41
+ ### @noble/hashes
42
+ - **License**: MIT
43
+ - **Copyright**: Copyright (c) 2022 Paul Miller
44
+ - **Repository**: https://github.com/paulmillr/noble-hashes
45
+ - **Description**: Cryptographic hash functions (BLAKE3) for receipt hashing
package/README.md CHANGED
@@ -1,86 +1,599 @@
1
- # @unrdf/hooks
1
+ # @unrdf/hooks - Knowledge Hook Engine
2
2
 
3
- ![Version](https://img.shields.io/badge/version-5.0.0--beta.1-blue) ![Production Ready](https://img.shields.io/badge/production-ready-green)
3
+ ![Version](https://img.shields.io/badge/version-6.0.0-blue) ![Production Ready](https://img.shields.io/badge/production-ready-green)
4
4
 
5
+ > Production-grade policy definition and execution framework for RDF knowledge graphs
6
+ >
7
+ > Implements 9 condition kinds, deterministic receipt chaining, SPARQL transformations, SHACL enforcement, N3 forward-chaining inference, and Datalog logic programming
5
8
 
6
- **Knowledge Hooks - Policy Definition and Execution Framework**
9
+ ## Overview
7
10
 
8
- The policy enforcement layer for UNRDF. Define and execute hooks to enforce rules, validate data, and transform quads.
11
+ The hooks package provides a complete governance layer for RDF operations with 6 core priorities:
9
12
 
10
- ## Installation
13
+ 1. **withReceipt Integration** - BLAKE3 cryptographic audit trails with receipt chaining
14
+ 2. **SPARQL CONSTRUCT Effects** - RDF-native transformations (SPARQL-native, no JavaScript)
15
+ 3. **SHACL Enforcement Modes** - Three modes (block/annotate/repair) for soft-fail governance
16
+ 4. **Input/Output Hash Receipts** - State change proof via canonical hashing with delta tracking
17
+ 5. **N3 Forward-Chaining Rules** - Inference engine via EYE reasoner with explicit rule definitions
18
+ 6. **Datalog Logic Programming** - Constraint evaluation via bottom-up fixpoint with goal satisfaction
19
+
20
+ ## Quick Start
21
+
22
+ ### Installation
11
23
 
12
24
  ```bash
13
- pnpm add @unrdf/hooks
25
+ pnpm add @unrdf/hooks @unrdf/v6-core @unrdf/oxigraph
14
26
  ```
15
27
 
16
- ## 📚 Examples
28
+ ### Basic Hook Definition
17
29
 
18
- See these examples that demonstrate @unrdf/hooks:
30
+ ```javascript
31
+ import { KnowledgeHookEngine, createKnowledgeHook } from '@unrdf/hooks';
32
+ import { createStore } from '@unrdf/oxigraph';
33
+ import { createContext } from '@unrdf/v6-core/receipt-pattern';
19
34
 
20
- - **[basic-knowledge-hook.mjs](../../examples/basic-knowledge-hook.mjs)** - Hook basics: validation and transformation (15 min)
21
- - **[define-hook-example.mjs](../../examples/define-hook-example.mjs)** - Advanced hook composition patterns (20 min)
22
- - **[production-hook-test.mjs](../../examples/production-hook-test.mjs)** - Production-ready hook testing
23
- - **[hook-lifecycle-test.mjs](../../examples/hook-lifecycle-test.mjs)** - Complete hook lifecycle
24
- - **[knowledge-hooks-events.mjs](../../examples/knowledge-hooks-events.mjs)** - Event-driven hooks
35
+ const store = createStore();
36
+ const engine = new KnowledgeHookEngine(store);
37
+ const context = createContext({
38
+ nodeId: 'my-app',
39
+ t_ns: BigInt(Date.now() * 1000000),
40
+ });
25
41
 
26
- **Want to learn hooks?** Follow the [hooks learning path](../../examples/README.md#-knowledge-hooks).
42
+ // Define a hook with SHACL condition (soft-fail annotation)
43
+ const hook = createKnowledgeHook({
44
+ name: 'validate-compliance',
45
+ condition: {
46
+ kind: 'shacl',
47
+ ref: { uri: 'file:///shapes/compliance.ttl' },
48
+ enforcementMode: 'annotate', // Log violations but don't block
49
+ },
50
+ effects: [
51
+ {
52
+ kind: 'sparql-construct',
53
+ query: `
54
+ CONSTRUCT {
55
+ ?s ex:status ex:Valid ;
56
+ ex:validatedAt ?now .
57
+ }
58
+ WHERE {
59
+ ?s ?p ?o .
60
+ BIND (NOW() as ?now)
61
+ }
62
+ `,
63
+ },
64
+ ],
65
+ });
27
66
 
28
- ## Quick Start
67
+ // Execute with receipt chaining
68
+ const result = await engine.execute(context, [hook]);
69
+
70
+ // Access deterministic receipt chain
71
+ console.log('Receipt Hash:', result.receipt.receiptHash); // BLAKE3(entire receipt)
72
+ console.log('Input Hash:', result.receipt.input_hash); // BLAKE3(store before)
73
+ console.log('Output Hash:', result.receipt.output_hash); // BLAKE3(store after)
74
+ console.log('Previous Hash:', result.receipt.previousReceiptHash); // Links to prior op
75
+ ```
76
+
77
+ ## 9 Condition Kinds
78
+
79
+ ### 1. SPARQL ASK (Boolean Query)
80
+
81
+ Returns true if SPARQL ASK query matches any bindings.
82
+
83
+ ```javascript
84
+ {
85
+ kind: 'sparql-ask',
86
+ query: 'ASK { ?s ?p ?o }'
87
+ }
88
+ ```
89
+
90
+ **Use Case**: Quick boolean checks without result binding.
91
+
92
+ ### 2. SPARQL SELECT (Result Set)
93
+
94
+ Returns true if SELECT query has results.
95
+
96
+ ```javascript
97
+ {
98
+ kind: 'sparql-select',
99
+ query: 'SELECT ?s WHERE { ?s a ex:Person }'
100
+ }
101
+ ```
102
+
103
+ **Use Case**: Condition depends on having matching results.
104
+
105
+ ### 3. SHACL Validation (RDF Shape)
106
+
107
+ Validates store against SHACL shape. Three enforcement modes for soft-fail governance.
108
+
109
+ ```javascript
110
+ {
111
+ kind: 'shacl',
112
+ ref: { uri: 'file:///shapes/person.ttl' },
113
+ enforcementMode: 'block', // or 'annotate', 'repair'
114
+ repairConstruct: 'CONSTRUCT { ?s ex:status ex:Repaired } WHERE { ... }'
115
+ }
116
+ ```
117
+
118
+ **Enforcement Modes**:
119
+
120
+ - `block`: Fail if violations exist (strict governance)
121
+ - `annotate`: Execute but add violations as RDF triples (soft-fail + audit trail)
122
+ - `repair`: Auto-fix via SPARQL CONSTRUCT then re-validate (self-healing)
123
+
124
+ ### 4. Delta (Change Detection)
125
+
126
+ Detects RDF changes (add/delete patterns) for reactive governance.
127
+
128
+ ```javascript
129
+ {
130
+ kind: 'delta',
131
+ adds: [{ subject: '?s', predicate: 'rdf:type', object: 'ex:Trade' }],
132
+ deletes: []
133
+ }
134
+ ```
135
+
136
+ **Use Case**: Trigger hooks only on specific RDF changes.
137
+
138
+ ### 5. Threshold (Numeric Comparison)
139
+
140
+ Compares numeric values against threshold for quantitative governance.
141
+
142
+ ```javascript
143
+ {
144
+ kind: 'threshold',
145
+ query: 'SELECT (COUNT(?s) as ?count) WHERE { ?s a ex:Trade }',
146
+ operator: 'greaterThan',
147
+ value: 100
148
+ }
149
+ ```
150
+
151
+ **Operators**: `greaterThan`, `lessThan`, `equal`, `greaterThanOrEqual`, `lessThanOrEqual`
152
+
153
+ ### 6. Count (Pattern Aggregation)
154
+
155
+ Counts matching patterns against expected value.
29
156
 
30
157
  ```javascript
31
- import { defineHook, executeHook } from '@unrdf/hooks'
158
+ {
159
+ kind: 'count',
160
+ pattern: { subject: '?s', predicate: 'ex:status', object: 'ex:Active' },
161
+ expected: 5
162
+ }
163
+ ```
164
+
165
+ **Use Case**: Enforce cardinality constraints.
166
+
167
+ ### 7. Window (Time Range Evaluation)
168
+
169
+ Evaluates conditions within time windows for temporal governance.
170
+
171
+ ```javascript
172
+ {
173
+ kind: 'window',
174
+ windowMs: 60000,
175
+ maxMatches: 10,
176
+ query: 'SELECT ?timestamp WHERE { ?s ex:timestamp ?timestamp }'
177
+ }
178
+ ```
179
+
180
+ **Use Case**: Rate limiting, temporal constraints.
181
+
182
+ ### 8. N3 Forward-Chaining Inference ⭐
183
+
184
+ Evaluates N3 rules via EYE reasoner for declarative inference.
185
+
186
+ ```javascript
187
+ {
188
+ kind: 'n3',
189
+ rules: `
190
+ { ?x a :RestrictedClass } => { ?x :requiresApproval true } .
191
+ { ?x :riskScore ?score . ?score > 50 } => { ?x :requiresReview true } .
192
+ `,
193
+ askQuery: 'ASK { ?s :requiresApproval true }'
194
+ }
195
+ ```
196
+
197
+ **Use Case**: Declarative rule application without imperative code.
198
+
199
+ ### 9. Datalog Logic Programming ⭐
200
+
201
+ Evaluates Datalog goals via bottom-up fixpoint for constraint solving.
202
+
203
+ ```javascript
204
+ {
205
+ kind: 'datalog',
206
+ facts: [
207
+ 'user(alice)',
208
+ 'admin(alice)',
209
+ 'group(admins)',
210
+ 'member(alice, admins)'
211
+ ],
212
+ rules: [
213
+ 'allowed(X) :- admin(X)',
214
+ 'allowed(X) :- member(X, admins)'
215
+ ],
216
+ goal: 'allowed(alice)'
217
+ }
218
+ ```
219
+
220
+ **Use Case**: Access control, permission evaluation via logical rules.
221
+
222
+ ## Effects (Transformations)
32
223
 
33
- // Define a validation hook
34
- defineHook('validate-pii', {
35
- type: 'validate-before-write',
36
- async check(quad) {
37
- // Reject PII without consent
38
- if (isPII(quad) && !hasConsent(quad.subject)) {
39
- return false
224
+ ### SPARQL CONSTRUCT (RDF-Native)
225
+
226
+ RDF-native transformation via SPARQL. No JavaScript required.
227
+
228
+ ```javascript
229
+ {
230
+ kind: 'sparql-construct',
231
+ query: `
232
+ CONSTRUCT {
233
+ ?s ex:processed true ;
234
+ ex:processedAt ?now ;
235
+ ex:delta ?deltaSize .
40
236
  }
41
- return true
42
- }
43
- })
237
+ WHERE {
238
+ ?s ?p ?o .
239
+ BIND (NOW() as ?now)
240
+ BIND (1 as ?deltaSize)
241
+ }
242
+ `
243
+ }
244
+ ```
245
+
246
+ **Advantage**: Pure RDF transformation, deterministic, no execution risk.
247
+
248
+ ### JavaScript Function (Legacy)
249
+
250
+ Execute custom logic. Included for backwards compatibility.
251
+
252
+ ```javascript
253
+ {
254
+ kind: 'function',
255
+ inline: async (store, quad) => {
256
+ // Custom transformation
257
+ return { success: true };
258
+ },
259
+ timeout: 30000,
260
+ sandbox: false
261
+ }
262
+ ```
263
+
264
+ ## SHACL Enforcement Modes (Priority 3)
265
+
266
+ ### Block Mode (Default)
44
267
 
45
- // Execute hooks
46
- const isValid = await executeHook('validate-pii', quad)
268
+ Prevents hook execution if SHACL validation fails. Strict governance.
269
+
270
+ ```javascript
271
+ {
272
+ kind: 'shacl',
273
+ ref: { uri: 'file:///shapes/strict.ttl' },
274
+ enforcementMode: 'block'
275
+ }
276
+ // Hook blocked if shape violations exist
277
+ // Result: Clean state or error
47
278
  ```
48
279
 
49
- ## Features
280
+ **Use Case**: Regulatory compliance, immutable audit trails.
281
+
282
+ ### Annotate Mode (Soft-Fail)
283
+
284
+ Executes hook but adds SHACL violations as RDF triples. Audit trail with soft-fail.
285
+
286
+ ```javascript
287
+ {
288
+ kind: 'shacl',
289
+ ref: { uri: 'file:///shapes/audit.ttl' },
290
+ enforcementMode: 'annotate'
291
+ }
292
+ // Violations materialized as RDF quads
293
+ // Result: Store updated + violations tracked in store
294
+ ```
50
295
 
51
- - Define custom hooks for any RDF operation
52
- - ✅ Pre-write validation (block invalid data)
53
- - ✅ Post-write transformation (modify data)
54
- - ✅ Hook composition (chain multiple hooks)
55
- - ✅ Type-safe hook definitions
56
- - ✅ Async/await support
296
+ **Use Case**: Logging, risk management, warning systems.
57
297
 
58
- ## Use Cases
298
+ ### Repair Mode (Self-Healing)
59
299
 
60
- - **Validation**: Check data before writing
61
- - **Transformation**: Modify quads on the fly
62
- - **Enforcement**: Implement security policies
63
- - **Audit**: Track and log changes
64
- - **Compliance**: Enforce regulatory requirements
300
+ Auto-repairs violations via SPARQL CONSTRUCT, then re-validates.
301
+
302
+ ```javascript
303
+ {
304
+ kind: 'shacl',
305
+ ref: { uri: 'file:///shapes/auto-fix.ttl' },
306
+ enforcementMode: 'repair',
307
+ repairConstruct: `
308
+ CONSTRUCT {
309
+ ?violation ex:repaired true .
310
+ ?entity ex:status ex:Repaired .
311
+ }
312
+ WHERE {
313
+ ?violation a sh:ValidationResult .
314
+ ?violation sh:focusNode ?entity
315
+ }
316
+ `
317
+ }
318
+ // Auto-fix violations, then re-validate
319
+ // Result: Clean state via automatic correction
320
+ ```
321
+
322
+ **Use Case**: Data quality, auto-remediation, self-healing systems.
323
+
324
+ ## Receipt Chaining (Priority 1 & 4)
325
+
326
+ Every hook execution produces a deterministic receipt with cryptographic proof:
327
+
328
+ ```javascript
329
+ {
330
+ receiptHash: 'a3f7...', // BLAKE3(entire receipt)
331
+ payloadHash: 'b9e2...', // BLAKE3(payload/hook definitions)
332
+ input_hash: 'c4d1...', // BLAKE3(store state before)
333
+ output_hash: 'e7f3...', // BLAKE3(store state after)
334
+ previousReceiptHash: '8f2a...', // Links to prior operation
335
+ timestamp: 1234567890000,
336
+ nodeId: 'my-app',
337
+ delta: {
338
+ adds: [{ subject, predicate, object }],
339
+ deletes: [{ subject, predicate, object }]
340
+ },
341
+ hooksExecuted: 3,
342
+ successful: 2,
343
+ failed: 0
344
+ }
345
+ ```
346
+
347
+ **Verify Chain Integrity**:
348
+
349
+ ```javascript
350
+ const receipt1 = await engine.execute(ctx1, hooks1);
351
+ const receipt2 = await engine.execute(
352
+ createContext({
353
+ ...ctx2,
354
+ previousReceiptHash: receipt1.receipt.receiptHash,
355
+ }),
356
+ hooks2
357
+ );
358
+
359
+ // receipt2.receipt.previousReceiptHash === receipt1.receipt.receiptHash ✅
360
+ // Proves immutable chain of operations
361
+ ```
362
+
363
+ ## CLI Integration
364
+
365
+ All 6 priorities exposed via `@unrdf/cli`:
366
+
367
+ ```bash
368
+ # List all condition kinds and effects
369
+ unrdf hooks list-conditions
370
+
371
+ # Execute hooks with receipt chain
372
+ unrdf hooks execute \
373
+ --store data.nq \
374
+ --config hooks.json \
375
+ --show-receipts \
376
+ --output results.json
377
+
378
+ # Validate hook configuration
379
+ unrdf hooks define --config hooks.json --validate
380
+
381
+ # Test single condition
382
+ unrdf hooks evaluate-condition \
383
+ --store data.nq \
384
+ --condition shacl \
385
+ --config '{"ref": {"uri": "file:///shapes/test.ttl"}, "enforcementMode": "block"}'
386
+
387
+ # Display receipt chain verification
388
+ unrdf hooks receipts --file results.json --verify
389
+
390
+ # Generate hooks from policy template
391
+ unrdf hooks template --type fibo --output hooks.json
392
+ ```
393
+
394
+ ## FIBO Case Study
395
+
396
+ Financial regulatory compliance using all 6 priorities.
397
+
398
+ See: `examples/fibo-jtbd-governance.mjs`
399
+
400
+ **5 Jobs-to-Be-Done**:
401
+
402
+ 1. **Verify Regulatory Compliance** - SHACL validation + SPARQL construction
403
+ 2. **Assess Counterparty Risk** - N3 forward-chaining inference
404
+ 3. **Manage Liquidity Positions** - Datalog logic programming
405
+ 4. **Maintain Audit Trail** - Receipt chaining with BLAKE3
406
+ 5. **Auto-Repair Violations** - SHACL repair mode with CONSTRUCT
407
+
408
+ Run example:
409
+
410
+ ```bash
411
+ node examples/fibo-jtbd-governance.mjs
412
+ ```
413
+
414
+ ## AtomVM Integration
415
+
416
+ Execute hooks from Erlang/BEAM processes via bridge.
417
+
418
+ See: `examples/atomvm-fibo-hooks-demo.mjs`
419
+
420
+ ```javascript
421
+ import { HooksBridge } from '@unrdf/hooks/atomvm';
422
+
423
+ const bridge = new HooksBridge(store);
424
+
425
+ // From Erlang: register hook
426
+ const hookId = await bridge.registerHook({
427
+ name: 'erlang-compliance',
428
+ condition: { kind: 'shacl', ref: { uri: '...' } },
429
+ effects: [{ kind: 'sparql-construct', query: '...' }],
430
+ });
431
+
432
+ // From Erlang: evaluate condition
433
+ const result = await bridge.evaluateCondition({
434
+ kind: 'datalog',
435
+ facts: ['user(alice)'],
436
+ rules: ['allowed(X) :- user(X)'],
437
+ goal: 'allowed(alice)',
438
+ });
439
+
440
+ // Full workflow with receipt
441
+ const receipt = await bridge.executeHooks(context, [hook]);
442
+ ```
443
+
444
+ ## Performance Characteristics
445
+
446
+ | Operation | Latency | Notes |
447
+ | ------------------- | -------- | ---------------------------------- |
448
+ | Receipt Creation | <1ms | BLAKE3 hashing |
449
+ | SPARQL ASK | 1-5ms | Depends on query complexity |
450
+ | SPARQL SELECT | 2-8ms | Result binding overhead |
451
+ | SHACL Validation | 5-15ms | Shape size dependent |
452
+ | N3 Inference | 10-100ms | Rule complexity & triple count |
453
+ | Datalog Goal | 1-30ms | Fixpoint iterations |
454
+ | Full Hook Execution | <150ms | All conditions + effects + receipt |
455
+
456
+ ## Architecture
457
+
458
+ ```
459
+ ┌─────────────────────────────────────────────────────────┐
460
+ │ User Application / CLI (@unrdf/cli) │
461
+ └─────────────────────────────────────────────────────────┘
462
+
463
+ ┌─────────────────────────────────────────────────────────┐
464
+ │ KnowledgeHookEngine │
465
+ │ ├─ Register hooks (6 priorities) │
466
+ │ ├─ Evaluate 9 condition kinds │
467
+ │ ├─ Execute effects (SPARQL/Function) │
468
+ │ ├─ SHACL enforcement (block/annotate/repair) │
469
+ │ ├─ Track receipts (BLAKE3 chaining) │
470
+ │ └─ Manage deltas (adds/deletes) │
471
+ └─────────────────────────────────────────────────────────┘
472
+ ↓ ↓ ↓
473
+ ┌─────────┐ ┌───────────┐ ┌──────────────┐
474
+ │ SPARQL │ │ SHACL │ │ Condition │
475
+ │ Engine │ │ Validator │ │ Evaluator │
476
+ │(ASK/SEL)│ │ (3 modes) │ │(N3/Datalog) │
477
+ └─────────┘ └───────────┘ └──────────────┘
478
+ ↓ ↓ ↓
479
+ └────────────────────┬────────────────────┘
480
+
481
+ ┌──────────────────────┐
482
+ │ @unrdf/oxigraph │
483
+ │ (RDF Store + SPARQL) │
484
+ └──────────────────────┘
485
+
486
+ ┌──────────────────────┐
487
+ │ v6-core Receipt │
488
+ │ (BLAKE3 Hashing + │
489
+ │ Deterministic Chain)│
490
+ └──────────────────────┘
491
+ ```
65
492
 
66
493
  ## Documentation
67
494
 
68
- - **[API Reference](./docs/API.md)** - Complete API documentation
69
- - **[User Guide](./docs/GUIDE.md)** - How to use hooks
70
- - **[Examples](./examples/)** - Code examples
71
- - **[Contributing](./docs/CONTRIBUTING.md)** - How to contribute
495
+ - **[EXAMPLES.md](./EXAMPLES.md)** - All 9 condition kinds + effects + FIBO + AtomVM
496
+ - **[API-REFERENCE.md](./API-REFERENCE.md)** - Complete Zod schemas and API
497
+ - **[ARCHITECTURE.md](./ARCHITECTURE.md)** - Design decisions and data flows
498
+ - **[DEPLOYMENT.md](./DEPLOYMENT.md)** - Production checklist and monitoring
499
+
500
+ ## Source Examples
501
+
502
+ Learn by example following the 80/20 principle:
503
+
504
+ - **[basic.mjs](./examples/basic.mjs)** - Minimal hook definition and execution (5 min)
505
+ - **[knowledge-hook-manager-usage.mjs](./examples/knowledge-hook-manager-usage.mjs)** - Manager API (10 min)
506
+ - **[validate-hooks.mjs](./examples/validate-hooks.mjs)** - Hook validation and debugging (15 min)
507
+
508
+ ## Testing
509
+
510
+ ```bash
511
+ # Full test suite
512
+ pnpm test
513
+
514
+ # Hooks-specific tests
515
+ pnpm test hooks.test.mjs
516
+
517
+ # Watch mode
518
+ pnpm test:watch
519
+
520
+ # Coverage
521
+ pnpm test --coverage
522
+
523
+ # Benchmarks
524
+ pnpm benchmark
525
+ ```
526
+
527
+ ## API Quick Reference
528
+
529
+ ### KnowledgeHookEngine
530
+
531
+ ```javascript
532
+ class KnowledgeHookEngine {
533
+ // Register a hook with 6 priorities
534
+ registerHook(hook: KnowledgeHook): string;
535
+
536
+ // Evaluate any of 9 condition kinds
537
+ async evaluateCondition(
538
+ condition: Condition
539
+ ): Promise<boolean>;
540
+
541
+ // Execute hooks with receipt chaining
542
+ async execute(
543
+ context: ExecutionContext,
544
+ hooks: KnowledgeHook[]
545
+ ): Promise<ExecutionResult>;
546
+
547
+ // Get receipt chain (BLAKE3 linked)
548
+ getReceiptChain(): Receipt[];
549
+ }
550
+ ```
551
+
552
+ ### Hook Definition (Zod)
72
553
 
73
- ## Depends On
554
+ ```javascript
555
+ const KnowledgeHook = {
556
+ name: string; // Hook identifier
557
+ condition: Condition; // 9 kinds
558
+ effects: Effect[]; // Transformations
559
+ metadata?: Record<string, any>;
560
+ }
561
+ ```
562
+
563
+ See [API-REFERENCE.md](./API-REFERENCE.md) for complete schema.
564
+
565
+ ## Contributing
566
+
567
+ See [CONTRIBUTING.md](./docs/CONTRIBUTING.md) for development guidelines.
74
568
 
75
- - `@unrdf/core` - RDF substrate
569
+ All code follows:
76
570
 
77
- ## VOC Usage
571
+ - 100% ESM (.mjs)
572
+ - JSDoc documentation
573
+ - Zod validation
574
+ - <500 lines per file
575
+ - 80%+ test coverage
78
576
 
79
- - VOC-1: Autonomous Knowledge Agent (policy enforcement)
80
- - VOC-3: ML Agent (apply learned patterns)
81
- - VOC-4: Audit Agent (compliance monitoring)
82
- - VOC-5: Data Engineer (validation during ingestion)
577
+ ## Key Files
578
+
579
+ - **src/hooks/knowledge-hook-engine.mjs** - Core executor (6 priorities)
580
+ - **src/hooks/condition-evaluator.mjs** - 9 condition kinds
581
+ - **src/hooks/validate.mjs** - SHACL validation (3 modes)
582
+ - **src/hooks/schemas.mjs** - Complete Zod schemas
583
+ - **test/comprehensive-hook-types.test.mjs** - Full test suite
83
584
 
84
585
  ## License
85
586
 
86
- MIT
587
+ MIT — see [LICENSE](./LICENSE) for full text.
588
+
589
+ ### Third-Party Dependencies
590
+
591
+ This package depends on the following notable third-party libraries:
592
+
593
+ | Dependency | License | Purpose |
594
+ | ---------------------------------------------------------- | ------------ | ------------------------------------------------------------ |
595
+ | [eyereasoner](https://github.com/eyereasoner/eye-js) | MIT | N3 forward-chaining inference via EYE reasoner (WebAssembly) |
596
+ | [swipl-wasm](https://github.com/nickmcdowall/swipl-wasm) | BSD-2-Clause | SWI-Prolog runtime bundled by eyereasoner |
597
+ | [@noble/hashes](https://github.com/paulmillr/noble-hashes) | MIT | BLAKE3 cryptographic hashing for receipt chains |
598
+
599
+ All dependencies use permissive open-source licenses compatible with MIT.