Repository navigation
Expand file tree
/
Copy pathobservability.test.ts
More file actions
398 lines (373 loc) · 10.6 KB
/
Copy pathobservability.test.ts
File metadata and controls
398 lines (373 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import { trace } from "@opentelemetry/api";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ControlExecutionEvent } from "agent-control";
import {
buildControlExecutionEvents,
buildControlObservabilityIndex,
emitControlExecutionEvents,
resolveTraceContext,
} from "../src/observability.ts";
afterEach(() => {
vi.restoreAllMocks();
});
describe("observability helpers", () => {
it("derives observability identity in leaf evaluation order", () => {
// Given two rendered controls with composite and leaf conditions
const index = buildControlObservabilityIndex([
{
id: 1,
name: "composite",
control: {
action: {
decision: "observe",
},
condition: {
and: [
{
selector: {
path: "input",
},
evaluator: {
name: "regex",
config: {
pattern: "alpha",
},
},
},
{
not: {
selector: {
path: "context.user.role",
},
evaluator: {
name: "list",
config: {
values: ["admin"],
},
},
},
},
],
},
enabled: true,
execution: "server",
},
},
]);
// When the cached observability metadata is read back
const identity = index.get(1);
// Then the first leaf becomes the representative identity and all leaves are tracked
expect(identity).toEqual({
selectorPath: "input",
evaluatorName: "regex",
leafCount: 2,
allEvaluators: ["regex", "list"],
allSelectorPaths: ["input", "context.user.role"],
});
});
it("skips unrendered controls and traverses or branches", () => {
// Given one rendered control with an or branch and one unrendered template control
const index = buildControlObservabilityIndex([
{
id: 1,
name: "or-control",
control: {
action: {
decision: "observe",
},
condition: {
or: [
{
selector: {
path: "input.command",
},
evaluator: {
name: "regex",
config: {
pattern: "npm",
},
},
},
{
selector: {
path: "context.user.role",
},
evaluator: {
name: "equals",
config: {
value: "admin",
},
},
},
],
},
enabled: true,
execution: "server",
},
},
{
id: 2,
name: "template-control",
control: {
action: {
decision: "observe",
},
} as never,
},
]);
// When the index is built from the returned controls
const identity = index.get(1);
// Then only rendered controls are indexed and both or leaves are captured
expect(index.size).toBe(1);
expect(identity).toEqual({
selectorPath: "input.command",
evaluatorName: "regex",
leafCount: 2,
allEvaluators: ["regex", "equals"],
allSelectorPaths: ["input.command", "context.user.role"],
});
});
it("builds control execution events with category-specific error handling", () => {
// Given a cached control identity and a mixed evaluation response
const events = buildControlExecutionEvents({
evaluation: {
isSafe: false,
confidence: 0.5,
matches: [
{
action: "deny",
controlExecutionId: "exec-match",
controlId: 1,
controlName: "deny-shell",
result: {
matched: true,
confidence: 0.9,
metadata: {
outcome: "match",
},
},
},
],
errors: [
{
action: "observe",
controlExecutionId: "exec-error",
controlId: 2,
controlName: "audit-shell",
result: {
matched: false,
confidence: 0.1,
error: "timeout",
},
},
],
nonMatches: [
{
action: "observe",
controlExecutionId: "exec-non-match",
controlId: 3,
controlName: "allow-shell",
result: {
matched: false,
confidence: 0.2,
error: "ignored",
},
},
],
},
agentName: "openclaw-agent:worker-1",
stepName: "shell",
stepType: "tool",
checkStage: "pre",
traceContext: {
traceId: "a".repeat(32),
spanId: "b".repeat(16),
},
controlObservabilityById: new Map([
[
1,
{
selectorPath: "input.command",
evaluatorName: "regex",
leafCount: 1,
allEvaluators: ["regex"],
allSelectorPaths: ["input.command"],
},
],
]),
sourceAgentId: "worker-1",
pluginId: "agent-control-openclaw-plugin",
runId: "run-1",
toolCallId: "call-1",
});
// When the events are built
const [matchEvent, errorEvent, nonMatchEvent] = events;
// Then each category maps to the correct matched/error fields
expect(matchEvent).toMatchObject({
matched: true,
errorMessage: null,
evaluatorName: "regex",
selectorPath: "input.command",
traceId: "a".repeat(32),
spanId: "b".repeat(16),
});
expect(matchEvent.metadata).toMatchObject({
outcome: "match",
primary_evaluator: "regex",
openclaw_step_name: "shell",
openclaw_tool_call_id: "call-1",
});
expect(errorEvent).toMatchObject({
matched: false,
errorMessage: "timeout",
evaluatorName: null,
selectorPath: null,
});
expect(nonMatchEvent).toMatchObject({
matched: false,
errorMessage: null,
});
});
it("falls back to generated trace identifiers when no active span exists", () => {
// Given no active OpenTelemetry span
const traceContext = resolveTraceContext();
// When trace context is resolved
expect(traceContext.traceId).toMatch(/^[a-f0-9]{32}$/);
expect(traceContext.spanId).toMatch(/^[a-f0-9]{16}$/);
});
it("reuses the active OpenTelemetry span context when it is valid", () => {
// Given a valid active span context from OpenTelemetry
vi.spyOn(trace, "getActiveSpan").mockReturnValue({
spanContext: () => ({
traceId: "1".repeat(32),
spanId: "2".repeat(16),
traceFlags: 1,
}),
} as never);
vi.spyOn(trace, "isSpanContextValid").mockReturnValue(true);
// When trace context is resolved
const traceContext = resolveTraceContext();
// Then the active span identifiers are preserved
expect(traceContext).toEqual({
traceId: "1".repeat(32),
spanId: "2".repeat(16),
});
});
it("logs ingestion failures without throwing", async () => {
// Given one event and an ingest client that fails
const logger = {
info: vi.fn(),
debug: vi.fn(),
warn: vi.fn(),
block: vi.fn(),
};
const ingestEvents = vi.fn().mockRejectedValue(new Error("boom"));
const events: ControlExecutionEvent[] = [
{
action: "observe",
agentName: "openclaw-agent:worker-1",
appliesTo: "tool_call",
checkStage: "pre",
confidence: 1,
controlId: 1,
controlName: "allow-shell",
matched: false,
spanId: "b".repeat(16),
traceId: "a".repeat(32),
},
];
// When the fire-and-forget ingest path runs
emitControlExecutionEvents({
client: {
observability: {
ingestEvents,
},
} as never,
logger,
events,
agentName: "openclaw-agent:worker-1",
stepName: "shell",
});
await Promise.resolve();
await Promise.resolve();
// Then the error is logged and the caller is not forced to await or catch
expect(ingestEvents).toHaveBeenCalledWith({ events });
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining("observability_ingest failed"),
);
});
it("returns early when there are no events to ingest", () => {
// Given an empty event batch
const logger = {
info: vi.fn(),
debug: vi.fn(),
warn: vi.fn(),
block: vi.fn(),
};
const ingestEvents = vi.fn();
// When the fire-and-forget ingest path runs
emitControlExecutionEvents({
client: {
observability: {
ingestEvents,
},
} as never,
logger,
events: [],
agentName: "openclaw-agent:worker-1",
stepName: "shell",
});
// Then no ingest call or log is emitted
expect(ingestEvents).not.toHaveBeenCalled();
expect(logger.warn).not.toHaveBeenCalled();
expect(logger.debug).not.toHaveBeenCalled();
});
it("warns when observability ingestion only partially enqueues events", async () => {
// Given one event and an ingest client that partially accepts the batch
const logger = {
info: vi.fn(),
debug: vi.fn(),
warn: vi.fn(),
block: vi.fn(),
};
const events: ControlExecutionEvent[] = [
{
action: "observe",
agentName: "openclaw-agent:worker-1",
appliesTo: "tool_call",
checkStage: "pre",
confidence: 1,
controlId: 1,
controlName: "allow-shell",
matched: false,
spanId: "b".repeat(16),
traceId: "a".repeat(32),
},
];
const ingestEvents = vi.fn().mockResolvedValue({
received: 1,
enqueued: 0,
dropped: 1,
status: "partial",
});
// When the fire-and-forget ingest path runs
emitControlExecutionEvents({
client: {
observability: {
ingestEvents,
},
} as never,
logger,
events,
agentName: "openclaw-agent:worker-1",
stepName: "shell",
});
await Promise.resolve();
await Promise.resolve();
// Then the partial enqueue result is warned instead of logged as success
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining("observability_ingest partial"),
);
expect(logger.debug).not.toHaveBeenCalled();
});
});