@ai-pip/core 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +260 -9
  3. package/dist/AAL/index.d.ts +28 -0
  4. package/dist/AAL/index.d.ts.map +1 -0
  5. package/dist/AAL/index.js +28 -0
  6. package/dist/AAL/index.js.map +1 -0
  7. package/dist/AAL/lineage/buildAALLineage.d.ts +22 -0
  8. package/dist/AAL/lineage/buildAALLineage.d.ts.map +1 -0
  9. package/dist/AAL/lineage/buildAALLineage.js +26 -0
  10. package/dist/AAL/lineage/buildAALLineage.js.map +1 -0
  11. package/dist/AAL/lineage/index.d.ts +5 -0
  12. package/dist/AAL/lineage/index.d.ts.map +1 -0
  13. package/dist/AAL/lineage/index.js +5 -0
  14. package/dist/AAL/lineage/index.js.map +1 -0
  15. package/dist/AAL/process/buildDecisionReason.d.ts +36 -0
  16. package/dist/AAL/process/buildDecisionReason.d.ts.map +1 -0
  17. package/dist/AAL/process/buildDecisionReason.js +48 -0
  18. package/dist/AAL/process/buildDecisionReason.js.map +1 -0
  19. package/dist/AAL/process/buildRemovalPlan.d.ts +32 -0
  20. package/dist/AAL/process/buildRemovalPlan.d.ts.map +1 -0
  21. package/dist/AAL/process/buildRemovalPlan.js +50 -0
  22. package/dist/AAL/process/buildRemovalPlan.js.map +1 -0
  23. package/dist/AAL/process/index.d.ts +9 -0
  24. package/dist/AAL/process/index.d.ts.map +1 -0
  25. package/dist/AAL/process/index.js +7 -0
  26. package/dist/AAL/process/index.js.map +1 -0
  27. package/dist/AAL/process/resolveAgentAction.d.ts +31 -0
  28. package/dist/AAL/process/resolveAgentAction.d.ts.map +1 -0
  29. package/dist/AAL/process/resolveAgentAction.js +43 -0
  30. package/dist/AAL/process/resolveAgentAction.js.map +1 -0
  31. package/dist/AAL/types.d.ts +104 -0
  32. package/dist/AAL/types.d.ts.map +1 -0
  33. package/dist/AAL/types.js +2 -0
  34. package/dist/AAL/types.js.map +1 -0
  35. package/dist/{isl → AAL}/value-objects/AnomalyScore.d.ts +2 -1
  36. package/dist/AAL/value-objects/AnomalyScore.d.ts.map +1 -0
  37. package/dist/{isl → AAL}/value-objects/AnomalyScore.js.map +1 -1
  38. package/dist/{isl → AAL}/value-objects/PolicyRule.d.ts.map +1 -1
  39. package/dist/{isl → AAL}/value-objects/PolicyRule.js.map +1 -1
  40. package/dist/AAL/value-objects/index.d.ts +5 -0
  41. package/dist/AAL/value-objects/index.d.ts.map +1 -0
  42. package/dist/AAL/value-objects/index.js +3 -0
  43. package/dist/AAL/value-objects/index.js.map +1 -0
  44. package/dist/index.d.ts +10 -6
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +8 -5
  47. package/dist/index.js.map +1 -1
  48. package/dist/isl/index.d.ts +15 -6
  49. package/dist/isl/index.d.ts.map +1 -1
  50. package/dist/isl/index.js +15 -5
  51. package/dist/isl/index.js.map +1 -1
  52. package/dist/isl/lineage/buildISLLineage.d.ts +22 -0
  53. package/dist/isl/lineage/buildISLLineage.d.ts.map +1 -0
  54. package/dist/isl/lineage/buildISLLineage.js +26 -0
  55. package/dist/isl/lineage/buildISLLineage.js.map +1 -0
  56. package/dist/isl/lineage/index.d.ts +5 -0
  57. package/dist/isl/lineage/index.d.ts.map +1 -0
  58. package/dist/isl/lineage/index.js +5 -0
  59. package/dist/isl/lineage/index.js.map +1 -0
  60. package/dist/isl/process/buildISLResult.d.ts +24 -0
  61. package/dist/isl/process/buildISLResult.d.ts.map +1 -0
  62. package/dist/isl/process/buildISLResult.js +38 -0
  63. package/dist/isl/process/buildISLResult.js.map +1 -0
  64. package/dist/isl/process/emitSignal.d.ts +23 -0
  65. package/dist/isl/process/emitSignal.d.ts.map +1 -0
  66. package/dist/isl/process/emitSignal.js +39 -0
  67. package/dist/isl/process/emitSignal.js.map +1 -0
  68. package/dist/isl/process/index.d.ts +6 -0
  69. package/dist/isl/process/index.d.ts.map +1 -0
  70. package/dist/isl/process/index.js +6 -0
  71. package/dist/isl/process/index.js.map +1 -0
  72. package/dist/isl/sanitize.d.ts +5 -5
  73. package/dist/isl/sanitize.d.ts.map +1 -1
  74. package/dist/isl/sanitize.js +24 -38
  75. package/dist/isl/sanitize.js.map +1 -1
  76. package/dist/isl/signals.d.ts +98 -0
  77. package/dist/isl/signals.d.ts.map +1 -0
  78. package/dist/isl/signals.js +92 -0
  79. package/dist/isl/signals.js.map +1 -0
  80. package/dist/isl/types.d.ts +4 -48
  81. package/dist/isl/types.d.ts.map +1 -1
  82. package/dist/isl/types.js +1 -1
  83. package/dist/isl/value-objects/PiDetection.d.ts +2 -1
  84. package/dist/isl/value-objects/PiDetection.d.ts.map +1 -1
  85. package/dist/isl/value-objects/PiDetectionResult.d.ts +2 -3
  86. package/dist/isl/value-objects/PiDetectionResult.d.ts.map +1 -1
  87. package/dist/isl/value-objects/PiDetectionResult.js +1 -27
  88. package/dist/isl/value-objects/PiDetectionResult.js.map +1 -1
  89. package/dist/isl/value-objects/RiskScore.d.ts +70 -0
  90. package/dist/isl/value-objects/RiskScore.d.ts.map +1 -0
  91. package/dist/isl/value-objects/RiskScore.js +85 -0
  92. package/dist/isl/value-objects/RiskScore.js.map +1 -0
  93. package/dist/isl/value-objects/index.d.ts +2 -2
  94. package/dist/isl/value-objects/index.d.ts.map +1 -1
  95. package/dist/isl/value-objects/index.js +1 -3
  96. package/dist/isl/value-objects/index.js.map +1 -1
  97. package/dist/shared/audit.d.ts +150 -0
  98. package/dist/shared/audit.d.ts.map +1 -0
  99. package/dist/shared/audit.js +173 -0
  100. package/dist/shared/audit.js.map +1 -0
  101. package/dist/shared/index.d.ts +5 -3
  102. package/dist/shared/index.d.ts.map +1 -1
  103. package/dist/shared/index.js +5 -6
  104. package/dist/shared/index.js.map +1 -1
  105. package/dist/shared/types.d.ts +36 -0
  106. package/dist/shared/types.d.ts.map +1 -0
  107. package/dist/shared/types.js +2 -0
  108. package/dist/shared/types.js.map +1 -0
  109. package/package.json +7 -2
  110. package/dist/isl/value-objects/AnomalyScore.d.ts.map +0 -1
  111. /package/dist/{isl → AAL}/value-objects/AnomalyScore.js +0 -0
  112. /package/dist/{isl → AAL}/value-objects/PolicyRule.d.ts +0 -0
  113. /package/dist/{isl → AAL}/value-objects/PolicyRule.js +0 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,52 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ---
