nexus-agents 2.145.1 → 2.146.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 (31) hide show
  1. package/dist/{chunk-IIGRVRKD.js → chunk-256RUC4U.js} +239 -200
  2. package/dist/{chunk-IIGRVRKD.js.map → chunk-256RUC4U.js.map} +1 -1
  3. package/dist/{chunk-QKWS3REM.js → chunk-45QUEZNS.js} +2 -2
  4. package/dist/{chunk-MFTWFPXS.js → chunk-4XQE5A7P.js} +2 -2
  5. package/dist/{chunk-ZRRL3YB6.js → chunk-I5T7GUM7.js} +4 -194
  6. package/dist/chunk-I5T7GUM7.js.map +1 -0
  7. package/dist/chunk-RCQLUJY3.js +208 -0
  8. package/dist/chunk-RCQLUJY3.js.map +1 -0
  9. package/dist/{chunk-J2KMYVWA.js → chunk-RII4VXHO.js} +34 -1
  10. package/dist/{chunk-J2KMYVWA.js.map → chunk-RII4VXHO.js.map} +1 -1
  11. package/dist/{chunk-SDJLXKZZ.js → chunk-XZ4QHFCD.js} +3 -3
  12. package/dist/{chunk-AREFLH3S.js → chunk-Y4NDNQYU.js} +2 -2
  13. package/dist/cli.js +17 -10
  14. package/dist/cli.js.map +1 -1
  15. package/dist/{consensus-vote-6V3JNRXI.js → consensus-vote-IBT3C5YC.js} +4 -3
  16. package/dist/{improvement-review-K7YYYZCJ.js → improvement-review-WMDMS32T.js} +4 -3
  17. package/dist/index.d.ts +33 -1
  18. package/dist/index.js +19 -17
  19. package/dist/index.js.map +1 -1
  20. package/dist/{issue-triage-44OGWBDA.js → issue-triage-R7DMXIEN.js} +3 -2
  21. package/dist/{setup-command-I3U4QK54.js → setup-command-BALYXSMI.js} +3 -3
  22. package/package.json +1 -1
  23. package/dist/chunk-ZRRL3YB6.js.map +0 -1
  24. /package/dist/{chunk-QKWS3REM.js.map → chunk-45QUEZNS.js.map} +0 -0
  25. /package/dist/{chunk-MFTWFPXS.js.map → chunk-4XQE5A7P.js.map} +0 -0
  26. /package/dist/{chunk-SDJLXKZZ.js.map → chunk-XZ4QHFCD.js.map} +0 -0
  27. /package/dist/{chunk-AREFLH3S.js.map → chunk-Y4NDNQYU.js.map} +0 -0
  28. /package/dist/{consensus-vote-6V3JNRXI.js.map → consensus-vote-IBT3C5YC.js.map} +0 -0
  29. /package/dist/{improvement-review-K7YYYZCJ.js.map → improvement-review-WMDMS32T.js.map} +0 -0
  30. /package/dist/{issue-triage-44OGWBDA.js.map → issue-triage-R7DMXIEN.js.map} +0 -0
  31. /package/dist/{setup-command-I3U4QK54.js.map → setup-command-BALYXSMI.js.map} +0 -0
