@ai-pip/core 0.2.0 → 0.4.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 (133) hide show
  1. package/CHANGELOG.md +106 -3
  2. package/README.md +52 -951
  3. package/dist/AAL/constants.d.ts +15 -0
  4. package/dist/AAL/constants.d.ts.map +1 -0
  5. package/dist/AAL/constants.js +20 -0
  6. package/dist/AAL/constants.js.map +1 -0
  7. package/dist/AAL/index.d.ts +5 -4
  8. package/dist/AAL/index.d.ts.map +1 -1
  9. package/dist/AAL/index.js +4 -2
  10. package/dist/AAL/index.js.map +1 -1
  11. package/dist/AAL/process/applyRemovalPlan.d.ts +23 -0
  12. package/dist/AAL/process/applyRemovalPlan.d.ts.map +1 -0
  13. package/dist/AAL/process/applyRemovalPlan.js +157 -0
  14. package/dist/AAL/process/applyRemovalPlan.js.map +1 -0
  15. package/dist/AAL/process/buildDecisionReason.d.ts.map +1 -1
  16. package/dist/AAL/process/buildDecisionReason.js +24 -4
  17. package/dist/AAL/process/buildDecisionReason.js.map +1 -1
  18. package/dist/AAL/process/buildRemediationPlan.d.ts +22 -0
  19. package/dist/AAL/process/buildRemediationPlan.d.ts.map +1 -0
  20. package/dist/AAL/process/buildRemediationPlan.js +81 -0
  21. package/dist/AAL/process/buildRemediationPlan.js.map +1 -0
  22. package/dist/AAL/process/buildRemovalPlan.d.ts +27 -9
  23. package/dist/AAL/process/buildRemovalPlan.d.ts.map +1 -1
  24. package/dist/AAL/process/buildRemovalPlan.js +95 -29
  25. package/dist/AAL/process/buildRemovalPlan.js.map +1 -1
  26. package/dist/AAL/process/index.d.ts +2 -2
  27. package/dist/AAL/process/index.d.ts.map +1 -1
  28. package/dist/AAL/process/index.js +2 -1
  29. package/dist/AAL/process/index.js.map +1 -1
  30. package/dist/AAL/process/resolveAgentAction.d.ts.map +1 -1
  31. package/dist/AAL/process/resolveAgentAction.js +13 -0
  32. package/dist/AAL/process/resolveAgentAction.js.map +1 -1
  33. package/dist/AAL/process/validatePolicy.d.ts +20 -0
  34. package/dist/AAL/process/validatePolicy.d.ts.map +1 -0
  35. package/dist/AAL/process/validatePolicy.js +40 -0
  36. package/dist/AAL/process/validatePolicy.js.map +1 -0
  37. package/dist/AAL/types.d.ts +18 -31
  38. package/dist/AAL/types.d.ts.map +1 -1
  39. package/dist/index.d.ts +9 -9
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +6 -6
  42. package/dist/index.js.map +1 -1
  43. package/dist/isl/detect/detect.d.ts +39 -0
  44. package/dist/isl/detect/detect.d.ts.map +1 -0
  45. package/dist/isl/detect/detect.js +369 -0
  46. package/dist/isl/detect/detect.js.map +1 -0
  47. package/dist/isl/detect/index.d.ts +6 -0
  48. package/dist/isl/detect/index.d.ts.map +1 -0
  49. package/dist/isl/detect/index.js +5 -0
  50. package/dist/isl/detect/index.js.map +1 -0
  51. package/dist/isl/index.d.ts +8 -1
  52. package/dist/isl/index.d.ts.map +1 -1
  53. package/dist/isl/index.js +5 -0
  54. package/dist/isl/index.js.map +1 -1
  55. package/dist/isl/process/emitSignal.d.ts +19 -10
  56. package/dist/isl/process/emitSignal.d.ts.map +1 -1
  57. package/dist/isl/process/emitSignal.js +25 -23
  58. package/dist/isl/process/emitSignal.js.map +1 -1
  59. package/dist/isl/process/index.d.ts +1 -0
  60. package/dist/isl/process/index.d.ts.map +1 -1
  61. package/dist/isl/riskScore/calculators.d.ts +19 -0
  62. package/dist/isl/riskScore/calculators.d.ts.map +1 -0
  63. package/dist/isl/riskScore/calculators.js +50 -0
  64. package/dist/isl/riskScore/calculators.js.map +1 -0
  65. package/dist/isl/riskScore/index.d.ts +14 -0
  66. package/dist/isl/riskScore/index.d.ts.map +1 -0
  67. package/dist/isl/riskScore/index.js +26 -0
  68. package/dist/isl/riskScore/index.js.map +1 -0
  69. package/dist/isl/riskScore/types.d.ts +20 -0
  70. package/dist/isl/riskScore/types.d.ts.map +1 -0
  71. package/dist/isl/riskScore/types.js +12 -0
  72. package/dist/isl/riskScore/types.js.map +1 -0
  73. package/dist/isl/sanitize.d.ts +8 -1
  74. package/dist/isl/sanitize.d.ts.map +1 -1
  75. package/dist/isl/sanitize.js +13 -5
  76. package/dist/isl/sanitize.js.map +1 -1
  77. package/dist/isl/signals.d.ts +16 -1
  78. package/dist/isl/signals.d.ts.map +1 -1
  79. package/dist/isl/signals.js +4 -2
  80. package/dist/isl/signals.js.map +1 -1
  81. package/dist/isl/value-objects/Pattern.d.ts +21 -0
  82. package/dist/isl/value-objects/Pattern.d.ts.map +1 -1
  83. package/dist/isl/value-objects/Pattern.js +36 -0
  84. package/dist/isl/value-objects/Pattern.js.map +1 -1
  85. package/dist/isl/value-objects/index.d.ts +2 -2
  86. package/dist/isl/value-objects/index.d.ts.map +1 -1
  87. package/dist/isl/value-objects/index.js +1 -1
  88. package/dist/isl/value-objects/index.js.map +1 -1
  89. package/dist/shared/audit.d.ts +126 -28
  90. package/dist/shared/audit.d.ts.map +1 -1
  91. package/dist/shared/audit.js +322 -44
  92. package/dist/shared/audit.js.map +1 -1
  93. package/dist/shared/envelope/envelope.d.ts +23 -0
  94. package/dist/shared/envelope/envelope.d.ts.map +1 -0
  95. package/dist/shared/envelope/envelope.js +58 -0
  96. package/dist/shared/envelope/envelope.js.map +1 -0
  97. package/dist/shared/envelope/exceptions/EnvelopeError.d.ts +8 -0
  98. package/dist/shared/envelope/exceptions/EnvelopeError.d.ts.map +1 -0
  99. package/dist/shared/envelope/exceptions/EnvelopeError.js +13 -0
  100. package/dist/shared/envelope/exceptions/EnvelopeError.js.map +1 -0
  101. package/dist/shared/envelope/exceptions/index.d.ts +2 -0
  102. package/dist/shared/envelope/exceptions/index.d.ts.map +1 -0
  103. package/dist/shared/envelope/exceptions/index.js +2 -0
  104. package/dist/shared/envelope/exceptions/index.js.map +1 -0
  105. package/dist/shared/envelope/index.d.ts +18 -0
  106. package/dist/shared/envelope/index.d.ts.map +1 -0
  107. package/dist/shared/envelope/index.js +15 -0
  108. package/dist/shared/envelope/index.js.map +1 -0
  109. package/dist/shared/envelope/types.d.ts +45 -0
  110. package/dist/shared/envelope/types.d.ts.map +1 -0
  111. package/dist/shared/envelope/types.js +10 -0
  112. package/dist/shared/envelope/types.js.map +1 -0
  113. package/dist/shared/envelope/value-objects/Metadata.d.ts +27 -0
  114. package/dist/shared/envelope/value-objects/Metadata.d.ts.map +1 -0
  115. package/dist/shared/envelope/value-objects/Metadata.js +57 -0
  116. package/dist/shared/envelope/value-objects/Metadata.js.map +1 -0
  117. package/dist/shared/envelope/value-objects/Nonce.d.ts +26 -0
  118. package/dist/shared/envelope/value-objects/Nonce.d.ts.map +1 -0
  119. package/dist/shared/envelope/value-objects/Nonce.js +38 -0
  120. package/dist/shared/envelope/value-objects/Nonce.js.map +1 -0
  121. package/dist/shared/envelope/value-objects/Signature.d.ts +28 -0
  122. package/dist/shared/envelope/value-objects/Signature.d.ts.map +1 -0
  123. package/dist/shared/envelope/value-objects/Signature.js +50 -0
  124. package/dist/shared/envelope/value-objects/Signature.js.map +1 -0
  125. package/dist/shared/envelope/value-objects/index.d.ts +9 -0
  126. package/dist/shared/envelope/value-objects/index.d.ts.map +1 -0
  127. package/dist/shared/envelope/value-objects/index.js +7 -0
  128. package/dist/shared/envelope/value-objects/index.js.map +1 -0
  129. package/dist/shared/index.d.ts +2 -2
  130. package/dist/shared/index.d.ts.map +1 -1
  131. package/dist/shared/index.js +1 -1
  132. package/dist/shared/index.js.map +1 -1
  133. package/package.json +11 -6