9
9
 
10
+ ## [0.2.0] - 2026-01-26
11
+
12
+ ### ♻️ Architectural Refactor - ISL / AAL Separation
13
+
14
+ - Refactored ISL (Instruction Sanitization Layer) to be strictly pure and semantic
15
+ - Removed all decision-making logic from ISL:
16
+ - No Blocking
17
+ - No allowing
18
+ - No warnings
19
+ - No instruction removal
20
+ - ISL is now responsible for:
21
+ - Malicious pattern detection (prompt injection, jailbreak, role hijacking, ...)
22
+ - Risk scoring (RiskScore)
23
+ - Content sanitization
24
+ - Signal emission and lineage preservation
25
+
26
+ - Introduced AAL (Agent Action Lock) as a distinct hybrid layer:
27
+ - Consume ISL signal (RiskScore, detection)
28
+ - Applies configurable policies (ALLOW / WARN / BLOCK)
29
+ - Decides whether to remove malicious instructions
30
+ - Ensures only sanitized content reaches the LLM
31
+ - Designed as a core-defined contract, implemented at the SDK level
32
+
33
+ - **Shared audit utilities**: Pure functions for ordered, human-readable audit output (`formatCSLForAudit`, `formatISLForAudit`, `formatISLSignalForAudit`, `formatAALForAudit`, `formatCPEForAudit`, `formatPipelineAudit`) for compliance and debugging
34
+
35
+ - **Package**: Version set to 0.2.0; AAL export path corrected (`./aal` → `./dist/AAL/`)
36
+
37
+ ### 📚 Documentation
38
+
39
+ - README.md updated to clarify the new ISL / AAL responsibility split; architecture and layer sections in English
40
+ - **Use cases** section added with scenarios (secure chat, policy moderation, audit, DOM/API/SYSTEM sources, lineage)
41
+ - Examples for policy-based moderation (ISL + AAL) and audit report using shared formatters
42
+ - Audit and pretty-print utilities documented (formatCSLForAudit, formatISLForAudit, formatISLSignalForAudit, formatAALForAudit, formatCPEForAudit, formatPipelineAudit)
43
+
44
+ ### 🧪 Testing
45
+
46
+ - Added unit tests for CSL (segment, classify), ISL (signals, emitSignal, buildISLResult, RiskScore), AAL (resolveAgentAction, buildDecisionReason, buildRemovalPlan, buildAALLineage, AnomalyScore, PolicyRule), CPE (envelope), and shared (audit formatters)
47
+ - Integration tests updated for ISL Signal → AAL flow; all test messages in English
48
+ - Coverage target met: **92%+** statements for CSL, ISL, AAL, CPE, and shared layers
49
+
50
+ ### ⚠️ Breaking Semantic Change
51
+
52
+ - Although public APIs remain mostly stable, ISL behavior has changed semantically
53
+ - Consumers must no longer expect ISL to perform actions or remove instructions
54
+ - Decision logic must be handled by AAL or the SDK
55
+
10
56
  ## [0.1.8] - 2026-01-04
11
57
 
12
58
  ### 🐛 Critical Fixes - Origin Classification
@@ -92,6 +138,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
92
138
 