@@ -0,0 +1,208 @@
1
+ import {
2
+ getTimeProvider
3
+ } from "./chunk-Q4UU2W6L.js";
4
+
5
+ // src/security/audit-trail.ts
6
+ var MAX_EVENTS = 1e4;
7
+ var MAX_STRIPPED_ELEMENTS_PER_EVENT = 20;
8
+ var AuditTrail = class {
9
+ constructor(durableSink) {
10
+ this.durableSink = durableSink;
11
+ }
12
+ durableSink;
13
+ events = [];
14
+ nextId = 1;
15
+ /** Appends an event to the trail. Returns the assigned event ID. */
16
+ append(event) {
17
+ const id = `audit-${String(this.nextId++)}`;
18
+ const fullEvent = {
19
+ ...event,
20
+ id,
21
+ timestamp: getTimeProvider().nowIso()
22
+ };
23
+ this.events.push(fullEvent);
24
+ this.enforceLimit();
25
+ if (this.durableSink !== void 0) {
26
+ try {
27
+ this.durableSink(fullEvent);
28
+ } catch {
29
+ }
30
+ }
31
+ return id;
32
+ }
33
+ /** Queries events matching the given filter. */
34
+ query(filter = {}) {
35
+ let results = this.events;
36
+ if (filter.type !== void 0) {
37
+ results = results.filter((e) => e.type === filter.type);
38
+ }
39
+ if (filter.since !== void 0) {
40
+ results = filterSince(results, filter.since);
41
+ }
42
+ if (filter.until !== void 0) {
43
+ results = filterUntil(results, filter.until);
44
+ }
45
+ if (filter.trustTier !== void 0) {
46
+ results = filterByTrustTier(results, filter.trustTier);
47
+ }
48
+ if (filter.actionType !== void 0) {
49
+ results = filterByActionType(results, filter.actionType);
50
+ }
51
+ if (filter.actor !== void 0) {
52
+ results = filterByActor(results, filter.actor);
53
+ }
54
+ if (filter.violationRule !== void 0) {
55
+ results = filterByViolationRule(results, filter.violationRule);
56
+ }
57
+ const limit = filter.limit ?? results.length;
58
+ return results.slice(-limit);
59
+ }
60
+ /** Returns the total number of events. */
61
+ get size() {
62
+ return this.events.length;
63
+ }
64
+ /** Clears all events. */
65
+ clear() {
66
+ this.events = [];
67
+ }
68
+ /** Enforces MAX_EVENTS bound. */
69
+ enforceLimit() {
70
+ if (this.events.length > MAX_EVENTS) {
71
+ this.events = this.events.slice(-MAX_EVENTS);
72
+ }
73
+ }
74
+ };
75
+ function filterSince(events, since) {
76
+ const sinceTime = new Date(since).getTime();
77
+ return events.filter((e) => new Date(e.timestamp).getTime() >= sinceTime);
78
+ }
79
+ function filterUntil(events, until) {
80
+ const untilTime = new Date(until).getTime();
81
+ return events.filter((e) => new Date(e.timestamp).getTime() <= untilTime);
82
+ }
83
+ function filterByTrustTier(events, tier) {
84
+ return events.filter((e) => {
85
+ if (e.type === "trust_classification") return e.assignedTier === tier;
86
+ if (e.type === "policy_gate") return e.inputTrustTier === tier;
87
+ if (e.type === "reputation") return e.effectiveTier === tier;
88
+ return true;
89
+ });
90
+ }
91
+ function filterByActionType(events, actionType) {
92
+ return events.filter(
93
+ (e) => (e.type === "policy_gate" || e.type === "corroboration") && e.actionType === actionType
94
+ );
95
+ }
96
+ function filterByActor(events, actor) {
97
+ return events.filter(
98
+ (e) => (e.type === "trust_classification" || e.type === "reputation") && e.username === actor
99
+ );
100
+ }
101
+ function filterByViolationRule(events, rule) {
102
+ return events.filter((e) => e.type === "policy_gate" && e.violationRules.includes(rule));
103
+ }
104
+ function emitTrustEvent(trail, data) {
105
+ return trail.append({
106
+ type: "trust_classification",
107
+ component: "trust-classifier",
108
+ ...data
109
+ });
110
+ }
111
+ function emitPolicyEvent(trail, data) {
112
+ return trail.append({
113
+ type: "policy_gate",
114
+ component: "policy-gate",
115
+ ...data
116
+ });
117
+ }
118
+ function emitPipelinePolicyEvent(trail, data) {
119
+ return trail.append({
120
+ type: "policy_gate",
121
+ component: "pipeline-policy-evaluator",
122
+ ...data
123
+ });
124
+ }
125
+ function emitCorroborationEvent(trail, data) {
126
+ return trail.append({
127
+ type: "corroboration",
128
+ component: "corroboration-validator",
129
+ ...data
130
+ });
131
+ }
132
+ function emitReputationEvent(trail, data) {
133
+ return trail.append({
134
+ type: "reputation",
135
+ component: "reputation-model",
136
+ ...data
137
+ });
138
+ }
139
+ function emitSanitizationEvent(trail, data) {
140
+ return trail.append({
141
+ type: "sanitization",
142
+ component: "input-sanitizer",
143
+ ...data
144
+ });
145
+ }
146
+ function emitGraphExecutionEvent(trail, data) {
147
+ return trail.append({
148
+ type: "graph_execution",
149
+ component: "graph-executor",
150
+ ...data
151
+ });
152
+ }
153
+ function emitClawGuardViolation(trail, data) {
154
+ return trail.append({
155
+ type: "clawguard_violation",
156
+ component: "clawguard-audit",
157
+ ...data
158
+ });
159
+ }
160
+ function createGraphAuditBridge(trail) {
161
+ return (event) => {
162
+ const nodeId = typeof event["nodeId"] === "string" ? event["nodeId"] : void 0;
163
+ const stepNumber = typeof event["stepNumber"] === "number" ? event["stepNumber"] : 0;
164
+ emitGraphExecutionEvent(trail, {
165
+ graphEvent: event.type,
166
+ ...nodeId !== void 0 ? { nodeId } : {},
167
+ stepNumber,
168
+ detail: formatGraphEventDetail(event)
169
+ });
170
+ };
171
+ }
172
+ function formatGraphEventDetail(event) {
173
+ switch (event.type) {
174
+ case "node_started":
175
+ return `Node ${String(event["nodeId"])} starting`;
176
+ case "node_completed":
177
+ return `Node ${String(event["nodeId"])} completed in ${String(event["durationMs"])}ms`;
178
+ case "node_error":
179
+ return `Node ${String(event["nodeId"])} failed: ${String(event["error"])}`;
180
+ case "state_updated":
181
+ return `State updated: ${String(event["updatedKeys"])}`;
182
+ case "step_completed":
183
+ return `Step ${String(event["stepNumber"])}: ${String(event["nodesExecuted"])} nodes`;
184
+ case "execution_complete":
185
+ return `Complete: ${String(event["totalSteps"])} steps, ${String(event["durationMs"])}ms`;
186
+ default:
187
+ return event.type;
188
+ }
189
+ }
190
+ function createAuditTrail(durableSink) {
191
+ return new AuditTrail(durableSink);
192
+ }
193
+
194
+ export {
195
+ MAX_STRIPPED_ELEMENTS_PER_EVENT,
196
+ AuditTrail,
197
+ emitTrustEvent,
198
+ emitPolicyEvent,
199
+ emitPipelinePolicyEvent,
200
+ emitCorroborationEvent,
201
+ emitReputationEvent,
202
+ emitSanitizationEvent,
203
+ emitGraphExecutionEvent,
204
+ emitClawGuardViolation,
205
+ createGraphAuditBridge,
206
+ createAuditTrail
207
+ };
208
+ //# sourceMappingURL=chunk-RCQLUJY3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/security/audit-trail.ts"],"sourcesContent":["/**\n * nexus-agents/security - Audit Trail\n *\n * Machine-readable JSON audit events for security pipeline decisions.\n * Every trust classification, policy gate decision, corroboration check,\n * and reputation assessment is recorded as a structured event.\n *\n * Satisfies CLAUDE.md requirement: \"Every action on untrusted input must\n * log: trust tier, sources cited, policy gate decision, stripped content.\"\n *\n * @module security/audit-trail\n * (Source: Issue #832 — Security audit trail)\n */\n\nimport { getTimeProvider } from '../core/index.js';\nimport type { TrustTier } from './trust-types.js';\nimport type { AgentActionType } from './action-schema.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Maximum stored events before oldest are evicted. */\nconst MAX_EVENTS = 10_000;\n\n/**\n * Discriminated union of audit event types.\n * Each event captures a single security pipeline decision.\n */\nexport type AuditEvent =\n | TrustClassificationEvent\n | PolicyGateEvent\n | CorroborationEvent\n | ReputationEvent\n | SanitizationEvent\n | GraphExecutionAuditEvent\n | ClawGuardViolationEvent;\n\n/** Base fields shared by all audit events. */\ninterface AuditEventBase {\n readonly id: string;\n readonly timestamp: string;\n readonly component: string;\n}\n\n/** Trust classification decision. */\nexport interface TrustClassificationEvent extends AuditEventBase {\n readonly type: 'trust_classification';\n readonly username: string;\n readonly assignedTier: TrustTier;\n readonly userRole: string;\n readonly isAllowlisted: boolean;\n readonly wasDowngraded: boolean;\n readonly reason: string;\n}\n\n/** Policy gate evaluation result. */\nexport interface PolicyGateEvent extends AuditEventBase {\n readonly type: 'policy_gate';\n /**\n * The agent action evaluated, for the security policy-gate path\n * (security/policy-gate.ts). Optional because the PIPELINE policy path\n * (pipeline/policy-evaluator.ts → #3710) records stage-boundary policy\n * decisions that have no `AgentAction` — they carry {@link stageType} +\n * {@link mode} + {@link ruleIds} instead. Security emitters always set it.\n */\n readonly actionType?: AgentActionType;\n readonly allowed: boolean;\n readonly requiresApproval: boolean;\n readonly inputTrustTier: TrustTier;\n readonly violationRules: readonly string[];\n /**\n * Pipeline-policy fields (#3710). Carried for the dev-pipeline\n * consensus→execute seam so the DURABLE record can distinguish soak (`warn`)\n * from enforce (`block`) and which rules/stage fired — without these the\n * persisted event is useless to the tune/readiness loop. Absent for the\n * security policy-gate path.\n */\n /** Enforcement mode the decision was made under: `warn` (soak) or `block` (enforce). */\n readonly mode?: 'off' | 'warn' | 'block';\n /** IDs of the policy rules that fired (mirrors `violationRules` for the pipeline path). */\n readonly ruleIds?: readonly string[];\n /** Type of the stage the gate guarded (e.g. `execute`). */\n readonly stageType?: string;\n /**\n * #3727: discriminates a per-EVALUATION SUMMARY record (`'summary'` — emitted\n * once per pipeline policy evaluation INCLUDING clean ones, the DENOMINATOR for\n * the would-block rate) from a per-VIOLATION record (`'violation'` — the\n * existing #3710 per-violation records). Absent for the security policy-gate\n * path. Denominator = count(recordKind==='summary'); numerator = summaries with\n * `violationCount > 0`. Scope the #3710 count-parity assertion to `'violation'`.\n */\n readonly recordKind?: 'summary' | 'violation';\n /** #3727: number of violations in THIS evaluation (set on the summary record). */\n readonly violationCount?: number;\n}\n\n/** Corroboration validation result. */\nexport interface CorroborationEvent extends AuditEventBase {\n readonly type: 'corroboration';\n readonly actionType: AgentActionType;\n readonly satisfied: boolean;\n readonly sourceCount: number;\n readonly missingRequirements: readonly string[];\n}\n\n/** Reputation assessment result. */\nexport interface ReputationEvent extends AuditEventBase {\n readonly type: 'reputation';\n readonly username: string;\n readonly reputationScore: number;\n readonly isSuspicious: boolean;\n readonly effectiveTier: TrustTier;\n readonly signalCount: number;\n}\n\n/** Summary of a single element stripped during sanitization. */\nexport interface StrippedElementSummary {\n /** Truncated tag text (≤30 chars + '...' from the sanitizer). */\n readonly tag: string;\n /** Reason the element was removed (e.g. 'Trail of Bits injection vector'). */\n readonly reason: string;\n}\n\n/** Max stripped-element details retained per sanitization event. */\nexport const MAX_STRIPPED_ELEMENTS_PER_EVENT = 20;\n\n/** Input sanitization result. */\nexport interface SanitizationEvent extends AuditEventBase {\n readonly type: 'sanitization';\n readonly source: string;\n readonly wasModified: boolean;\n readonly strippedCount: number;\n readonly injectionFlagCount: number;\n /**\n * Per-element tag/reason details, truncated to at most\n * MAX_STRIPPED_ELEMENTS_PER_EVENT entries. Required by CLAUDE.md's\n * Untrusted Input Policy: \"Log stripped elements for audit trail.\"\n */\n readonly strippedElements: readonly StrippedElementSummary[];\n}\n\n/**\n * ClawGuard AUDIT-mode violation (#4097). Records a tool call that VIOLATED the\n * derived access policy but was ALLOWED to proceed because the policy is in\n * `audit` mode (log-and-allow). Persisting these is what lets the audit→enforce\n * graduation loop size the real violation rate from durable telemetry rather\n * than ephemeral logs.\n */\nexport interface ClawGuardViolationEvent extends AuditEventBase {\n readonly type: 'clawguard_violation';\n /** The tool whose call violated the policy. */\n readonly toolName: string;\n /** Human-readable warning from the access decision (may be truncated). */\n readonly warning: string;\n /** Source of the derived policy (`llm` / `fallback-keyword` / `bypass`). */\n readonly policySource: string;\n /** Policy mode under which the violation was allowed (e.g. `audit`). */\n readonly mode: string;\n /** Request ID of the offending tool call, for correlation. */\n readonly requestId: string;\n}\n\n/** Graph execution lifecycle event (Issue #839). */\nexport interface GraphExecutionAuditEvent extends AuditEventBase {\n readonly type: 'graph_execution';\n readonly graphEvent: string;\n readonly nodeId?: string;\n readonly stepNumber: number;\n readonly detail: string;\n}\n\n/**\n * Query filter for retrieving audit events.\n *\n * The post-mortem dimensions (#3197) — `actionType`, `actor`, `violationRule`\n * — NARROW to events that actually carry the field (events lacking it are\n * excluded), unlike `trustTier`'s legacy keep-non-applicable behavior. Only\n * dimensions backed by a real event field are offered: `resource` and\n * `policyName` from the original ask were dropped because no AuditEvent\n * records them (a filter with no backing field would be dead config); the\n * policy-rule intent is served by `violationRule` (PolicyGateEvent's\n * `violationRules`).\n */\nexport interface AuditQuery {\n readonly type?: AuditEvent['type'];\n readonly since?: string;\n readonly until?: string;\n readonly trustTier?: TrustTier;\n /** Match PolicyGate/Corroboration events by their `actionType`. */\n readonly actionType?: AgentActionType;\n /** Match Trust/Reputation events by `username` (the acting/assessed user). */\n readonly actor?: string;\n /** Match PolicyGate events whose `violationRules` include this rule name. */\n readonly violationRule?: string;\n readonly limit?: number;\n}\n\n// ============================================================================\n// AuditTrail\n// ============================================================================\n\n/**\n * Append-only audit trail for security pipeline decisions.\n * Events are bounded by MAX_EVENTS to prevent unbounded growth.\n */\n/**\n * Optional durable sink: receives every fully-formed event appended to the\n * trail, so security decisions can be mirrored to a persistent, hash-chained\n * store (see security/audit-bridge.ts). Default-off — when absent, the trail\n * behaves exactly as before (#3291).\n */\nexport type DurableAuditSink = (event: AuditEvent) => void;\n\nexport class AuditTrail {\n private events: AuditEvent[] = [];\n private nextId = 1;\n\n constructor(private readonly durableSink?: DurableAuditSink) {}\n\n /** Appends an event to the trail. Returns the assigned event ID. */\n append(event: Omit<AuditEvent, 'id' | 'timestamp'>): string {\n const id = `audit-${String(this.nextId++)}`;\n const fullEvent = {\n ...event,\n id,\n timestamp: getTimeProvider().nowIso(),\n } as AuditEvent;\n\n this.events.push(fullEvent);\n this.enforceLimit();\n\n // Mirror to the durable store when wired (#3291). Best-effort: a sink\n // failure must never break the in-memory security pipeline.\n if (this.durableSink !== undefined) {\n try {\n this.durableSink(fullEvent);\n } catch {\n // Sink implementations already swallow+log; this is belt-and-suspenders.\n }\n }\n\n return id;\n }\n\n /** Queries events matching the given filter. */\n query(filter: AuditQuery = {}): readonly AuditEvent[] {\n let results = this.events as readonly AuditEvent[];\n\n if (filter.type !== undefined) {\n results = results.filter((e) => e.type === filter.type);\n }\n\n if (filter.since !== undefined) {\n results = filterSince(results, filter.since);\n }\n\n if (filter.until !== undefined) {\n results = filterUntil(results, filter.until);\n }\n\n if (filter.trustTier !== undefined) {\n results = filterByTrustTier(results, filter.trustTier);\n }\n\n if (filter.actionType !== undefined) {\n results = filterByActionType(results, filter.actionType);\n }\n\n if (filter.actor !== undefined) {\n results = filterByActor(results, filter.actor);\n }\n\n if (filter.violationRule !== undefined) {\n results = filterByViolationRule(results, filter.violationRule);\n }\n\n const limit = filter.limit ?? results.length;\n return results.slice(-limit);\n }\n\n /** Returns the total number of events. */\n get size(): number {\n return this.events.length;\n }\n\n /** Clears all events. */\n clear(): void {\n this.events = [];\n }\n\n /** Enforces MAX_EVENTS bound. */\n private enforceLimit(): void {\n if (this.events.length > MAX_EVENTS) {\n this.events = this.events.slice(-MAX_EVENTS);\n }\n }\n}\n\n// ============================================================================\n// Filter Helpers\n// ============================================================================\n\nfunction filterSince(events: readonly AuditEvent[], since: string): readonly AuditEvent[] {\n const sinceTime = new Date(since).getTime();\n return events.filter((e) => new Date(e.timestamp).getTime() >= sinceTime);\n}\n\nfunction filterUntil(events: readonly AuditEvent[], until: string): readonly AuditEvent[] {\n const untilTime = new Date(until).getTime();\n return events.filter((e) => new Date(e.timestamp).getTime() <= untilTime);\n}\n\nfunction filterByTrustTier(events: readonly AuditEvent[], tier: TrustTier): readonly AuditEvent[] {\n return events.filter((e) => {\n if (e.type === 'trust_classification') return e.assignedTier === tier;\n if (e.type === 'policy_gate') return e.inputTrustTier === tier;\n if (e.type === 'reputation') return e.effectiveTier === tier;\n return true;\n });\n}\n\n/**\n * Narrow to events carrying the given `actionType` (#3197). Only PolicyGate and\n * Corroboration events have one; all others are excluded.\n */\nfunction filterByActionType(\n events: readonly AuditEvent[],\n actionType: AgentActionType\n): readonly AuditEvent[] {\n return events.filter(\n (e) => (e.type === 'policy_gate' || e.type === 'corroboration') && e.actionType === actionType\n );\n}\n\n/**\n * Narrow to events for the given actor (#3197), matched on `username`. Only\n * Trust-classification and Reputation events carry a username; others are\n * excluded so an actor filter never returns unrelated rows.\n */\nfunction filterByActor(events: readonly AuditEvent[], actor: string): readonly AuditEvent[] {\n return events.filter(\n (e) => (e.type === 'trust_classification' || e.type === 'reputation') && e.username === actor\n );\n}\n\n/**\n * Narrow to PolicyGate events whose `violationRules` include the given rule\n * name (#3197) — the security post-mortem \"who tripped rule X\" query.\n */\nfunction filterByViolationRule(events: readonly AuditEvent[], rule: string): readonly AuditEvent[] {\n return events.filter((e) => e.type === 'policy_gate' && e.violationRules.includes(rule));\n}\n\n// ============================================================================\n// Convenience Emitters\n// ============================================================================\n\n/**\n * Records a trust classification decision.\n */\nexport function emitTrustEvent(\n trail: AuditTrail,\n data: Omit<TrustClassificationEvent, 'id' | 'timestamp' | 'type' | 'component'>\n): string {\n return trail.append({\n type: 'trust_classification',\n component: 'trust-classifier',\n ...data,\n });\n}\n\n/**\n * Records a policy gate evaluation.\n */\nexport function emitPolicyEvent(\n trail: AuditTrail,\n data: Omit<PolicyGateEvent, 'id' | 'timestamp' | 'type' | 'component'>\n): string {\n return trail.append({\n type: 'policy_gate',\n component: 'policy-gate',\n ...data,\n });\n}\n\n/**\n * Records a PIPELINE-policy gate decision (#3710) — the dev-pipeline\n * consensus→execute seam. Distinct from {@link emitPolicyEvent} (the security\n * policy-gate path with an `AgentAction`): this carries `mode`/`ruleIds`/\n * `stageType` so the durable record distinguishes soak(warn) from enforce(block)\n * and is usable by the tune/readiness loop. ONE append per call.\n */\nexport function emitPipelinePolicyEvent(\n trail: AuditTrail,\n data: Omit<PolicyGateEvent, 'id' | 'timestamp' | 'type' | 'component' | 'actionType'>\n): string {\n return trail.append({\n type: 'policy_gate',\n component: 'pipeline-policy-evaluator',\n ...data,\n });\n}\n\n/** The pipeline-policy would-block rate over a window (#3727). */\nexport interface PolicyWouldBlockRate {\n /** Total pipeline-policy evaluations (the denominator — summary records). */\n readonly evaluations: number;\n /** Evaluations that had ≥1 violation (what enforce mode WOULD block). */\n readonly wouldBlock: number;\n /** `wouldBlock / evaluations`; 0 when there are no evaluations. */\n readonly rate: number;\n}\n\n/**\n * Compute the pipeline-policy would-block RATE from durable audit events (#3727)\n * — the read-side of the per-evaluation summary records, and the signal the\n * #3769-enforce soak-readiness gate needs. Denominator = per-evaluation SUMMARY\n * records (`recordKind === 'summary'`); numerator = summaries with\n * `violationCount > 0` (the would-block fraction, independent of warn/block mode).\n * Per-violation records (`recordKind === 'violation'`) are intentionally NOT\n * counted — counting them would double-count and break the denominator.\n */\nexport function computePolicyWouldBlockRate(events: readonly AuditEvent[]): PolicyWouldBlockRate {\n let evaluations = 0;\n let wouldBlock = 0;\n for (const e of events) {\n if (e.type !== 'policy_gate' || e.recordKind !== 'summary') continue;\n evaluations += 1;\n if ((e.violationCount ?? 0) > 0) wouldBlock += 1;\n }\n return { evaluations, wouldBlock, rate: evaluations > 0 ? wouldBlock / evaluations : 0 };\n}\n\n/**\n * Records a corroboration validation.\n */\nexport function emitCorroborationEvent(\n trail: AuditTrail,\n data: Omit<CorroborationEvent, 'id' | 'timestamp' | 'type' | 'component'>\n): string {\n return trail.append({\n type: 'corroboration',\n component: 'corroboration-validator',\n ...data,\n });\n}\n\n/**\n * Records a reputation assessment.\n */\nexport function emitReputationEvent(\n trail: AuditTrail,\n data: Omit<ReputationEvent, 'id' | 'timestamp' | 'type' | 'component'>\n): string {\n return trail.append({\n type: 'reputation',\n component: 'reputation-model',\n ...data,\n });\n}\n\n/**\n * Records an input sanitization result.\n */\nexport function emitSanitizationEvent(\n trail: AuditTrail,\n data: Omit<SanitizationEvent, 'id' | 'timestamp' | 'type' | 'component'>\n): string {\n return trail.append({\n type: 'sanitization',\n component: 'input-sanitizer',\n ...data,\n });\n}\n\n/**\n * Records a graph execution lifecycle event.\n */\nexport function emitGraphExecutionEvent(\n trail: AuditTrail,\n data: Omit<GraphExecutionAuditEvent, 'id' | 'timestamp' | 'type' | 'component'>\n): string {\n return trail.append({\n type: 'graph_execution',\n component: 'graph-executor',\n ...data,\n });\n}\n\n/**\n * Records a ClawGuard AUDIT-mode violation (#4097) — a policy-violating tool\n * call that was log-and-allowed because the policy is in `audit` mode. ONE\n * append per call; mirrors to the durable sink when the trail is wired.\n */\nexport function emitClawGuardViolation(\n trail: AuditTrail,\n data: Omit<ClawGuardViolationEvent, 'id' | 'timestamp' | 'type' | 'component'>\n): string {\n return trail.append({\n type: 'clawguard_violation',\n component: 'clawguard-audit',\n ...data,\n });\n}\n\n/**\n * Creates an onEvent callback that bridges graph events to the audit trail.\n * Pass the returned function as `onEvent` in GraphExecuteOptions.\n *\n * @example\n * const trail = createAuditTrail();\n * await executeGraph(graph, inputs, { onEvent: createGraphAuditBridge(trail) });\n */\nexport function createGraphAuditBridge(\n trail: AuditTrail\n): (event: { readonly type: string; readonly [key: string]: unknown }) => void {\n return (event) => {\n const nodeId = typeof event['nodeId'] === 'string' ? event['nodeId'] : undefined;\n const stepNumber = typeof event['stepNumber'] === 'number' ? event['stepNumber'] : 0;\n emitGraphExecutionEvent(trail, {\n graphEvent: event.type,\n ...(nodeId !== undefined ? { nodeId } : {}),\n stepNumber,\n detail: formatGraphEventDetail(event),\n });\n };\n}\n\n/** Formats a brief detail string from a graph event. */\nfunction formatGraphEventDetail(event: {\n readonly type: string;\n readonly [key: string]: unknown;\n}): string {\n switch (event.type) {\n case 'node_started':\n return `Node ${String(event['nodeId'])} starting`;\n case 'node_completed':\n return `Node ${String(event['nodeId'])} completed in ${String(event['durationMs'])}ms`;\n case 'node_error':\n return `Node ${String(event['nodeId'])} failed: ${String(event['error'])}`;\n case 'state_updated':\n return `State updated: ${String(event['updatedKeys'])}`;\n case 'step_completed':\n return `Step ${String(event['stepNumber'])}: ${String(event['nodesExecuted'])} nodes`;\n case 'execution_complete':\n return `Complete: ${String(event['totalSteps'])} steps, ${String(event['durationMs'])}ms`;\n default:\n return event.type;\n }\n}\n\n/**\n * Creates a new AuditTrail instance. Pass a {@link DurableAuditSink} (e.g. from\n * `createDurableAuditSink(auditLogger)`) to mirror appended security decisions\n * to a durable, hash-chained store (#3291). Default: in-memory only.\n */\nexport function createAuditTrail(durableSink?: DurableAuditSink): AuditTrail {\n return new AuditTrail(durableSink);\n}\n"],"mappings":";;;;;AAuBA,IAAM,aAAa;AAsGZ,IAAM,kCAAkC;AAyFxC,IAAM,aAAN,MAAiB;AAAA,EAItB,YAA6B,aAAgC;AAAhC;AAAA,EAAiC;AAAA,EAAjC;AAAA,EAHrB,SAAuB,CAAC;AAAA,EACxB,SAAS;AAAA;AAAA,EAKjB,OAAO,OAAqD;AAC1D,UAAM,KAAK,SAAS,OAAO,KAAK,QAAQ,CAAC;AACzC,UAAM,YAAY;AAAA,MAChB,GAAG;AAAA,MACH;AAAA,MACA,WAAW,gBAAgB,EAAE,OAAO;AAAA,IACtC;AAEA,SAAK,OAAO,KAAK,SAAS;AAC1B,SAAK,aAAa;AAIlB,QAAI,KAAK,gBAAgB,QAAW;AAClC,UAAI;AACF,aAAK,YAAY,SAAS;AAAA,MAC5B,QAAQ;AAAA,MAER;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,MAAM,SAAqB,CAAC,GAA0B;AACpD,QAAI,UAAU,KAAK;AAEnB,QAAI,OAAO,SAAS,QAAW;AAC7B,gBAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,SAAS,OAAO,IAAI;AAAA,IACxD;AAEA,QAAI,OAAO,UAAU,QAAW;AAC9B,gBAAU,YAAY,SAAS,OAAO,KAAK;AAAA,IAC7C;AAEA,QAAI,OAAO,UAAU,QAAW;AAC9B,gBAAU,YAAY,SAAS,OAAO,KAAK;AAAA,IAC7C;AAEA,QAAI,OAAO,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ACjB;AACF;AAOO,SAAS,iBAAiB,aAA4C;AAC3E,SAAO,IAAI,WAAW,WAAW;AACnC;","names":[]}
@@ -1,3 +1,6 @@
1
+ import {
2
+ emitClawGuardViolation
3
+ } from "./chunk-RCQLUJY3.js";
1
4
  import {
2
5
  CACHE_TIMEOUTS,
3
6
  MCP_TIMEOUTS,
@@ -1331,6 +1334,28 @@ function decideOnViolation(toolName, mode) {
1331
1334
  // src/security/access-constraint-deriver/mcp-guard.ts
1332
1335
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
1333
1336
  var accessPolicyStorage = new AsyncLocalStorage2();
1337
+ var auditTrailStorage = new AsyncLocalStorage2();
1338
+ var MAX_WARNING_LEN = 500;
1339
+ function withAuditTrail(trail, fn) {
1340
+ return auditTrailStorage.run(trail, fn);
1341
+ }
1342
+ function getActiveAuditTrail() {
1343
+ return auditTrailStorage.getStore();
1344
+ }
1345
+ function recordAuditModeViolation(input) {
1346
+ const trail = getActiveAuditTrail();
1347
+ if (trail === void 0) return;
1348
+ try {
1349
+ emitClawGuardViolation(trail, {
1350
+ toolName: input.toolName,
1351
+ warning: input.warning.slice(0, MAX_WARNING_LEN),
1352
+ policySource: input.policySource,
1353
+ mode: input.mode,
1354
+ requestId: input.requestId
1355
+ });
1356
+ } catch {
1357
+ }
1358
+ }
1334
1359
  function withAccessPolicy(policy, fn) {
1335
1360
  return accessPolicyStorage.run(policy, fn);
1336
1361
  }
@@ -1372,6 +1397,13 @@ function createAccessPolicyChainMiddleware(toolName) {
1372
1397
  policySource: policy.source,
1373
1398
  requestId: ctx.requestContext.requestId
1374
1399
  });
1400
+ recordAuditModeViolation({
1401
+ toolName,
1402
+ warning: decision.warning,
1403
+ policySource: policy.source,
1404
+ mode: policy.mode,
1405
+ requestId: ctx.requestContext.requestId
1406
+ });
1375
1407
  return next(args, ctx);
1376
1408
  }
1377
1409
  ctx.logger.info("access-policy: tool call denied", {
@@ -1968,6 +2000,7 @@ export {
1968
2000
  NOOP_NOTIFIER,
1969
2001
  abortSignalStorage,
1970
2002
  withProgressHeartbeat,
2003
+ withAuditTrail,
1971
2004
  withAccessPolicy,
1972
2005
  getToolTimeout,
1973
2006
  wrapToolWithTimeout,
@@ -1990,4 +2023,4 @@ export {
1990
2023
  VOTING_THRESHOLDS,
1991
2024
  ConsensusMetricsSchema
1992
2025
  };
1993
- //# sourceMappingURL=chunk-J2KMYVWA.js.map
2026
+ //# sourceMappingURL=chunk-RII4VXHO.js.map