@@ -2,37 +2,232 @@
2
2
  * AI-PIP Audit utilities - Pure functions for ordered, human-readable audit output
3
3
  *
4
4
  * @remarks
5
- * These functions format layer results and signals into consistent, pretty-printed
6
- * strings or structured data for auditing, logging, and compliance. They are
7
- * layer-agnostic (accept minimal shapes) and do not depend on layer internals.
5
+ * These functions format layer results and signals so that the **data** exposed
6
+ * is self-explanatory for an external auditor: each block includes a short
7
+ * explanation of what it represents, human-readable labels (e.g. TC/STC/UC,
8
+ * ALLOW/WARN/BLOCK), and origin/traceability. Visual styling is not part of core;
9
+ * scripts or SDK can consume this text for richer presentation.
10
+ *
11
+ * Supports:
12
+ * - Text report (formatPipelineAudit, formatPipelineAuditFull)
13
+ * - JSON report for logs/machine consumption (buildFullAuditPayload, formatPipelineAuditAsJson)
14
+ * - Run identifier (createAuditRunId) and generatedAt for correlation
15
+ * - Compact log entry (buildAuditLogEntry) for one-line logging
8
16
  */
17
+ /** Trust level legend for audit output (human-readable) */
18
+ const TRUST_LEGEND = {
19
+ TC: 'Trusted Content',
20
+ STC: 'Semi-Trusted Content',
21
+ UC: 'Untrusted Content'
22
+ };
23
+ /** Action legend for audit output */
24
+ const ACTION_LEGEND = {
25
+ ALLOW: 'Allow (risk below warn threshold)',
26
+ WARN: 'Warn (risk above warn, below block)',
27
+ BLOCK: 'Block (risk above block threshold)'
28
+ };
9
29
  const SEP = ' ';