93
139
  ## [0.1.7] - 2026-01-04
94
140
 
141
+ ### ⚠️ DEPRECATED
142
+
143
+ **Deprecation reason**: This version has incorrect source classification that doesn't match the AI-PIP protocol specification. The trust level assignments for sources (UI, DOM, API, SYSTEM) are incorrect, which can lead to improper sanitization levels and security vulnerabilities.
144
+
145
+ **Known issues**:
146
+ - Incorrect source-to-trust-level mapping (UI classified as TC instead of STC, DOM as STC instead of UC, API as UC instead of STC)
147
+ - Inconsistent behavior with AI-PIP protocol specification
148
+ - Tests and documentation don't match actual implementation
149
+ - Potential security risks due to incorrect sanitization levels
150
+
151
+ **Recommendation**: Update to `0.1.8` or higher, which fixes all classification issues and aligns with the AI-PIP protocol specification.
152
+
95
153
  ### 🐛 Critical Fixes
96
154
 
97
155
  #### Type Resolution Fix
@@ -145,6 +203,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
145
203
 
146
204
  ## [0.1.6] - 2025-12-28
147
205
 
206
+ ### ⚠️ DEPRECATED
207
+
208
+ **Deprecation reason**: This version has incorrect source classification that doesn't match the AI-PIP protocol specification. The trust level assignments for sources are incorrect, which can lead to improper sanitization levels and security vulnerabilities.
209
+
210
+ **Known issues**:
211
+ - Incorrect source-to-trust-level mapping
212
+ - Inconsistent behavior with AI-PIP protocol specification
213
+ - Potential security risks due to incorrect sanitization levels
214
+
215
+ **Recommendation**: Update to `0.1.8` or higher, which fixes all classification issues and aligns with the AI-PIP protocol specification.
216
+
148
217
  ### 📚 Documentation Improvements
149
218
  - **Centralized documentation**: Moved all protocol documentation to `ai-pip-docs` repository
150
219
  - **Updated README**: Added comprehensive links to centralized documentation
@@ -158,6 +227,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
158
227
 
159
228
  ## [0.1.5] - 2025-12-28
160
229
 
230
+ ### ⚠️ DEPRECATED
231
+
232
+ **Deprecation reason**: This version has incorrect source classification that doesn't match the AI-PIP protocol specification. The trust level assignments for sources are incorrect, which can lead to improper sanitization levels and security vulnerabilities.
233
+
234
+ **Known issues**:
235
+ - Incorrect source-to-trust-level mapping
236
+ - Inconsistent behavior with AI-PIP protocol specification
237
+ - Potential security risks due to incorrect sanitization levels
238
+
239
+ **Recommendation**: Update to `0.1.8` or higher, which fixes all classification issues and aligns with the AI-PIP protocol specification.
240
+
161
241
  ### 📚 Documentation Improvements
162
242
  - **Updated README**: Added links to whitepaper, roadmap, and complete layer documentation
163
243
  - **Updated Roadmap**: Added SDK-browser in Phase 4, updated Phase 1 status to 100% completed
@@ -176,6 +256,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
176
256
 
177
257
  ## [0.1.3] - 2025-12-28
178
258
 
259
+ ### ⚠️ DEPRECATED
260
+
261
+ **Deprecation reason**: This version has incorrect source classification that doesn't match the AI-PIP protocol specification. The trust level assignments for sources are incorrect, which can lead to improper sanitization levels and security vulnerabilities.
262
+
263
+ **Known issues**:
264
+ - Incorrect source-to-trust-level mapping
265
+ - Inconsistent behavior with AI-PIP protocol specification
266
+ - Potential security risks due to incorrect sanitization levels
267
+
268
+ **Recommendation**: Update to `0.1.8` or higher, which fixes all classification issues and aligns with the AI-PIP protocol specification.
269
+
179
270
  ### ✨ New Features
180
271
  - **JavaScript compilation**: The package now compiles to JavaScript (`dist/`) for better compatibility
181
272
  - **Type declaration files**: `.d.ts` files are generated for full TypeScript support