10
30
  const BORDER = '---';
11
31
  /**
12
- * Formats lineage entries for pretty audit output
32
+ * Creates a unique run identifier for audit correlation (e.g. logs, multiple reports).
33
+ * Uses crypto.randomUUID() when available, otherwise a time-based id.
34
+ */
35
+ export function createAuditRunId() {
36
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
37
+ return crypto.randomUUID();
38
+ }
39
+ return `audit-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
40
+ }
41
+ function ensureRunInfo(options) {
42
+ const generatedAt = options?.generatedAt ?? Date.now();
43
+ return {
44
+ runId: options?.runId ?? createAuditRunId(),
45
+ generatedAt,
46
+ generatedAtIso: new Date(generatedAt).toISOString()
47
+ };
48
+ }
49
+ /**
50
+ * Builds a compact audit entry for one-line logging (e.g. logger.info(JSON.stringify(entry))).
51
+ * Lineage is not included; use buildFullAuditPayload for full traceability.
52
+ */
53
+ export function buildAuditLogEntry(signal, reason, options) {
54
+ const run = ensureRunInfo(options);
55
+ return {
56
+ runId: run.runId,
57
+ generatedAt: run.generatedAt,
58
+ generatedAtIso: run.generatedAtIso,
59
+ action: reason.action,
60
+ riskScore: reason.riskScore,
61
+ hasThreats: reason.hasThreats,
62
+ detectionCount: reason.detectionCount
63
+ };
64
+ }
65
+ function lineageToJson(lineage) {
66
+ return lineage.map((e) => ({ step: e.step, timestamp: e.timestamp }));
67
+ }
68
+ function buildCslSection(result) {
69
+ return {
70
+ layer: 'CSL',
71
+ segmentCount: result.segments.length,
72
+ segments: result.segments.map((seg) => ({
73
+ id: seg.id,
74
+ trust: seg.trust.value,
75
+ contentLength: seg.content.length
76
+ })),
77
+ lineage: lineageToJson(result.lineage),
78
+ ...(typeof result.processingTimeMs === 'number' && { processingTimeMs: result.processingTimeMs })
79
+ };
80
+ }
81
+ function buildIslSection(result) {
82
+ const meta = result.metadata;
83
+ return {
84
+ layer: 'ISL',
85
+ totalSegments: meta.totalSegments,
86
+ sanitizedSegments: meta.sanitizedSegments,
87
+ segments: result.segments.map((seg) => {
88
+ const pi = seg.piDetection;
89
+ const detections = pi?.detections;
90
+ const detectionTypes = detections?.length ? summarizeDetectionTypes(detections) : 'none';
91
+ return {
92
+ id: seg.id,
93
+ trust: seg.trust.value,
94
+ sanitizationLevel: seg.sanitizationLevel,
95
+ originalLength: seg.originalContent.length,
96
+ sanitizedLength: seg.sanitizedContent.length,
97
+ detections: detections?.length ?? 0,
98
+ detectionTypes
99
+ };
100
+ }),
101
+ lineage: lineageToJson(result.lineage),
102
+ ...(typeof meta.processingTimeMs === 'number' && { processingTimeMs: meta.processingTimeMs })
103
+ };
104
+ }
105
+ function buildIslSignalSection(signal) {
106
+ const pd = signal.piDetection;
107
+ return {
108
+ layer: 'ISL_SIGNAL',
109
+ riskScore: signal.riskScore,
110
+ hasThreats: signal.hasThreats,
111
+ timestamp: signal.timestamp,
112
+ timestampIso: new Date(signal.timestamp).toISOString(),
113
+ piDetection: {
114
+ detected: pd.detected,
115
+ score: pd.score,
116
+ detectionCount: pd.detections.length,
117
+ detectionTypes: summarizeDetectionTypes(pd.detections),
118
+ ...(pd.patterns && pd.patterns.length > 0 && { patterns: [...pd.patterns] })
119
+ },
120
+ ...(signal.metadata?.strategy && { strategy: signal.metadata.strategy })
121
+ };
122
+ }
123
+ function buildAalSection(reason, remediationPlan) {
124
+ const section = {
125
+ layer: 'AAL',
126
+ action: reason.action,
127
+ reason: reason.reason,
128
+ riskScore: reason.riskScore,
129
+ threshold: reason.threshold,
130
+ hasThreats: reason.hasThreats,
131
+ detectionCount: reason.detectionCount
132
+ };
133
+ if (remediationPlan != null) {
134
+ section.remediationStrategy = remediationPlan.strategy;
135
+ section.remediationGoals = remediationPlan.goals;
136
+ section.remediationConstraints = remediationPlan.constraints;
137
+ section.targetSegments = remediationPlan.targetSegments;
138
+ section.needsRemediation = remediationPlan.needsRemediation;
139
+ }
140
+ return section;
141
+ }
142
+ function buildCpeSection(result) {
143
+ const env = result.envelope;
144
+ return {
145
+ layer: 'CPE',
146
+ nonce: env.metadata.nonce,
147
+ timestamp: env.metadata.timestamp,
148
+ timestampIso: new Date(env.metadata.timestamp).toISOString(),
149
+ signatureAlgorithm: env.signature.algorithm,
150
+ lineage: lineageToJson(env.lineage),
151
+ ...(typeof env.metadata.protocolVersion === 'string' && { protocolVersion: env.metadata.protocolVersion }),
152
+ ...(typeof result.processingTimeMs === 'number' && { processingTimeMs: result.processingTimeMs })
153
+ };
154
+ }
155
+ /**
156
+ * Builds the full pipeline audit payload (JSON-serializable) with run id, timestamp, summary for logs, and section data.
157
+ * Preserves lineage in each section for traceability. Use formatPipelineAuditAsJson to get a JSON string.
158
+ */
159
+ export function buildFullAuditPayload(csl, isl, signal, reason, options) {
160
+ const run = ensureRunInfo(options);
161
+ const remediationPlan = options?.remediationPlan ?? undefined;
162
+ const cpe = options?.cpe;
163
+ const includeCpe = options?.includeCpe === true && cpe != null;
164
+ const payload = {
165
+ runId: run.runId,
166
+ generatedAt: run.generatedAt,
167
+ generatedAtIso: run.generatedAtIso,
168
+ summary: {
169
+ action: reason.action,
170
+ riskScore: reason.riskScore,
171
+ hasThreats: reason.hasThreats,
172
+ detectionCount: reason.detectionCount
173
+ },
174
+ sections: {
175
+ csl: buildCslSection(csl),
176
+ isl: buildIslSection(isl),
177
+ islSignal: buildIslSignalSection(signal),
178
+ aal: buildAalSection(reason, remediationPlan),
179
+ ...(includeCpe && cpe && { cpe: buildCpeSection(cpe) })
180
+ }
181
+ };
182
+ return payload;
183
+ }
184
+ /** Summarizes detection types for audit (e.g. "prompt-injection (2), jailbreak (1)") */
185
+ function summarizeDetectionTypes(detections) {
186
+ if (detections.length === 0)
187
+ return 'none';
188
+ const counts = {};
189
+ for (const d of detections) {
190
+ const t = d.pattern_type ?? 'unknown';
191
+ counts[t] = (counts[t] ?? 0) + 1;
192
+ }
193
+ return Object.entries(counts)
194
+ .sort((a, b) => b[1] - a[1])
195
+ .map(([type, n]) => `${type} (${n})`)
196
+ .join(', ');
197
+ }
198
+ /**
199
+ * Formats lineage entries for audit - chronological traceability
13
200
  *
14
201
  * @param lineage - Array of lineage entries (any layer)
15
- * @returns Formatted string
202
+ * @returns Formatted string with short legend and chronological steps
16
203
  */
17
204
  export function formatLineageForAudit(lineage) {
18
205
  if (lineage.length === 0)
19
- return 'Lineage: (none)';
206
+ return 'Lineage: (none)\n Data: chronological list of processing steps (CSL, ISL, CPE, etc.) with timestamp.';
207
+ const legend = 'Chronological traceability: each entry is a processing step with timestamp.';
20
208
  const lines = lineage.map((e, i) => `${SEP}${i + 1}. [${e.step}] ${new Date(e.timestamp).toISOString()}`);
21
- return ['Lineage:', ...lines].join('\n');
209
+ return ['Lineage:', legend, BORDER, ...lines].join('\n');
22
210
  }
23
211
  /**
24
- * Formats CSL result for audit - ordered and human-readable
212
+ * Formats CSL result for audit - data self-explanatory for external auditor
25
213
  *
26
214
  * @param result - CSL result (or compatible shape)
27
- * @returns Formatted string for auditing
215
+ * @returns Formatted string: what this block is, data origin, trust legend, per-segment data
28
216
  */
29
217
  export function formatCSLForAudit(result) {
218
+ const header = 'Content segmented and classified by trust. Trust levels: TC=Trusted Content, STC=Semi-Trusted Content, UC=Untrusted Content.';
219
+ const origin = 'Data from: CSL segmentation result (input split into segments with trust per segment).';
30
220
  const processingTimeLine = typeof result.processingTimeMs === 'number'
31
221
  ? [`Processing time: ${result.processingTimeMs}ms`]
32
222
  : [];
33
- const segmentLines = result.segments.map((seg, i) => `${SEP}Segment ${i + 1}: id=${seg.id} trust=${seg.trust.value} content_length=${seg.content.length}`);
223
+ const segmentLines = result.segments.map((seg, i) => {
224
+ const trustLabel = TRUST_LEGEND[seg.trust.value] ?? seg.trust.value;
225
+ return `${SEP}Segment ${i + 1}: id=${seg.id} trust=${seg.trust.value} (${trustLabel}) content_length=${seg.content.length}`;
226
+ });
34
227
  const lines = [
35
228
  '[CSL] Context Segmentation Layer',
229
+ header,
230
+ origin,
36
231
  BORDER,
37
232
  `Segments: ${result.segments.length}`,
38
233
  ...processingTimeLine,
@@ -43,20 +238,40 @@ export function formatCSLForAudit(result) {
43
238
  return lines.join('\n');
44
239
  }
45
240
  /**
46
- * Formats ISL result for audit - ordered and human-readable
241
+ * Formats ISL result for audit - data self-explanatory; per-segment detections when present
47
242
  *
48
243
  * @param result - ISL result (or compatible shape)
49
- * @returns Formatted string for auditing
244
+ * @returns Formatted string: what this block is, data origin, per-segment trust/level/length/detections
50
245
  */
51
246
  export function formatISLForAudit(result) {
247
+ const header = 'Content sanitized by ISL; sanitization level per segment (minimal/moderate/aggressive). Per segment: trust, level, length before/after, detections (if any).';
248
+ const origin = 'Data from: ISL sanitization result (each segment may have piDetection with threat detections).';
52
249
  const meta = result.metadata;
53
250
  const processingTimeLine = typeof meta.processingTimeMs === 'number' ? [`Processing time: ${meta.processingTimeMs}ms`] : [];
54
- const segmentLines = result.segments.flatMap((seg, i) => [
55
- `${SEP}Segment ${i + 1}: id=${seg.id} trust=${seg.trust.value} level=${seg.sanitizationLevel}`,
56
- `${SEP} original_length=${seg.originalContent.length} sanitized_length=${seg.sanitizedContent.length}`
57
- ]);
251
+ const segmentLines = result.segments.flatMap((seg, i) => {
252
+ const trustLabel = TRUST_LEGEND[seg.trust.value] ?? seg.trust.value;
253
+ const base = [
254
+ `${SEP}Segment ${i + 1}: id=${seg.id} trust=${seg.trust.value} (${trustLabel}) level=${seg.sanitizationLevel}`,
255
+ `${SEP} original_length=${seg.originalContent.length} sanitized_length=${seg.sanitizedContent.length}`
256
+ ];
257
+ const pi = seg.piDetection;
258
+ const detections = pi?.detections;
259
+ if (detections?.length) {
260
+ const types = summarizeDetectionTypes(detections);
261
+ base.push(`${SEP} detections: ${detections.length} (types: ${types})`);
262
+ }
263
+ else if (pi?.detected) {
264
+ base.push(`${SEP} detections: yes (count/type not available)`);
265
+ }
266
+ else {
267
+ base.push(`${SEP} detections: none`);
268
+ }
269
+ return base;
270
+ });
58
271
  const lines = [
59
272
  '[ISL] Instruction Sanitization Layer',
273
+ header,
274
+ origin,
60
275
  BORDER,
61
276
  `Segments: ${meta.totalSegments} (sanitized: ${meta.sanitizedSegments})`,
62
277
  ...processingTimeLine,
@@ -67,65 +282,77 @@ export function formatISLForAudit(result) {
67
282
  return lines.join('\n');
68
283
  }
69
284
  /**
70
- * Formats ISL signal for audit - ordered and human-readable
285
+ * Formats ISL signal for audit - data self-explanatory; risk score and detection types
71
286
  *
72
287
  * @param signal - ISL signal (or compatible shape)
73
- * @returns Formatted string for auditing
288
+ * @returns Formatted string: what this block is, data origin, risk score (0-1), hasThreats, detection types
74
289
  */
75
290
  export function formatISLSignalForAudit(signal) {
291
+ const header = 'Risk signal for AAL: summarizes threats and global risk. riskScore (0-1, higher = more risk), hasThreats (true if any detections), detections (count and types).';
292
+ const origin = 'Data from: signal emitted by ISL for AAL (external contract; AAL uses this to decide ALLOW/WARN/BLOCK).';
76
293
  const pd = signal.piDetection;
77
- const patternLine = pd.patterns && pd.patterns.length > 0 ? [`${SEP}Patterns: ${pd.patterns.join(', ')}`] : [];
294
+ const detectionTypes = summarizeDetectionTypes(pd.detections);
295
+ const strategyLine = signal.metadata?.strategy ? [`${SEP}Strategy: ${signal.metadata.strategy} (used to compute risk score)`] : [];
296
+ const patternLine = pd.patterns && pd.patterns.length > 0 ? [`${SEP}Patterns matched: ${pd.patterns.join(', ')}`] : [];
78
297
  const lines = [
79
298
  '[ISL Signal] External contract',
299
+ header,
300
+ origin,
80
301
  BORDER,
81
- `Risk score: ${signal.riskScore.toFixed(3)}`,
82
- `Has threats: ${signal.hasThreats}`,
302
+ `Risk score: ${signal.riskScore.toFixed(3)} (0-1, higher = more risk)`,
303
+ `Has threats: ${signal.hasThreats} (true if any detections present)`,
83
304
  `Timestamp: ${new Date(signal.timestamp).toISOString()}`,
84
- `Detections: ${pd.detections.length} (score: ${pd.score.toFixed(3)}, detected: ${pd.detected})`,
305
+ `Detections: ${pd.detections.length} (aggregated score: ${pd.score.toFixed(3)}, detected: ${pd.detected})`,
306
+ `Detection types: ${detectionTypes}`,
307
+ ...strategyLine,
85
308
  ...patternLine
86
309
  ];
87
310
  return lines.join('\n');
88
311
  }
89
312
  /**
90
- * Formats AAL decision reason and optional removal plan for audit
313
+ * Formats AAL decision reason and optional remediation plan for audit
91
314
  *
92
315
  * @param reason - Decision reason (or compatible shape)
93
- * @param removalPlan - Optional removal plan (or compatible shape)
94
- * @returns Formatted string for auditing
316
+ * @param remediationPlan - Optional remediation plan (or compatible shape)
317
+ * @returns Formatted string: action (ALLOW/WARN/BLOCK), reason, thresholds, remediation plan
95
318
  */
96
- export function formatAALForAudit(reason, removalPlan) {
97
- const plan = removalPlan ?? undefined;
98
- const removalBlock = plan === undefined
319
+ export function formatAALForAudit(reason, remediationPlan) {
320
+ const header = 'Agent Action Lock decision. Action (ALLOW/WARN/BLOCK), reason in plain language, thresholds used (warn/block), remediation plan (what to do; SDK/AI agent performs cleanup).';
321
+ const origin = 'Data from: AAL decision (resolveAgentAction + buildDecisionReason + optional buildRemediationPlan).';
322
+ const actionLabel = ACTION_LEGEND[reason.action] ?? reason.action;
323
+ const plan = remediationPlan ?? undefined;
324
+ const remediationBlock = plan === undefined
99
325
  ? []
100
326
  : [
101
327
  '',
102
- `Removal enabled: ${plan.removalEnabled}`,
103
- `Should remove: ${plan.shouldRemove}`,
104
- ...(plan.instructionsToRemove.length > 0
105
- ? [
106
- `Instructions to remove: ${plan.instructionsToRemove.length}`,
107
- ...plan.instructionsToRemove.map((inst, i) => `${SEP}${i + 1}. ${inst.type ?? 'unknown'} - ${inst.description ?? inst.pattern ?? ''}`)
108
- ]
109
- : [])
328
+ `Remediation strategy: ${plan.strategy}`,
329
+ `Needs remediation: ${plan.needsRemediation}`,
330
+ `Target segments: ${plan.targetSegments.length} [${plan.targetSegments.slice(0, 5).join(', ')}${plan.targetSegments.length > 5 ? '...' : ''}]`,
331
+ `Goals: ${plan.goals.join(', ')}`,
332
+ `Constraints: ${plan.constraints.join(', ')}`
110
333
  ];
111
334
  const lines = [
112
335
  '[AAL] Agent Action Lock',
336
+ header,
337
+ origin,
113
338
  BORDER,
114
- `Action: ${reason.action}`,
339
+ `Action: ${reason.action} (${actionLabel})`,
115
340
  `Risk score: ${reason.riskScore.toFixed(3)} (threshold: ${reason.threshold.toFixed(3)})`,
116
341
  `Reason: ${reason.reason}`,
117
- `Threats: ${reason.hasThreats} (count: ${reason.detectionCount})`,
118
- ...removalBlock
342
+ `Threats: ${reason.hasThreats} (detection count: ${reason.detectionCount})`,
343
+ ...remediationBlock
119
344
  ];
120
345
  return lines.join('\n');
121
346
  }
122
347
  /**
123
- * Formats CPE result for audit - ordered and human-readable
348
+ * Formats CPE result for audit - data self-explanatory
124
349
  *
125
350
  * @param result - CPE result (or compatible shape)
126
- * @returns Formatted string for auditing
351
+ * @returns Formatted string: what this block is, data origin, nonce, timestamp, signature
127
352
  */
128
353
  export function formatCPEForAudit(result) {
354
+ const header = 'Cryptographic envelope: nonce (unique per request), timestamp, signature (integrity).';
355
+ const origin = 'Data from: CPE envelope result (wraps sanitized content for integrity verification).';
129
356
  const env = result.envelope;
130
357
  const protocolVersionLine = typeof env.metadata.protocolVersion === 'string'
131
358
  ? [`Protocol version: ${env.metadata.protocolVersion}`]
@@ -135,6 +362,8 @@ export function formatCPEForAudit(result) {
135
362
  : [];
136
363
  const lines = [
137
364
  '[CPE] Cryptographic Prompt Envelope',
365
+ header,
366
+ origin,
138
367
  BORDER,
139
368
  `Nonce: ${env.metadata.nonce}`,
140
369
  `Timestamp: ${new Date(env.metadata.timestamp).toISOString()}`,
@@ -149,25 +378,74 @@ export function formatCPEForAudit(result) {
149
378
  /**
150
379
  * Builds a full pipeline audit report (CSL → ISL → CPE) from layer results.
151
380
  * Accepts minimal shapes for flexibility.
381
+ * Use formatPipelineAuditFull when you need ISL Signal and AAL included.
152
382
  *
153
383
  * @param csl - CSL result (or compatible shape)
154
384
  * @param isl - ISL result (or compatible shape)
155
385
  * @param cpe - CPE result (or compatible shape)
156
- * @param options - Optional title and separator
386
+ * @param options - Optional title and separator; use includeSignalAndAAL to add Signal + AAL sections
157
387
  * @returns Single formatted string for full audit
158
388
  */
159
389
  export function formatPipelineAudit(csl, isl, cpe, options) {
160
390
  const sep = options?.sectionSeparator ?? '\n\n';
161
391
  const title = options?.title ?? 'AI-PIP Pipeline Audit';
162
- const parts = [
392
+ const parts = [title, BORDER, formatCSLForAudit(csl), sep, formatISLForAudit(isl)];
393
+ if (options?.includeSignalAndAAL && options.signal != null && options.aalReason != null) {
394
+ parts.push(sep, formatISLSignalForAudit(options.signal), sep, formatAALForAudit(options.aalReason, options.remediationPlan ?? undefined));
395
+ }
396
+ parts.push(sep, formatCPEForAudit(cpe));
397
+ return parts.join('\n');
398
+ }
399
+ /**
400
+ * Full pipeline audit report (CSL → ISL → ISL Signal → AAL → optional CPE) with run id and timestamp.
401
+ * Unites all layers for a single audit view. Lineage is included in each section.
402
+ *
403
+ * @param csl - CSL result
404
+ * @param isl - ISL result
405
+ * @param signal - ISL signal (for AAL)
406
+ * @param aalReason - AAL decision reason
407
+ * @param remediationPlan - Optional remediation plan
408
+ * @param cpe - Optional CPE result (included when includeCpe is true)
409
+ * @param options - runId, generatedAt, includeCpe, title, sectionSeparator
410
+ * @returns Formatted string with header (runId, generatedAt) and all sections
411
+ */
412
+ export function formatPipelineAuditFull(csl, isl, signal, aalReason, remediationPlan, cpe, options) {
413
+ const run = ensureRunInfo(options);
414
+ const sep = options?.sectionSeparator ?? '\n\n';
415
+ const title = options?.title ?? 'AI-PIP Pipeline Audit (full)';
416
+ const includeCpe = options?.includeCpe === true && cpe != null;
417
+ const header = [
163
418
  title,
164
419
  BORDER,
420
+ `Run ID: ${run.runId}`,
421
+ `Generated at: ${run.generatedAtIso}`,
422
+ BORDER
423
+ ].join('\n');
424
+ const parts = [
425
+ header,
426
+ sep,
165
427
  formatCSLForAudit(csl),
166
428
  sep,
167
429
  formatISLForAudit(isl),
168
430
  sep,
169
- formatCPEForAudit(cpe)
431
+ formatISLSignalForAudit(signal),
432
+ sep,
433
+ formatAALForAudit(aalReason, remediationPlan ?? undefined)
170
434
  ];
435
+ if (includeCpe && cpe) {
436
+ parts.push(sep, formatCPEForAudit(cpe));
437
+ }
171
438
  return parts.join('\n');
172
439
  }
440
+ /**
441
+ * Full pipeline audit as JSON string (for logs, SIEM, machine consumption).
442
+ * Preserves lineage in each section. Use buildFullAuditPayload for the raw object.
443
+ *
444
+ * @param options.compact - If true, single-line JSON; otherwise pretty-printed
445
+ * @returns JSON string of the full audit payload
446
+ */
447
+ export function formatPipelineAuditAsJson(csl, isl, signal, reason, options) {
448
+ const payload = buildFullAuditPayload(csl, isl, signal, reason, options);
449
+ return options?.compact === true ? JSON.stringify(payload) : JSON.stringify(payload, null, 2);
450
+ }
173
451
  //# sourceMappingURL=audit.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"audit.js","sourceRoot":"","sources":["../../src/shared/audit.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAyFH,MAAM,GAAG,GAAG,IAAI,CAAA;AAChB,MAAM,MAAM,GAAG,KAAK,CAAA;AAEpB;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAAoC;I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I,CAAC,CAAA;AACzB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CACvC,GAAkB,EAClB,GAAkB,EAClB,MAAqB,EACrB,MAA0B,EAC1B,OAAiH;IAEjH,MAAM,OAAO,GAAG,qBAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAA;IACxE,OAAO,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;AAC/F,CAAC"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * envelope – builds a cryptographic envelope around pipeline result (transversal).
3
+ *
4
+ * @remarks
5
+ * The envelope is a cross-cutting concern: it wraps the result of the pipeline
6
+ * (e.g. ISL result or AAL-cleaned result) with integrity and anti-replay guarantees:
7
+ * - Metadata: timestamp, nonce, protocol version
8
+ * - Signature: HMAC-SHA256 over payload + metadata
9
+ * - Lineage: appends an envelope step to the existing lineage
10
+ *
11
+ * This is not a processing layer; it applies to whatever output the SDK chooses
12
+ * to wrap (after ISL or after AAL). Serialization and verification belong in the SDK.
13
+ *
14
+ * @param islResult - Pipeline result with segments (e.g. ISLResult); must have at least one segment
15
+ * @param secretKey - Secret key for HMAC. Must not be logged, serialized, or exposed. Key rotation
16
+ * and secure storage are the SDK's responsibility (e.g. key id in metadata, multiple keys in verifier).
17
+ * @returns CPEResult with envelope and optional processingTimeMs
18
+ * @throws {EnvelopeError} If input is invalid or generation fails
19
+ */
20
+ import type { ISLResult } from '../../isl/types.js';
21
+ import type { CPEResult } from './types.js';
22
+ export declare function envelope(islResult: ISLResult, secretKey: string): CPEResult;
23
+ //# sourceMappingURL=envelope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../../../src/shared/envelope/envelope.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AACnD,OAAO,KAAK,EAAc,SAAS,EAAE,MAAM,YAAY,CAAA;AAQvD,wBAAgB,QAAQ,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,GAAG,SAAS,CA6D3E"}
@@ -0,0 +1,58 @@
1
+ import { createNonce } from './value-objects/Nonce.js';
2
+ import { createMetadata } from './value-objects/Metadata.js';
3
+ import { createSignature } from './value-objects/Signature.js';
4
+ import { EnvelopeError } from './exceptions/index.js';
5
+ import { addLineageEntries } from '../lineage.js';
6
+ import { createLineageEntry } from '../../csl/value-objects/LineageEntry.js';
7
+ export function envelope(islResult, secretKey) {
8
+ const startTime = Date.now();
9
+ try {
10
+ if (!islResult?.segments?.length) {
11
+ throw new EnvelopeError('ISLResult must contain at least one segment');
12
+ }
13
+ if (!secretKey || secretKey.length === 0) {
14
+ throw new EnvelopeError('Secret key is required for envelope generation');
15
+ }
16
+ const timestamp = Date.now();
17
+ const nonce = createNonce();
18
+ const metadata = createMetadata(timestamp, nonce);
19
+ const payload = {
20
+ segments: islResult.segments.map((segment) => ({
21
+ id: segment.id,
22
+ content: segment.sanitizedContent,
23
+ trust: segment.trust.value,
24
+ sanitizationLevel: segment.sanitizationLevel,
25
+ })),
26
+ };
27
+ const algorithm = 'HMAC-SHA256';
28
+ const signableContent = JSON.stringify({
29
+ payload,
30
+ metadata,
31
+ algorithm,
32
+ });
33
+ const signatureVO = createSignature(signableContent, secretKey);
34
+ const envelopeLineageEntry = createLineageEntry('CPE', timestamp);
35
+ const updatedLineage = addLineageEntries(islResult.lineage, [envelopeLineageEntry]);
36
+ const envelopeResult = {
37
+ payload,
38
+ metadata,
39
+ signature: {
40
+ value: signatureVO.value,
41
+ algorithm: signatureVO.algorithm,
42
+ },
43
+ lineage: updatedLineage,
44
+ };
45
+ const processingTime = Date.now() - startTime;
46
+ return Object.freeze({
47
+ envelope: envelopeResult,
48
+ processingTimeMs: processingTime,
49
+ });
50
+ }
51
+ catch (error) {
52
+ if (error instanceof EnvelopeError) {
53
+ throw error;
54
+ }
55
+ throw new EnvelopeError(`Failed to generate envelope: ${error instanceof Error ? error.message : 'Unknown error'}`, error instanceof Error ? error : undefined);
56
+ }
57
+ }
58
+ //# sourceMappingURL=envelope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../../src/shared/envelope/envelope.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAA;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAA;AAE5E,MAAM,UAAU,QAAQ,CAAC,SAAoB,EAAE,SAAiB;IAC9D,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;IAE5B,IAAI,CAAC;QACH,IAAI,CAAC,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;YACjC,MAAM,IAAI,aAAa,CAAC,6CAA6C,CAAC,CAAA;QACxE,CAAC;QAED,IAAI,CAAC,SAAS,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzC,MAAM,IAAI,aAAa,CAAC,gDAAgD,CAAC,CAAA;QAC3E,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QAC5B,MAAM,KAAK,GAAG,WAAW,EAAE,CAAA;QAC3B,MAAM,QAAQ,GAAG,cAAc,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;QAEjD,MAAM,OAAO,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AC,CAAC,CAAC,eAAe,EAAE,EAC1F,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAC3C,CAAA;IACH,CAAC;AACH,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * EnvelopeError – raised when envelope generation or validation fails.
3
+ */
4
+ export declare class EnvelopeError extends Error {
5
+ readonly cause?: Error | undefined;
6
+ constructor(message: string, cause?: Error | undefined);
7
+ }
8
+ //# sourceMappingURL=EnvelopeError.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EnvelopeError.d.ts","sourceRoot":"","sources":["../../../../src/shared/envelope/exceptions/EnvelopeError.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,aAAc,SAAQ,KAAK;aACO,KAAK,CAAC,EAAE,KAAK;gBAA9C,OAAO,EAAE,MAAM,EAAkB,KAAK,CAAC,EAAE,KAAK,YAAA;CAK3D"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * EnvelopeError – raised when envelope generation or validation fails.
3
+ */
4
+ export class EnvelopeError extends Error {
5
+ cause;
6
+ constructor(message, cause) {
7
+ super(message);
8
+ this.cause = cause;
9
+ this.name = 'EnvelopeError';
10
+ Object.setPrototypeOf(this, EnvelopeError.prototype);
11
+ }
12
+ }
13
+ //# sourceMappingURL=EnvelopeError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EnvelopeError.js","sourceRoot":"","sources":["../../../../src/shared/envelope/exceptions/EnvelopeError.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,OAAO,aAAc,SAAQ,KAAK;IACO;IAA7C,YAAY,OAAe,EAAkB,KAAa;QACxD,KAAK,CAAC,OAAO,CAAC,CAAA;QAD6B,UAAK,GAAL,KAAK,CAAQ;QAExD,IAAI,CAAC,IAAI,GAAG,eAAe,CAAA;QAC3B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,aAAa,CAAC,SAAS,CAAC,CAAA;IACtD,CAAC;CACF"}
@@ -0,0 +1,2 @@
1
+ export { EnvelopeError } from './EnvelopeError.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/shared/envelope/exceptions/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA"}