package/README.md CHANGED
@@ -25,6 +25,9 @@ This package contains the **core** implementation of the protocol, which include
25
25
  - [Complete Example (Layer-Specific Imports)](#complete-example-layer-specific-imports)
26
26
  - [Example with additional functions](#example-with-additional-functions)
27
27
  - [Example: Multi-Layer Lineage and Audit Trail](#example-multi-layer-lineage-and-audit-trail)
28
+ - [Example: ISL Signal and AAL Integration](#example-isl-signal-aal)
29
+ - [Example: Audit and pretty-print utilities](#example-audit-utilities)
30
+ - [Use cases](#use-cases)
28
31
  - [Examples by Content Source](#examples-by-content-source)
29
32
  - [DOM Source (HTML Content)](#example-dom-source-html-content)
30
33
  - [UI Source (User Input)](#example-ui-source-user-input)
@@ -32,6 +35,7 @@ This package contains the **core** implementation of the protocol, which include
32
35
  - [API Source (External Data)](#example-api-source-external-data)
33
36
  - [Documentation](#documentation)
34
37
  - [Testing](#testing)
38
+ - [Coverage](#coverage)
35
39
  - [Development](#development)
36
40
  - [Requirements](#requirements)
37
41
  - [License](#license)
@@ -44,21 +48,73 @@ This package contains the **core** implementation of the protocol, which include
44
48
  <a id="architecture"></a>
45
49
  ## 🏗️ Architecture
46
50
 
47
- The AI-PIP protocol is composed of the following layers:
51
+ The AI-PIP protocol is composed of the following layers with clear separation of responsibilities:
48
52
 
49
53
  ### ✅ Implemented Layers
50
54
 
51
55
  - **CSL (Context Segmentation Layer)**: Segments and classifies content according to its origin
52
- - **ISL (Instruction Sanitization Layer)**: Sanitizes instructions according to trust level
56
+ - **ISL (Instruction Sanitization Layer)**: Detects malicious patterns, scores risk, and sanitizes content. Emits signals (ISLSignal) for other layers to consume.
57
+ - **AAL (Agent Action Lock)**: Hybrid layer that consumes ISL signals and applies configurable policies (ALLOW/WARN/BLOCK). Core-defined contract, SDK-implemented.
53
58
  - **CPE (Cryptographic Prompt Envelope)**: Generates cryptographic envelope with HMAC-SHA256 signature
54
59
 
55
60
  ### 🔧 Shared Features
56
61
 
57
62
  - **Shared**: Shared functions and global incremental lineage (not a layer, but features shared between layers)
58
63
 
64
+ ### 🏛️ Architectural Principles
65
+
66
+ #### Layer Separation and Signals
67
+
68
+ **Fundamental rule**: A layer must never consume another layer's internal "result". It consumes a signal.
69
+
70
+ - **ISLResult**: Internal result of the ISL pipeline (segments, lineage, full metadata)
71
+ - Intended for: debugging, reporter, internal traceability
72
+ - **ISLSignal**: Semantic contract between layers (risk scores, detections, security signals)
73
+ - Intended for: AAL, SDK, Engine
74
+ - Does not expose ISL internals
75
+
76
+ **Processing flow:**
77
+ ```
78
+ ISL.process()
79
+ → ISLResult (internal)
80
+ → ISLSignal (external)
81
+ → AAL consumes ISLSignal (not ISLResult)
82
+ ```
83
+
84
+ #### Layer Organization
85
+
86
+ Each layer follows a consistent structure:
87
+
88
+ ```
89
+ Layer/
90
+ ├─ exceptions/ → what is invalid
91
+ ├─ value-objects/ → what it is
92
+ ├─ process/ → how it transforms
93
+ ├─ lineage/ → what happened
94
+ ├─ types.ts
95
+ └─ index.ts
96
+ ```
97
+
98
+ **Benefits:**
99
+ - ✅ No layer overlap
100
+ - ✅ Clear separation of responsibilities
101
+ - ✅ Core scales better
102
+ - ✅ Clear separation between internals and semantic contracts
103
+
59
104
  ### 📝 Note on AAL and Model Gateway
60
105
 
61
- **AAL (Agent Action Lock)** and **Model Gateway** are SDK components, not part of the semantic core. The semantic core focuses on pure functions and signals, while these layers require operational decisions and side effects that belong to the implementation (SDK).
106
+ **AAL (Agent Action Lock)** is a hybrid layer defined in the semantic core but implemented at the SDK level. The core provides:
107
+ - Value objects (AnomalyScore, AgentPolicy, PolicyRule)
108
+ - Semantic contracts and types
109
+ - Pure functions for decision logic
110
+
111
+ The SDK implements:
112
+ - Operational decision execution
113
+ - Policy enforcement
114
+ - Instruction removal
115
+ - Side effects and state management
116
+
117
+ **Model Gateway** is a pure SDK component for routing and managing AI model interactions.
62
118
 
63
119
  <a id="installation"></a>
64
120
  ## 📦 Installation
@@ -97,8 +153,12 @@ import { segment, classifySource, createTrustLevel } from '@ai-pip/core/csl'
97
153
  import type { CSLResult, CSLSegment, TrustLevel } from '@ai-pip/core/csl'
98
154
 
99
155
  // Import from ISL (Instruction Sanitization Layer)
100
- import { sanitize } from '@ai-pip/core/isl'
101
- import type { ISLResult, ISLSegment } from '@ai-pip/core/isl'
156
+ import { sanitize, createISLSignal } from '@ai-pip/core/isl'
157
+ import type { ISLResult, ISLSegment, ISLSignal } from '@ai-pip/core/isl'
158
+
159
+ // Import from AAL (Agent Action Lock)
160
+ import { createAnomalyScore, resolveAgentAction } from '@ai-pip/core/aal'
161
+ import type { AnomalyScore, AgentPolicy } from '@ai-pip/core/aal'
102
162
 
103
163
  // Import from CPE (Cryptographic Prompt Envelope)
104
164
  import { envelope, createNonce, createMetadata } from '@ai-pip/core/cpe'
@@ -139,7 +199,7 @@ This example demonstrates the complete AI-PIP processing pipeline:
139
199
 
140
200
  1. **CSL (Context Segmentation Layer)**: The `segment()` function takes user input and segments it into semantic chunks. Each segment is classified by its origin (`source: 'UI'`), which determines its trust level. The result contains multiple segments, each with its own trust classification and lineage tracking.
141
201
 
142
- 2. **ISL (Instruction Sanitization Layer)**: The `sanitize()` function processes the segmented content and applies sanitization based on each segment's trust level. Trusted content (TC) receives minimal sanitization, semi-trusted (STC) gets moderate sanitization, and untrusted content (UC) receives aggressive sanitization to remove potential prompt injection attempts.
202
+ 2. **ISL (Instruction Sanitization Layer)**: The `sanitize()` function processes the segmented content and applies sanitization based on each segment's trust level. Trusted content (TC) receives minimal sanitization, semi-trusted (STC) gets moderate sanitization, and untrusted content (UC) receives aggressive sanitization to remove potential prompt injection attempts. ISL also detects malicious patterns and emits signals (ISLSignal) that can be consumed by AAL for policy-based decisions.
143
203
 
144
204
  3. **CPE (Cryptographic Prompt Envelope)**: The `envelope()` function creates a cryptographic wrapper around the sanitized content. It generates a unique nonce, timestamp, and HMAC-SHA256 signature to ensure the integrity and authenticity of the processed prompt. The resulting envelope can be safely sent to an AI model with cryptographic proof that the content hasn't been tampered with.
145
205
 
@@ -529,6 +589,193 @@ const cpeResult = envelope(islResult, 'your-secret-key')
529
589
  - Enhanced pattern matching and anomaly detection
530
590
  - Production-ready implementations with comprehensive security features
531
591
  - and more...
592
+
593
+ ---
594
+
595
+ <a id="example-isl-signal-aal"></a>
596
+ ### Example: ISL Signal and AAL Integration
597
+
598
+ **How signals work:** ISL produces an internal result (`ISLResult`). You call `emitSignal(islResult)` to obtain an `ISLSignal` (risk score, detections, `hasThreats`). AAL consumes only this signal via `resolveAgentAction(islSignal, policy)` and never sees `ISLResult`. Minimal flow:
599
+
600
+ ```typescript
601
+ const islResult = sanitize(cslResult) // ISL internal result
602
+ const islSignal = emitSignal(islResult) // External signal for other layers
603
+ const action = resolveAgentAction(islSignal, policy) // AAL consumes signal → 'ALLOW' | 'WARN' | 'BLOCK'
604
+ ```
605
+
606
+ Full example below demonstrates the signal-based communication between ISL and AAL layers, following the architectural principle that layers should consume signals, not internal results:
607
+
608
+ ```typescript
609
+ import {
610
+ segment,
611
+ sanitize,
612
+ emitSignal,
613
+ resolveAgentAction,
614
+ buildDecisionReason,
615
+ buildRemovalPlan
616
+ } from '@ai-pip/core'
617
+ import type { ISLSignal, AgentPolicy } from '@ai-pip/core'
618
+
619
+ // 1. Segment content (CSL)
620
+ const cslResult = segment({
621
+ content: 'User input with potential injection',
622
+ source: 'UI',
623
+ metadata: {}
624
+ })
625
+
626
+ // 2. Sanitize content (ISL) - produces internal result
627
+ const islResult = sanitize(cslResult)
628
+
629
+ // 3. Emit signal from ISL result - external contract
630
+ const islSignal: ISLSignal = emitSignal(islResult)
631
+
632
+ // 4. Define agent policy
633
+ const policy: AgentPolicy = {
634
+ thresholds: {
635
+ warn: 0.3,
636
+ block: 0.7
637
+ },
638
+ removal: {
639
+ enabled: true
640
+ },
641
+ mode: 'balanced'
642
+ }
643
+
644
+ // 5. AAL consumes ISLSignal (not ISLResult) and resolves action
645
+ const action = resolveAgentAction(islSignal, policy)
646
+ console.log('Agent action:', action) // 'ALLOW', 'WARN', or 'BLOCK'
647
+
648
+ // 6. Build decision reason for audit
649
+ const reason = buildDecisionReason(action, islSignal, policy)
650
+ console.log('Decision reason:', reason.reason)
651
+
652
+ // 7. Build removal plan if threats detected
653
+ const removalPlan = buildRemovalPlan(islSignal, policy)
654
+ if (removalPlan.shouldRemove) {
655
+ console.log(`Removing ${removalPlan.instructionsToRemove.length} instruction(s)`)
656
+ }
657
+ ```
658
+
659
+ **What this example demonstrates:**
660
+
661
+ 1. **Signal-Based Communication**: ISL emits `ISLSignal` (external contract) instead of exposing `ISLResult` (internal). This maintains layer separation.
662
+
663
+ 2. **AAL Decision Making**: AAL consumes the signal and applies configurable policies to determine actions (ALLOW/WARN/BLOCK).
664
+
665
+ 3. **Separation of Concerns**:
666
+ - ISL: Detects threats, scores risk, sanitizes content
667
+ - AAL: Evaluates signals, applies policies, builds removal plans
668
+ - SDK: Executes actions, removes instructions, manages state
669
+
670
+ 4. **Architectural Benefits**:
671
+ - ✅ No layer coupling (AAL doesn't know ISL internals)
672
+ - ✅ Clear contracts between layers
673
+ - ✅ Easy to test and maintain
674
+ - ✅ Scalable architecture
675
+
676
+ **Key Principle**: A layer should never consume the internal "result" of another layer. It consumes a signal.
677
+
678
+ ---
679
+
680
+ <a id="example-audit-utilities"></a>
681
+ ### Example: Audit and pretty-print utilities
682
+
683
+ The core provides pure functions to format layer results and signals for clear, ordered audit output. Use them for logging, compliance, and debugging:
684
+
685
+ ```typescript
686
+ import {
687
+ segment,
688
+ sanitize,
689
+ emitSignal,
690
+ envelope,
691
+ resolveAgentAction,
692
+ buildDecisionReason,
693
+ buildRemovalPlan,
694
+ formatCSLForAudit,
695
+ formatISLForAudit,
696
+ formatISLSignalForAudit,
697
+ formatAALForAudit,
698
+ formatCPEForAudit,
699
+ formatPipelineAudit
700
+ } from '@ai-pip/core'
701
+ import type { AgentPolicy } from '@ai-pip/core'
702
+
703
+ // Run pipeline
704
+ const cslResult = segment({ content: 'User input', source: 'UI', metadata: {} })
705
+ const islResult = sanitize(cslResult)
706
+ const islSignal = emitSignal(islResult)
707
+ const cpeResult = envelope(islResult, 'secret-key')
708
+
709
+ const policy: AgentPolicy = {
710
+ thresholds: { warn: 0.3, block: 0.7 },
711
+ removal: { enabled: true }
712
+ }
713
+ const action = resolveAgentAction(islSignal, policy)
714
+ const reason = buildDecisionReason(action, islSignal, policy)
715
+ const removalPlan = buildRemovalPlan(islSignal, policy)
716
+
717
+ // Pretty-print per layer (ordered, human-readable)
718
+ console.log(formatCSLForAudit(cslResult))
719
+ console.log(formatISLForAudit(islResult))
720
+ console.log(formatISLSignalForAudit(islSignal))
721
+ console.log(formatAALForAudit(reason, removalPlan))
722
+ console.log(formatCPEForAudit(cpeResult))
723
+
724
+ // Full pipeline audit report
725
+ const fullAudit = formatPipelineAudit(cslResult, islResult, cpeResult, {
726
+ title: 'AI-PIP Pipeline Audit',
727
+ sectionSeparator: '\n\n'
728
+ })
729
+ console.log(fullAudit)
730
+ ```
731
+
732
+ **What this example demonstrates:**
733
+
734
+ - **`formatCSLForAudit(result)`**: Formats CSL result (segments, trust, lineage) for audit.
735
+ - **`formatISLForAudit(result)`**: Formats ISL result (segments, sanitization level, metadata, lineage).
736
+ - **`formatISLSignalForAudit(signal)`**: Formats ISL signal (risk score, threats, detections) for audit.
737
+ - **`formatAALForAudit(reason, removalPlan?)`**: Formats AAL decision reason and optional removal plan.
738
+ - **`formatCPEForAudit(result)`**: Formats CPE result (metadata, signature, lineage).
739
+ - **`formatPipelineAudit(csl, isl, cpe, options?)`**: Builds a single full pipeline audit string.
740
+
741
+ All formatters accept minimal shapes (layer-agnostic) so you can pass any compatible object. Output is ordered and consistent for compliance and debugging.
742
+
743
+ <a id="use-cases"></a>
744
+ ### Use cases
745
+
746
+ Typical scenarios where AI-PIP core is used:
747
+
748
+ | Use case | Layers involved | Goal |
749
+ |----------|-----------------|------|
750
+ | **Secure user chat** | CSL → ISL → CPE | Segment UI input, sanitize, wrap in envelope before sending to the model. |
751
+ | **Policy-based moderation** | CSL → ISL → emitSignal → AAL | Get risk signal from ISL, resolve ALLOW/WARN/BLOCK and removal plan from AAL. |
752
+ | **Audit and compliance** | Shared audit formatters | Pretty-print CSL/ISL/AAL/CPE results and full pipeline for logs and reports. |
753
+ | **DOM / scraped content** | CSL (source: DOM) → ISL → CPE | Treat web content as untrusted (UC), apply aggressive sanitization. |
754
+ | **System instructions** | CSL (source: SYSTEM) → ISL → CPE | Trusted content (TC), minimal sanitization. |
755
+ | **Lineage and forensics** | All layers | Use lineage from results and `filterLineageByStep` / `getLastLineageEntry` for tracing. |
756
+
757
+ **Example: policy-based moderation (ISL + AAL)**
758
+
759
+ ```typescript
760
+ const cslResult = segment({ content: userInput, source: 'UI', metadata: {} })
761
+ const islResult = sanitize(cslResult)
762
+ const signal = emitSignal(islResult)
763
+ const action = resolveAgentAction(signal, policy)
764
+ const reason = buildDecisionReason(action, signal, policy)
765
+ const plan = buildRemovalPlan(signal, policy)
766
+ // Use action, reason, and plan in your SDK to enforce policy and optionally remove instructions.
767
+ ```
768
+
769
+ **Example: audit report**
770
+
771
+ ```typescript
772
+ const report = formatPipelineAudit(cslResult, islResult, cpeResult, {
773
+ title: 'Request Audit',
774
+ sectionSeparator: '\n---\n'
775
+ })
776
+ logger.info(report)
777
+ ```
778
+
532
779
  <a id="documentation"></a>
533
780
  ## 📚 Documentation
534
781
 
@@ -545,6 +792,7 @@ All AI-PIP protocol documentation is centralized in the [documentation repositor
545
792
  - **[Core Overview](https://github.com/AI-PIP/ai-pip-docs/blob/main/docs/core/CORE.md)** - Semantic core description
546
793
  - **[CSL (Context Segmentation Layer)](https://github.com/AI-PIP/ai-pip-docs/blob/main/docs/core/layers/CSL.md)** - Context segmentation layer
547
794
  - **[ISL (Instruction Sanitization Layer)](https://github.com/AI-PIP/ai-pip-docs/blob/main/docs/core/layers/ISL.md)** - Instruction sanitization layer
795
+ - **[AAL (Agent Action Lock)](https://github.com/AI-PIP/ai-pip-docs/blob/main/docs/core/layers/AAL.md)** - Agent Action Lock (hybrid layer)
548
796
  - **[CPE (Cryptographic Prompt Envelope)](https://github.com/AI-PIP/ai-pip-docs/blob/main/docs/core/layers/CPE.md)** - Cryptographic prompt envelope
549
797
  - **[Shared](https://github.com/AI-PIP/ai-pip-docs/blob/main/docs/core/layers/shared.md)** - Shared features and lineage
550
798
 
@@ -575,7 +823,9 @@ pnpm test:coverage
575
823
  pnpm test:ui
576
824
  ```
577
825
 
578
- **Current coverage**: 88.5%
826
+ ### Coverage
827
+ - **Current coverage**: 92%+ (CSL, ISL, AAL, CPE, shared)
828
+
579
829
 
580
830
  <a id="development"></a>
581
831
  ## 🔧 Development
@@ -752,5 +1002,6 @@ For complete details and all version history, see [CHANGELOG.md](./CHANGELOG.md)
752
1002
 
753
1003
  ---
754
1004
 
755
- **Current Version**: 0.1.8
756
- **Status**: Phase 1 - Core Layers (100% completed)
1005
+ **Current Version**: 0.2.0
1006
+ **Status**: Phase 1 - Core Layers (100% completed)
1007
+ **Latest**: Architectural refactor with ISL/AAL separation and signal-based communication
@@ -0,0 +1,28 @@
1
+ /**
2
+ * AAL (Agent Action Lock) - Semantic Core
3
+ *
4
+ * @remarks
5
+ * This is the semantic core of AAL. It only contains:
6
+ * - Pure functions (stateless)
7
+ * - Immutable value objects
8
+ * - Types
9
+ * - Decision processing
10
+ *
11
+ * **Architecture:**
12
+ * - Consumes ISLSignal (not ISLResult) to maintain layer separation
13
+ * - Applies configurable policies (ALLOW/WARN/BLOCK)
14
+ * - Builds instruction removal plans
15
+ * - Does not execute actions (that is SDK responsibility)
16
+ *
17
+ * **Does NOT contain:**
18
+ * - Prompt injection detection (goes to ISL)
19
+ * - Stateful services (go to SDK)
20
+ * - Action execution (goes to SDK)
21
+ */
22
+ export { createAnomalyScore, isHighRisk, isLowRisk, isWarnRisk, isRoleProtected, isContextLeakPreventionEnabled, isInstructionImmutable, isIntentBlocked, isScopeSensitive } from './value-objects/index.js';
23
+ export type { AnomalyScore, PolicyRule } from './value-objects/index.js';
24
+ export { resolveAgentAction, resolveAgentActionWithScore, buildDecisionReason, buildRemovalPlan } from './process/index.js';
25
+ export type { DecisionReason, RemovalPlan } from './process/index.js';
26
+ export { buildAALLineage } from './lineage/index.js';
27
+ export type { AnomalyAction, RemovedInstruction, BlockedIntent, SensitiveScope, ProtectedRole, ImmutableInstruction, AgentPolicy, } from './types.js';
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/AAL/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EACH,kBAAkB,EAClB,UAAU,EACV,SAAS,EACT,UAAU,EACV,eAAe,EACf,8BAA8B,EAC9B,sBAAsB,EACtB,eAAe,EACf,gBAAgB,EACnB,MAAM,0BAA0B,CAAA;AAEjC,YAAY,EACR,YAAY,EACZ,UAAU,EACb,MAAM,0BAA0B,CAAA;AAGjC,OAAO,EACH,kBAAkB,EAClB,2BAA2B,EAC3B,mBAAmB,EACnB,gBAAgB,EACnB,MAAM,oBAAoB,CAAA;AAE3B,YAAY,EACR,cAAc,EACd,WAAW,EACd,MAAM,oBAAoB,CAAA;AAG3B,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAGpD,YAAY,EACR,aAAa,EACb,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,aAAa,EACb,oBAAoB,EACpB,WAAW,GACd,MAAM,YAAY,CAAA"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * AAL (Agent Action Lock) - Semantic Core
3
+ *
4
+ * @remarks
5
+ * This is the semantic core of AAL. It only contains:
6
+ * - Pure functions (stateless)
7
+ * - Immutable value objects
8
+ * - Types
9
+ * - Decision processing
10
+ *
11
+ * **Architecture:**
12
+ * - Consumes ISLSignal (not ISLResult) to maintain layer separation
13
+ * - Applies configurable policies (ALLOW/WARN/BLOCK)
14
+ * - Builds instruction removal plans
15
+ * - Does not execute actions (that is SDK responsibility)
16
+ *
17
+ * **Does NOT contain:**
18
+ * - Prompt injection detection (goes to ISL)
19
+ * - Stateful services (go to SDK)
20
+ * - Action execution (goes to SDK)
21
+ */
22
+ // Value objects
23
+ export { createAnomalyScore, isHighRisk, isLowRisk, isWarnRisk, isRoleProtected, isContextLeakPreventionEnabled, isInstructionImmutable, isIntentBlocked, isScopeSensitive } from './value-objects/index.js';
24
+ // Process functions
25
+ export { resolveAgentAction, resolveAgentActionWithScore, buildDecisionReason, buildRemovalPlan } from './process/index.js';
26
+ // Lineage
27
+ export { buildAALLineage } from './lineage/index.js';
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/AAL/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,gBAAgB;AAChB,OAAO,EACH,kBAAkB,EAClB,UAAU,EACV,SAAS,EACT,UAAU,EACV,eAAe,EACf,8BAA8B,EAC9B,sBAAsB,EACtB,eAAe,EACf,gBAAgB,EACnB,MAAM,0BAA0B,CAAA;AAOjC,oBAAoB;AACpB,OAAO,EACH,kBAAkB,EAClB,2BAA2B,EAC3B,mBAAmB,EACnB,gBAAgB,EACnB,MAAM,oBAAoB,CAAA;AAO3B,UAAU;AACV,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * buildAALLineage - Builds AAL lineage
3
+ *
4
+ * @remarks
5
+ * This function builds and updates the AAL-specific lineage,
6
+ * adding decision and action entries for auditing and traceability.
7
+ *
8
+ * **Responsibility:**
9
+ * - Build AAL lineage
10
+ * - Add decision entries
11
+ * - Preserve lineage from previous layers
12
+ */
13
+ import type { LineageEntry } from '../../csl/value-objects/index.js';
14
+ /**
15
+ * Builds AAL lineage by adding a processing entry
16
+ *
17
+ * @param previousLineage - Lineage from previous layers
18
+ * @param timestamp - Processing timestamp (default: Date.now())
19
+ * @returns Updated lineage with AAL entry
20
+ */
21
+ export declare function buildAALLineage(previousLineage: readonly LineageEntry[], timestamp?: number): readonly LineageEntry[];
22
+ //# sourceMappingURL=buildAALLineage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildAALLineage.d.ts","sourceRoot":"","sources":["../../../src/AAL/lineage/buildAALLineage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAA;AAIpE;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,eAAe,EAAE,SAAS,YAAY,EAAE,EACxC,SAAS,GAAE,MAAmB,GAC7B,SAAS,YAAY,EAAE,CAGzB"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * buildAALLineage - Builds AAL lineage
3
+ *
4
+ * @remarks
5
+ * This function builds and updates the AAL-specific lineage,
6
+ * adding decision and action entries for auditing and traceability.
7
+ *
8
+ * **Responsibility:**
9
+ * - Build AAL lineage
10
+ * - Add decision entries
11
+ * - Preserve lineage from previous layers
12
+ */
13
+ import { createLineageEntry } from '../../csl/value-objects/index.js';
14
+ import { addLineageEntry } from '../../shared/lineage.js';
15
+ /**
16
+ * Builds AAL lineage by adding a processing entry
17
+ *
18
+ * @param previousLineage - Lineage from previous layers
19
+ * @param timestamp - Processing timestamp (default: Date.now())
20
+ * @returns Updated lineage with AAL entry
21
+ */
22
+ export function buildAALLineage(previousLineage, timestamp = Date.now()) {
23
+ const aalEntry = createLineageEntry('AAL', timestamp);
24
+ return addLineageEntry(previousLineage, aalEntry);
25
+ }
26
+ //# sourceMappingURL=buildAALLineage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildAALLineage.js","sourceRoot":"","sources":["../../../src/AAL/lineage/buildAALLineage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAA;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAEzD;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,eAAwC,EACxC,YAAoB,IAAI,CAAC,GAAG,EAAE;IAE9B,MAAM,QAAQ,GAAG,kBAAkB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;IACrD,OAAO,eAAe,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAA;AACnD,CAAC"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * AAL Lineage - Lineage construction for AAL
3
+ */
4
+ export { buildAALLineage } from './buildAALLineage.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/AAL/lineage/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * AAL Lineage - Lineage construction for AAL
3
+ */
4
+ export { buildAALLineage } from './buildAALLineage.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/AAL/lineage/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * buildDecisionReason - Builds the reason for an AAL decision
3
+ *
4
+ * @remarks
5
+ * This function builds a human-readable description of why
6
+ * a specific decision was made (ALLOW, WARN, BLOCK).
7
+ *
8
+ * **Responsibility:**
9
+ * - Generate readable decision reasons
10
+ * - Include risk score and threshold information
11
+ * - Facilitate auditing and debugging
12
+ */
13
+ import type { AnomalyAction } from '../types.js';
14
+ import type { ISLSignal } from '../../isl/signals.js';
15
+ import type { AgentPolicy } from '../types.js';
16
+ /**
17
+ * Reason for an AAL decision
18
+ */
19
+ export interface DecisionReason {
20
+ readonly action: AnomalyAction;
21
+ readonly riskScore: number;
22
+ readonly threshold: number;
23
+ readonly reason: string;
24
+ readonly hasThreats: boolean;
25
+ readonly detectionCount: number;
26
+ }
27
+ /**
28
+ * Builds the reason for a decision
29
+ *
30
+ * @param action - Determined action (ALLOW, WARN, BLOCK)
31
+ * @param islSignal - ISL signal that originated the decision
32
+ * @param policy - Applied policy
33
+ * @returns DecisionReason with complete information
34
+ */
35
+ export declare function buildDecisionReason(action: AnomalyAction, islSignal: ISLSignal, policy: AgentPolicy): DecisionReason;
36
+ //# sourceMappingURL=buildDecisionReason.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildDecisionReason.d.ts","sourceRoot":"","sources":["../../../src/AAL/process/buildDecisionReason.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAChD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAA;AACrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAA;IAC9B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAA;IAC5B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;CAChC;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,aAAa,EACrB,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,WAAW,GAClB,cAAc,CA2BhB"}