Repository navigation
Expand file tree
/
Copy pathtools.test.ts
More file actions
6965 lines (5882 loc) · 323 KB
/
Copy pathtools.test.ts
File metadata and controls
6965 lines (5882 loc) · 323 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test";
import { asSchema } from "ai";
import { z } from "zod";
import {
AGENT_WORKFLOW_BUDGETS,
AGENT_EXECUTION_PROFILE,
AGENT_OPERATIONS_PROFILE,
} from "@/lib/agent/execution-policy";
import type { AgentStatementLanguageId } from "@/lib/agent/agent-manifest";
import { AgentRunDeadline } from "@/lib/agent/deadline";
import { AgentRepairLedger, fingerprintStatement } from "@/lib/agent/repair-ledger";
import {
AGENT_TOOL_DEFINITIONS,
type AgentToolContext,
agentToolDefinition,
comparePlansTool,
composeReportTool,
executeAgentOperation,
inspectOperationsTool,
inspectPlanTool,
inspectSchemaTool,
planTableProfile,
presentAnswerTool,
profileTableTool,
readCatalogForGrounding,
readStatementForGrounding,
recommendChangeTool,
runReadQueryTool,
selectAgentTools,
} from "@/lib/agent/tools";
import { AGENT_ANSWER_CONTRACT } from "@/lib/agent/tool-contracts";
import { UNTRUSTED_CONTENT_BEGIN, UNTRUSTED_CONTENT_END } from "@/lib/agent/untrusted-content";
import {
AGENT_WORKFLOW_PRESENTS_ANSWER,
AGENT_WORKFLOW_SENDS_STATEMENTS,
type AgentRunEvent,
type AgentRunRecord,
type AgentRunWorkflowType,
} from "@/lib/agent/types";
import { ExecutionArtifactStore } from "@/lib/db/operations/artifacts";
import { ExecutionBudgetTracker } from "@/lib/db/operations/budgets";
import {
createCanonicalOperationRegistry,
dbOperationsReadDescriptor,
dbSchemaReadDescriptor,
sqlExplainAnalyzeDescriptor,
sqlExplainEstimateDescriptor,
sqlQueryReadDescriptor,
sqlTableProfileDescriptor,
} from "@/lib/db/operations/descriptors";
import { agentPlanExecutionSqlInput, agentReadSqlInput } from "@/lib/db/operations/statement-guard";
import { createTargetScope } from "@/lib/db/operations/policy";
import * as errorModule from "@/lib/db/errors";
import {
AuthenticationError,
ConnectionError,
DatabaseConfigError,
DatabaseError,
ExecutionProfileError,
mapDatabaseError,
PoolExhaustedError,
QueryError,
TimeoutError,
} from "@/lib/db/errors";
import type { DatabaseProvider, ProviderCapabilities } from "@/lib/db/types";
import { TABLE_LABELS } from "../../../fixtures/provider-labels";
import type { DatabaseConnection, QueryResult } from "@/lib/types";
/**
* The tool layer over the M1 operations (#329 T6).
*
* Every database reach in this layer goes through `executeAuditedOperation`
* against a provider acquired from the execution-profile seam, so the spy pair
* below (`acquireProvider` + `queryReadOnly`) is the instrument for the
* acceptance bar's central invariant: on a denial, on an approval requirement, on
* a deadline refusal and on a ledger refusal, NEITHER spy is reached.
*
* What the audit TRAIL contains is deliberately not asserted here, for the same
* reason `tests/unit/db/operations/execution.test.ts` says so in its own header:
* `tests/api/db/maintenance.test.ts` replaces `@/lib/audit` process-wide and
* `bun run test` runs these directories in one process.
*/
const connection: DatabaseConnection = {
id: "conn-1",
name: "Orders",
type: "postgres",
createdAt: new Date(0),
};
const capabilities: ProviderCapabilities = {
queryLanguage: "sql",
supportsExplain: true,
explainFormat: "postgres-json",
supportsExternalQueryLimiting: true,
supportsInlineRowEdit: true,
supportsMaintenance: false,
maintenanceOperations: [],
supportsConnectionString: true,
defaultPort: 5432,
schemaRefreshPattern: "manual",
};
function queryResult(overrides: Partial<QueryResult> = {}): QueryResult {
return {
rows: [{ id: 1, name: "Ada" }],
fields: ["id", "name"],
rowCount: 1,
executionTime: 12,
...overrides,
};
}
interface Harness {
readonly context: AgentToolContext;
readonly queryReadOnly: ReturnType<typeof mock>;
readonly acquireProvider: ReturnType<typeof mock>;
readonly tracker: ExecutionBudgetTracker;
readonly artifacts: ExecutionArtifactStore<QueryResult>;
readonly deadline: AgentRunDeadline;
readonly repairs: AgentRepairLedger;
}
/** A clock that never advances, so the deadline is never the reason anything fails. */
const frozenClock = () => 1_000;
function harness(
overrides: Partial<AgentToolContext> = {},
result: () => Promise<QueryResult> = async () => queryResult(),
): Harness {
const queryReadOnly = mock(result);
const provider = { queryReadOnly } as unknown as DatabaseProvider;
const acquireProvider = mock(async () => provider);
const tracker = new ExecutionBudgetTracker();
const artifacts = new ExecutionArtifactStore<QueryResult>({ ttlMs: 60_000, maxArtifacts: 16 });
const deadline = new AgentRunDeadline(
AGENT_WORKFLOW_BUDGETS.investigation.policy.budgets.maxTotalRunMs * 2,
frozenClock,
);
const repairs = new AgentRepairLedger();
const context: AgentToolContext = {
runId: "run-1",
// A model with no profile, so these tests read the DEFAULTS. A named model here would
// quietly test one model's settings and call the result the tool's behaviour.
modelId: "unmeasured-model-for-tests",
mode: "agent",
workflowType: "investigation",
actor: { sessionId: "session-1", role: "user" },
connection,
capabilities,
labels: TABLE_LABELS,
registry: createCanonicalOperationRegistry(),
scope: createTargetScope("conn-1"),
tracker,
artifacts,
deadline,
repairs,
acquireProvider,
clock: stubClock(1_000, 1_012),
...overrides,
};
return { context, queryReadOnly, acquireProvider, tracker, artifacts, deadline, repairs };
}
/** Deterministic clock for the audited-execution elapsed measurement. */
function stubClock(...instants: number[]): () => number {
let index = 0;
return () => {
const value = instants[Math.min(index, instants.length - 1)];
index += 1;
return value;
};
}
let consoleSpy: ReturnType<typeof spyOn<Console, "log">>;
beforeEach(() => {
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
});
afterEach(() => {
consoleSpy.mockRestore();
});
const WORKFLOW_TYPES = [
"investigation",
"query-optimization",
"database-assessment",
"operations",
"data-analysis",
] as const;
/**
* The workflows built ON the read-class four. `operations` is deliberately not one of
* them: all three read-class tools it leaves out reach `provider.queryReadOnly`, so
* offering any of them would put back, tool by tool, the engine restriction that
* workflow exists to escape.
*/
const SQL_WORKFLOW_TYPES = ["investigation", "query-optimization", "database-assessment", "data-analysis"] as const;
/** A run record narrowed to what tool selection is allowed to read. */
const persisted = (
mode: AgentRunRecord["mode"],
workflowType: AgentRunWorkflowType = "investigation",
): Pick<AgentRunRecord, "mode" | "workflowType"> => ({ mode, workflowType });
describe("selectAgentTools — the server decides, from the persisted mode and workflow type", () => {
test("planning mode yields a genuinely empty tool set", () => {
expect(selectAgentTools(persisted("planning"))).toEqual([]);
});
test("planning stays toolless whatever the run is FOR", () => {
// A workflow type must never be a way to give a toolless mode a tool.
for (const workflowType of WORKFLOW_TYPES) {
expect(selectAgentTools(persisted("planning", workflowType)), workflowType).toEqual([]);
}
});
test("agent mode yields the four read-class tools and nothing else", () => {
const names = selectAgentTools(persisted("agent")).map((tool) => tool.name);
expect([...names].sort()).toEqual(["compose_report", "inspect_plan", "inspect_schema", "run_read_query"]);
});
test("every workflow type resolves to a tool set, so none can fall through to undefined", () => {
// A workflow with no entry would hand the run loop `undefined` and take its
// tools away entirely.
for (const workflowType of WORKFLOW_TYPES) {
expect(selectAgentTools(persisted("agent", workflowType)).length, workflowType).toBeGreaterThan(0);
}
});
test("the read-class four are what every SQL-authoring workflow starts from", () => {
for (const workflowType of SQL_WORKFLOW_TYPES) {
const names = selectAgentTools(persisted("agent", workflowType)).map((tool) => tool.name);
expect(names.slice(0, 4), workflowType).toEqual([
"inspect_schema",
"run_read_query",
"inspect_plan",
"compose_report",
]);
}
});
test("the operations workflow carries NONE of the tools that send SQL to a database", () => {
// The property the whole workflow rests on, asserted as an exclusion rather than
// as a list: a tool added to the read class later must not silently reach a run
// that is offered on engines with no read-only statement path at all.
const names = selectAgentTools(persisted("agent", "operations")).map((tool) => tool.name);
for (const sqlAuthoring of ["inspect_schema", "run_read_query", "inspect_plan", "profile_table", "compare_plans"]) {
expect(names, sqlAuthoring).not.toContain(sqlAuthoring);
}
expect(names).toEqual(["inspect_operations", "recommend_change", "compose_report"]);
});
test("the persisted statement language picks the variant, and an absent one reads as sql", () => {
// The same frozen array for the same variant, so a run recorded before languages existed and one recorded
// as sql are offered exactly the same tools.
expect(selectAgentTools({ ...persisted("agent"), statementLanguage: "sql" })).toBe(
selectAgentTools(persisted("agent")),
);
expect(selectAgentTools({ ...persisted("agent", "operations"), statementLanguage: "kubectl" })).toBe(
selectAgentTools(persisted("agent", "operations")),
);
expect(selectAgentTools({ ...persisted("planning"), statementLanguage: "kubectl" })).toEqual([]);
expect(
selectAgentTools({ ...persisted("agent", "database-assessment"), statementLanguage: "kubectl" }).map(
(tool) => tool.name,
),
).toEqual(["run_read_query", "profile_workloads", "compose_report"]);
});
test("a SQL run is offered the SQL definitions themselves, by name", () => {
// Every definition is read through `agentToolDefinition`, so a later language's override cannot reach a SQL
// run: what an investigation sends is the record's own entry for each name, the same object.
const offered = selectAgentTools({ mode: "agent", workflowType: "investigation" });
expect(offered).toEqual(offered.map((definition) => AGENT_TOOL_DEFINITIONS[definition.name]));
for (const definition of offered) expect(definition, definition.name).toBe(AGENT_TOOL_DEFINITIONS[definition.name]);
});
test("a run with no recorded language reads the SQL definition", () => {
expect(agentToolDefinition(undefined, "investigation", "run_read_query")).toBe(
AGENT_TOOL_DEFINITIONS.run_read_query,
);
expect(agentToolDefinition("sql", "operations", "inspect_operations")).toBe(
AGENT_TOOL_DEFINITIONS.inspect_operations,
);
});
test("present_answer is offered exactly where AGENT_WORKFLOW_PRESENTS_ANSWER says it is", () => {
// The binding that keeps four layers agreeing. The rail offers the auto-execute
// checkbox from this record, the route accepts the field from it, and
// `investigation.ts` states AUTO_EXECUTE_RULE from it — all three describing a
// hand-over that only `present_answer` can perform. A workflow that gained the
// tool without the flag would take the setting silently and never offer it;
// one that gained the flag without the tool would promise a hand-over it cannot
// make. Asserted over EVERY workflow, so neither direction can drift.
for (const workflowType of WORKFLOW_TYPES) {
const names = selectAgentTools(persisted("agent", workflowType)).map((tool) => tool.name);
expect(names.includes("present_answer"), workflowType).toBe(AGENT_WORKFLOW_PRESENTS_ANSWER[workflowType]);
}
// And the record is not vacuously false everywhere, which would satisfy the loop
// above while the feature did not exist.
expect(AGENT_WORKFLOW_PRESENTS_ANSWER["data-analysis"]).toBe(true);
});
test("a statement-carrying tool is offered exactly where AGENT_WORKFLOW_SENDS_STATEMENTS says so", () => {
/*
The binding that lets `POST /api/agent/runs` refuse a run BEFORE it opens on an
engine whose provider implements no read-only statement path (#512). The route reads
that record and nothing else, so this is what keeps it equal to the tool sets: a
workflow that gained a statement tool without the flag would
open there and end `engine-unsupported` after a model turn, and one that gained the
flag without such a tool would be withheld from an engine it runs on today.
Which operations carry a statement is MEASURED off the descriptors rather than
listed here: a statement-carrying operation is one whose input contract is a
statement schema, and those are exactly the calls that reach the engine through
`provider.queryReadOnly`.
*/
const statementCarrying = new Set(
[
sqlQueryReadDescriptor,
sqlExplainEstimateDescriptor,
sqlExplainAnalyzeDescriptor,
sqlTableProfileDescriptor,
dbOperationsReadDescriptor,
dbSchemaReadDescriptor,
]
.filter(
(descriptor) =>
descriptor.inputSchema === agentReadSqlInput || descriptor.inputSchema === agentPlanExecutionSqlInput,
)
.map((descriptor) => descriptor.id),
);
// Not vacuous in either direction: the four SQL operations are in the set, and the
// two that name no statement at all - the curated reading and the provider's own
// schema read - are out of it.
expect(statementCarrying).toEqual(
new Set(["sql.query.read", "sql.explain.estimate", "sql.explain.analyze", "sql.table.profile"]),
);
for (const workflowType of WORKFLOW_TYPES) {
const sendsStatement = selectAgentTools(persisted("agent", workflowType)).some(
(tool) => tool.operationId !== undefined && statementCarrying.has(tool.operationId),
);
expect(sendsStatement, workflowType).toBe(AGENT_WORKFLOW_SENDS_STATEMENTS[workflowType]);
}
// And the record is not uniformly true, which would satisfy the loop above while
// leaving no workflow for an unsupported engine to run.
expect(AGENT_WORKFLOW_SENDS_STATEMENTS.operations).toBe(false);
});
test("no workflow but operations is offered the curated reading", () => {
for (const workflowType of SQL_WORKFLOW_TYPES) {
const names = selectAgentTools(persisted("agent", workflowType)).map((tool) => tool.name);
expect(names, workflowType).not.toContain("inspect_operations");
}
});
test("each template is offered its own tools, and no other workflow gets them", () => {
// The axis made load-bearing: an investigation that calls `compare_plans` is
// told there is no such tool, because for that run there is not.
expect(selectAgentTools(persisted("agent", "query-optimization")).map((tool) => tool.name)).toEqual([
"inspect_schema",
"run_read_query",
"inspect_plan",
"compose_report",
"compare_plans",
"recommend_change",
]);
expect(selectAgentTools(persisted("agent", "database-assessment")).map((tool) => tool.name)).toEqual([
"inspect_schema",
"run_read_query",
"inspect_plan",
"compose_report",
"profile_table",
]);
expect(selectAgentTools(persisted("agent", "data-analysis")).map((tool) => tool.name)).toEqual([
"inspect_schema",
"run_read_query",
"inspect_plan",
"compose_report",
"profile_table",
"present_answer",
]);
const investigation = selectAgentTools(persisted("agent", "investigation")).map((tool) => tool.name);
for (const template of ["compare_plans", "recommend_change", "profile_table", "present_answer"]) {
expect(investigation).not.toContain(template);
}
expect(selectAgentTools(persisted("agent", "query-optimization")).map((t) => t.name)).not.toContain(
"profile_table",
);
expect(selectAgentTools(persisted("agent", "database-assessment")).map((t) => t.name)).not.toContain(
"compare_plans",
);
});
test("neither of the optimization tools reaches a database", () => {
// Both are ledger-only: they record what the run already established. A tool
// that named an operation would need a descriptor, an audit line and a budget.
expect(AGENT_TOOL_DEFINITIONS.compare_plans.operationId).toBeUndefined();
expect(AGENT_TOOL_DEFINITIONS.recommend_change.operationId).toBeUndefined();
});
test("a client-supplied tool list is ignored, not merged", () => {
// The shape a hostile request body would take: the run record carries the mode
// and the workflow type, and anything else travelling beside them has no effect.
const hostile = {
mode: "planning",
workflowType: "investigation",
tools: ["run_read_query"],
allowedTools: ["sql.explain.analyze"],
};
expect(selectAgentTools(hostile as unknown as Pick<AgentRunRecord, "mode" | "workflowType">)).toEqual([]);
});
test("no tool maps onto the approval-gated plan-execution operation", () => {
const operations = Object.values(AGENT_TOOL_DEFINITIONS).map((tool) => tool.operationId);
expect(operations).not.toContain("sql.explain.analyze");
// `toStrictEqual`, not `toEqual`: bun's `toEqual` ignores `undefined` entries, so
// the array comparison this assertion used to make was blind to every tool that
// declares no operation — it passed unchanged when two more were added.
expect([...operations].sort()).toStrictEqual([
"cluster.usage.read",
"cluster.workloads.read",
"db.operations.read",
"sql.explain.estimate",
"sql.query.read",
"sql.query.read",
"sql.table.profile",
undefined,
undefined,
undefined,
undefined,
]);
});
test("exactly the four ledger-only tools declare no operation", () => {
const withoutOperation = Object.values(AGENT_TOOL_DEFINITIONS)
.filter((tool) => tool.operationId === undefined)
.map((tool) => tool.name)
.sort();
expect(withoutOperation).toEqual(["compare_plans", "compose_report", "present_answer", "recommend_change"]);
});
test("the returned set is frozen, so a caller cannot push a tool into it", () => {
expect(Object.isFrozen(selectAgentTools(persisted("agent")))).toBe(true);
});
test("every definition declares a description and an input schema", () => {
for (const tool of selectAgentTools(persisted("agent"))) {
expect(tool.description.length).toBeGreaterThan(20);
expect(tool.inputSchema.safeParse(undefined).success, tool.name).toBe(false);
}
});
});
/*
#350: two live runs called `run_read_query` seven times and `compose_report`
zero times, and the ledger's rationales say why — "evidence (array of table row
objects or strings? …)". Both places the model is told about citing said a claim
must cite; neither said what a citation IS. So the contract is asserted here as
the model reads it: the description carries the object, and the object it carries
is one the schema beside it accepts.
*/
describe("a tool that demands a citation says what a citation IS (#350)", () => {
/** Every literal evidence object the description offers, as the model would lift it. */
const offeredObjects = (description: string): unknown[] =>
[...description.matchAll(/\{"source":"[a-z-]+","[A-Za-z]+":"[^"]*"\}/g)].map((match) => JSON.parse(match[0]));
for (const name of ["compose_report", "recommend_change"] as const) {
test(`${name} shows both arms of the evidence contract`, () => {
const objects = offeredObjects(AGENT_TOOL_DEFINITIONS[name].description);
expect(objects.map((object) => (object as { source: string }).source).sort()).toEqual([
"artifact",
"context-snapshot",
]);
});
test(`${name} accepts the very objects its own description offers`, () => {
// The point of asserting through the SCHEMA rather than on the prose: a
// description that showed a shape the parser refuses would be worse than one
// that showed nothing, and only this fails when the two drift apart.
for (const evidence of offeredObjects(AGENT_TOOL_DEFINITIONS[name].description)) {
const input =
name === "compose_report"
? { claims: [{ claim: "a claim", evidence: [evidence] }] }
: { change: "index", statement: "CREATE INDEX i ON t (c)", rationale: "why", evidence: [evidence] };
expect(AGENT_TOOL_DEFINITIONS[name].inputSchema.safeParse(input).success, JSON.stringify(evidence)).toBe(true);
}
});
}
test("a completed read hands over a citation the report tool will accept", async () => {
// The moment the id changes hands. The live run was HOLDING the correlation id
// it needed and still never produced the object, so naming the id is not enough:
// the text has to carry the form.
const h = harness();
const outcome = await runReadQueryTool(h.context, { sql: "SELECT id FROM orders" });
if (outcome.kind !== "completed") throw new Error(`expected a completed read, got ${outcome.kind}`);
const offered = offeredObjects(outcome.modelText);
expect(offered).toEqual([{ source: "artifact", correlationId: outcome.artifact.correlationId }]);
// And it verifies against the run's own ledger, which is the check that
// actually refuses a report.
const events: AgentRunEvent[] = [{ kind: "tool-completed", atMs: 1, stepId: "step_1", artifact: outcome.artifact }];
const report = composeReportTool(
h.context,
{ runId: h.context.runId, events },
{
claims: [{ claim: "orders has rows", evidence: offered }],
},
);
expect(report.kind).toBe("composed");
});
test("provider warnings reach the model fenced, and a result with none reads as it always did", async () => {
const warned = harness({}, async () =>
queryResult({ warnings: [{ message: "Studio read the last 100 lines of each stream." }] }),
);
const plain = harness();
const withWarnings = await runReadQueryTool(warned.context, { sql: "SELECT 1" });
const without = await runReadQueryTool(plain.context, { sql: "SELECT 1" });
expect(withWarnings.modelText).toContain("Studio read the last 100 lines of each stream.");
expect(withWarnings.modelText).toContain("warnings");
expect(without.modelText).not.toContain("warnings");
expect(without.modelText.split(UNTRUSTED_CONTENT_BEGIN)).toHaveLength(2);
});
/*
Measured 2026-10-05 on `qwen2.5:3b-instruct`, data-analysis: FIFTY-FIVE refusals in one
five-run cell, every one character for character `presentation belongs to present_answer,
send it there`. The model called `compose_report` carrying a `presentation`, was told where
that field lives, and sent the same call again - fifty-five times, until the runs ended
having reported nothing. The cell scored 0/5.
The sentence is true and it is not an instruction. It names a destination and leaves the
model to work out that there are TWO calls and which comes first. The house rule for the
difference is already written one layer down, where `present_answer` offers an id outside
`refusalExamples`: a whole worked call stays behind the lever because it crowds a small
model's turn, while a short concrete value goes to everyone, "because being told to cite
something somewhere and being handed the characters are different instructions".
An order is short. The refused tool does not have to be named - it is the one the model just
called - so this needs no new data threaded through `parseToolInput`, only the sentence
saying what to do rather than where to look.
*/
test("a misfiled field is told which call to make first, not only where the field lives", async () => {
const h = harness();
const outcome = await runReadQueryTool(h.context, { sql: "SELECT id FROM orders" });
if (outcome.kind !== "completed") throw new Error(`expected a completed read, got ${outcome.kind}`);
// The draft event belongs here: `presentableArtifact` counts a read the RUN WROTE, and without
// it this fixture is a run that read nothing it could present - which is the other test's case,
// not this one. A real `run_read_query` emits both.
const events: AgentRunEvent[] = [
{ kind: "statement-drafted", atMs: 1, stepId: "step_1", sql: "SELECT id FROM orders", rationale: "the rows" },
{ kind: "tool-completed", atMs: 2, stepId: "step_1", artifact: outcome.artifact },
];
const report = composeReportTool(
h.context,
{ runId: h.context.runId, events },
{
claims: [
{
claim: "orders has rows",
evidence: [{ source: "artifact", correlationId: outcome.artifact.correlationId }],
},
],
// The field that belongs to the other tool, exactly as the losing runs sent it.
presentation: { kind: "table" },
},
);
if (report.kind !== "unavailable") throw new Error(`expected unavailable, got ${report.kind}`);
expect(report.reasonCode).toBe("INVALID_TOOL_INPUT");
// Where it lives, as it already said.
expect(report.modelText).toContain("presentation belongs to present_answer");
// And the part the model could act on: the order of the two calls.
expect(report.modelText).toContain("call present_answer with it first");
expect(report.modelText).toContain("without it");
});
/*
Measured 2026-10-09 on `gemma4:e2b`, investigation: ONE HUNDRED AND ONE refusals in one
five-run cell, every one carrying `fingerprint: expected string, received nothing` beside
`remove correlationId`. The cell scored 0/5 and two of its runs spent seven minutes in the
loop. The same refusal appears in `laguna-xs-2.1:latest` and `devstral-small-2:24b`.
`evidenceSchema` is a discriminated union on `source`: `artifact` takes `correlationId`,
`context-snapshot` takes `fingerprint`. A model holding an artifact id that declares the wrong
`source` is validated against the snapshot branch, so it is told to delete the id it has and
supply a value it was never given a way to obtain. The remedy is neither: it is to set `source`
to the branch that takes the field it already sent.
The same defect `presentation belongs to present_answer` had, one level down. The server can see
which branch was meant - the key is in the input - and says the opposite of what would fix it.
*/
test("evidence sent under the wrong source is told which source takes the field it has", async () => {
const h = harness();
const outcome = await runReadQueryTool(h.context, { sql: "SELECT id FROM orders" });
if (outcome.kind !== "completed") throw new Error(`expected a completed read, got ${outcome.kind}`);
const events: AgentRunEvent[] = [{ kind: "tool-completed", atMs: 1, stepId: "step_1", artifact: outcome.artifact }];
const report = composeReportTool(
h.context,
{ runId: h.context.runId, events },
{
claims: [
{
claim: "orders has rows",
// The id is right and the source is wrong, exactly as the losing runs sent it.
evidence: [{ source: "context-snapshot", correlationId: outcome.artifact.correlationId }],
},
],
},
);
if (report.kind !== "unavailable") throw new Error(`expected unavailable, got ${report.kind}`);
expect(report.reasonCode).toBe("INVALID_TOOL_INPUT");
// The field it sent, and the source that takes it.
expect(report.modelText).toContain("correlationId");
expect(report.modelText).toContain('source to "artifact"');
// And NOT the instruction that loses the id it was holding.
expect(report.modelText).not.toContain("remove correlationId");
});
/*
THE ORDER IS ONLY AN INSTRUCTION WHERE THE OTHER CALL CAN SUCCEED.
`presentation belongs to present_answer - call present_answer with it first, then call this tool
again without it` was measured as a fix and shipped as one. It is now the single most frequent
refusal in the ledger: 382 deliveries, beside 188 `present_answer: ANSWER_NOT_A_DATA_READ`. The
two numbers are one loop. A run that has drafted no read has nothing presentable, so the tool it
is being sent to refuses it, and it comes back to `compose_report` with the same argument.
Measured 2026-10-11: `granite4:1b` analyze lost its one failing run to FIFTY refusals, and
`qwen2.5:3b-instruct` analyze to forty-seven, while the passing runs of the same cells finished
in seventeen to eighty-eight seconds.
`compose_report` does not need `presentation` at all. Where the run holds a presentable read the
order stands - present it, then report. Where it does not, the only move that ends the loop is to
drop the field, and saying so is the difference between an instruction and a wall.
*/
test("a field whose other tool would refuse is told to drop it, not to call that tool", async () => {
const h = harness();
// A run that read the SCHEMA only: nothing here is a data read, so `present_answer` has nothing
// it can accept - which is the shape the 188 refusals were measured on.
const schema = await inspectSchemaTool(h.context, {});
if (schema.kind !== "completed") throw new Error(`expected a completed inspect, got ${schema.kind}`);
const events: AgentRunEvent[] = [{ kind: "tool-completed", atMs: 1, stepId: "step_1", artifact: schema.artifact }];
const report = composeReportTool(
h.context,
{ runId: h.context.runId, events },
{
claims: [
{
claim: "orders is a table",
evidence: [{ source: "artifact", correlationId: schema.artifact.correlationId }],
},
],
presentation: { kind: "table" },
},
);
if (report.kind !== "unavailable") throw new Error(`expected unavailable, got ${report.kind}`);
expect(report.reasonCode).toBe("INVALID_TOOL_INPUT");
// The move that ends the loop, not the one that restarts it.
expect(report.modelText).toContain("without it");
expect(report.modelText).not.toContain("call present_answer with it first");
});
/*
THE TWO BIGGEST REFUSAL LOOPS IN THE WHOLE LEDGER, and both were type reports.
Counted across the sweep's ledger on 2026-10-09, `compose_report` refusals by exact message:
140x claims.0.evidence: expected array, received nothing
95x claims.0.evidence: expected array, received object
32x the same, on two claims at once
267 refusals, in the cell that is unlocked on fifteen of the sixteen rows in the candidate
table. `cogito:3b` was refused thirty times in one optimize cell, `qwen3.5:0.8b` twenty-two,
`gemma4:e2b` a hundred and one - and the dominant LOSS those cells record is `model-timeout`
with `no-report`, which is the consequence: the run spends its deadline re-sending a call it
was never told how to fix.
"expected array, received object" names the types and not the move. The model sent ONE citation
where a list of one belongs, which is the cheapest mistake in this contract to state a remedy
for: wrap what you sent. "received nothing" is the same shape one step earlier - the field is
required, and saying so is not the same as reporting its type.
This is the rule the file already turns on, in its own words one function down: naming what
WOULD have worked. A closed set gets its values, a refused call gets a worked example, a
misfiled field gets the order of the two calls. An array gets "wrap it".
*/
test("a single citation where a list belongs is told to wrap it, not just told the type", async () => {
const h = harness();
const outcome = await runReadQueryTool(h.context, { sql: "SELECT id FROM orders" });
if (outcome.kind !== "completed") throw new Error(`expected a completed read, got ${outcome.kind}`);
const events: AgentRunEvent[] = [{ kind: "tool-completed", atMs: 1, stepId: "step_1", artifact: outcome.artifact }];
// ONE citation object where an array of one belongs - 95 refusals in the ledger wore this shape.
const tek = composeReportTool(
h.context,
{ runId: h.context.runId, events },
{
claims: [
{
claim: "orders has rows",
evidence: { source: "artifact", correlationId: outcome.artifact.correlationId },
},
],
},
);
if (tek.kind !== "unavailable") throw new Error(`expected unavailable, got ${tek.kind}`);
expect(tek.reasonCode).toBe("INVALID_TOOL_INPUT");
expect(tek.modelText).toContain("wrap it in an array");
// And the field omitted entirely - 140 refusals, the single most common in the ledger.
const yok = composeReportTool(
h.context,
{ runId: h.context.runId, events },
{ claims: [{ claim: "orders has rows" }] },
);
if (yok.kind !== "unavailable") throw new Error(`expected unavailable, got ${yok.kind}`);
expect(yok.modelText).toContain("required");
});
/*
Measured 2026-08-16 against a real Ollama endpoint: `qwen3.8` could not finish a
data-analysis run, and the reason was an ENCODING rather than a capability. Kept as its own
group because the fix belongs to the tool's input contract and to nothing else.
*/
describe("a presentation the model serialized instead of nesting", () => {
const analysis = (over: Partial<AgentToolContext> = {}) => harness({ workflowType: "data-analysis", ...over });
/**
* A read this run took, plus the full ledger `present_answer` reads: the drafted statement
* AND the completed artifact. Every test that reaches the schema shares it deliberately,
* including the ones expecting a refusal — with a COMPLETE ledger behind them, the only thing
* left for the tool to object to is the input, so an `INVALID_TOOL_INPUT` cannot be an
* `ANSWER_STATEMENT_UNKNOWN` or an `ANSWER_ARTIFACT_UNKNOWN` wearing the assertion's colours.
*
* The table-driven passthrough cases below deliberately do NOT use it: they pass an empty
* ledger because they assert on `readSerializedPresentation`, which runs before any ledger
* guard, and a real read there would buy nothing but time.
*/
const readWithLedger = async (context: AgentToolContext) => {
const outcome = await runReadQueryTool(context, { sql: "SELECT id FROM orders" });
if (outcome.kind !== "completed") throw new Error(`expected a completed read, got ${outcome.kind}`);
const events: AgentRunEvent[] = [
{ kind: "statement-drafted", atMs: 1, stepId: "step_1", sql: "SELECT id FROM orders", rationale: "r" },
{ kind: "tool-completed", atMs: 2, stepId: "step_1", artifact: outcome.artifact },
];
return { artifact: outcome.artifact, events };
};
/*
Measured 2026-08-16: `qwen3.8` called `present_answer` three times with a correct artifact id
and a correct chart spec, and every call was refused as `INVALID_TOOL_INPUT` because it had
SERIALIZED the nested object rather than nesting it. The run reported without an answer and
was scored `no-answer`, so what a reader saw was a model that would not present — while its
own closing prose said the presentation "is being persistently rejected despite conforming to
the declared shape". It was conforming; the encoding was the only thing wrong.
*/
test("accepts a presentation the model serialized, because the content was never the problem", async () => {
const h = analysis();
const { artifact, events } = await readWithLedger(h.context);
const answer = presentAnswerTool(
h.context,
{ runId: h.context.runId, events, autoExecute: false },
{ artifact: artifact.correlationId, presentation: JSON.stringify({ kind: "table" }) },
);
if (answer.kind !== "answered") throw new Error(`expected an answer, got ${answer.kind}`);
// Asserted on the RECORDED presentation, not only on the outcome kind: the run that
// motivated this reads the presentation back out to render, so an accepted call that
// recorded something other than what the model serialized would be the same failure
// one layer later.
expect(answer.answer.presentation).toEqual({ kind: "table" });
expect(answer.answer.artifact.correlationId).toBe(artifact.correlationId);
});
test("and the report's claims, which is the same encoding on the tool that ends the run", async () => {
/*
The same fault one tool over, and by a wide margin the more expensive of the two.
`readSerializedPresentation` was written for `present_answer` after `qwen3.8` serialized a
nested object three times and was refused three times. `compose_report` takes the identical
mistake and was never given the identical read — and it is the call that ENDS a run, so a
model that makes it here does not lose a presentation, it loses everything.
Measured on `llama3.1:8b`, the most-pulled tool-capable model on Ollama: five operate runs,
**seventy** declines, every one of them the same line —
the fields that did not match — claims: expected array, received string
— with the model re-sending the serialized array roughly fourteen times per run until the
turn limit ended it. The sentence is complete and correct by then; the model reads it and
cannot act on it, which is precisely the case the sibling read exists for.
Read ONCE and never recursively, at the call boundary rather than in the schema, and the
value still goes through the same strict schema afterwards — every constraint the sibling
states applies here unchanged, including why the placement matters to the contract the SDK
advertises.
*/
const h = harness();
const outcome = await runReadQueryTool(h.context, { sql: "SELECT id FROM orders" });
if (outcome.kind !== "completed") throw new Error(`expected a completed read, got ${outcome.kind}`);
const events: AgentRunEvent[] = [
{ kind: "tool-completed", atMs: 1, stepId: "step_1", artifact: outcome.artifact },
];
const claims = [
{
claim: "orders has rows",
evidence: [{ source: "artifact", correlationId: outcome.artifact.correlationId }],
},
];
const report = composeReportTool(
h.context,
{ runId: h.context.runId, events },
{
// The array serialized, which is what the model sends.
claims: JSON.stringify(claims),
},
);
expect(report.kind).toBe("composed");
if (report.kind !== "composed") return;
expect(report.claims).toHaveLength(1);
expect(report.claims[0]?.claim).toBe("orders has rows");
});
test("text that is not JSON at all is refused in words the model can act on", async () => {
/*
The half a lenient reader cannot fix, measured on the same model and captured off the wire.
`llama3.1:8b` sends its claims as a PYTHON repr — single quotes throughout:
"[{'claim': 'The employee table is incomplete.', 'evidence': [{'source': 'artifact', …}]}]"
The content is right: the claim is true, the source is right, the correlation id is one this
run produced. Only the quote character is wrong, and `JSON.parse` refuses it. Converting the
quotes here would be inventing an encoding rather than reading one the model chose, and it
breaks on the first apostrophe inside a sentence, so this layer does not try.
What it can do is stop saying something the model has no way to act on. `claims: expected
array, received string` is true and, to a model that believes it sent an array, says
nothing — measured across five assess runs, it re-sent the identical bytes THIRTY times.
The refusal now names the fault: the argument arrived as text, and what a JSON array
requires.
*/
const h = harness();
const report = composeReportTool(
h.context,
{ runId: h.context.runId, events: [] },
{
claims: "[{'claim': 'orders has rows', 'evidence': []}]",
},
);
expect(report.kind).toBe("unavailable");
if (report.kind !== "unavailable") return;
expect(report.reasonCode).toBe("INVALID_TOOL_INPUT");
expect(report.modelText).toContain("arrived as TEXT");
expect(report.modelText).toContain("double quotes");
// The model's own text is never quoted back at it; only the fault is named.
expect(report.modelText).not.toContain("orders has rows");
});
test("a serialized claims array of the wrong shape is still refused, so the schema is not relaxed", async () => {
const h = harness();
const report = composeReportTool(
h.context,
{ runId: h.context.runId, events: [] },
{
// Valid JSON, wrong shape: the read admits nothing the object form would not have been.
claims: JSON.stringify([{ text: "orders has rows" }]),
},
);
expect(report.kind).toBe("unavailable");
if (report.kind !== "unavailable") return;
expect(report.reasonCode).toBe("INVALID_TOOL_INPUT");
});
test("the id under a near-miss key is read, so what is left to say is one field and not two", async () => {
/*
Captured 2026-09-17: five of seventeen refusals across the two failing surfaces are
`{"artifact_id": "669cc394-..."}` - the id right, the key one affix off, `presentation`
genuinely absent. `renamesAmong` has NAMED this pair in the refusal since #4xx, and the
models kept re-sending the same key; on `llama3.1:8b` it declined all five analyze runs and
never once on the value it carried.
Naming it left the model two sentences for one mistake and one real omission, and the repair
that suggests itself from two sentences is to send the surplus field again with more of it.
Reading the key leaves exactly one sentence, about the one thing actually missing.
Answered here since 2026-09-19. It was refused when this test was written, on the argument
that supplying the missing `presentation` would be the server choosing how the answer is
displayed. Ninety-three more refusals of exactly this call, across the two models whose
analyze cells sat at 0/5, retired that argument: see `readMisrenderedPresentation`. Both
halves are now read - the key and the absent rendering - and what the test still pins is
that the ID SURVIVES the rename.
*/
const h = analysis();
const { artifact, events } = await readWithLedger(h.context);
const answer = presentAnswerTool(
h.context,
{ runId: h.context.runId, events, autoExecute: false },
{ artifact_id: artifact.correlationId },
);
if (answer.kind !== "answered") throw new Error(`expected the answer to be presented, got ${answer.kind}`);
expect(answer.answer.artifact.correlationId).toBe(artifact.correlationId);
expect(answer.answer.presentation).toEqual({ kind: "table" });
});
/*
The two shapes that were holding `present_answer` shut, measured 2026-09-19 with the argument
capture running for a whole sweep: 206 of 221 refused calls, and both belong to the two models
whose `data-analysis` cell sits at 0/5.
Neither is a model failing to do the work. Both are runs that read the data, produced the
artifact, and then could not say how to show it.
*/
test("a spec attached to a table is dropped, because the model already said table", async () => {
/*
113 refusals, all `phi4-mini:3.8b`, all this:
{"kind": "table", "spec": {"x": "total_rows", "y": 9488, "caption": "Total rows"}}
The spec is not a chart and could not become one - no `type`, and `y` is a number where a
list of column names goes. It is a caption the model wanted to attach to a table. The schema
says a table takes no spec, which is true, and the refusal says `remove spec`, which the
model did not do 113 times.
So it is removed here. `kind` is explicit and `table` is what the contract itself calls a
complete answer; a surplus decoration is not a reason to throw the answer away.
*/
const h = analysis();
const { artifact, events } = await readWithLedger(h.context);
const answer = presentAnswerTool(h.context, { runId: h.context.runId, events, autoExecute: false }, {
artifact: artifact.correlationId,
presentation: { kind: "table", spec: { x: "total_rows", y: 9488, caption: "Total rows" } },
} as never);
if (answer.kind !== "answered") throw new Error(`expected the answer to be presented, got ${answer.kind}`);
expect(answer.answer.presentation).toEqual({ kind: "table" });
});
test("and the result inlined into the table is dropped too, because the artifact already holds it", async () => {
/*
The same surplus wearing three more names, 47 refusals in one sweep:
{"kind":"table","data":{"dept_name":"Sales","total_salary":12500000}} 17
{"kind":"table","rows":[{"dept_name":"Development", ...}]} 16
{"kind":"table","columns":[{"name":"dept_name","value":"Development"}]} 14
The model is pasting the RESULT into the presentation. It has no reason to: the artifact id
beside it already names the rows, and `presentation` only ever says how to show them. The
first version of this reader dropped `spec` by name and left these three, which is the
mistake a by-name list always makes - so a table now keeps `kind` and nothing else.
Safe precisely because a table takes no options at all. A CHART is left alone: its `spec` is
the whole instruction, and dropping an unknown key there could silently change the picture.
*/
const h = analysis();
const { artifact, events } = await readWithLedger(h.context);
const answer = presentAnswerTool(h.context, { runId: h.context.runId, events, autoExecute: false }, {
artifact: artifact.correlationId,
presentation: { kind: "table", rows: [{ dept_name: "Development", total_salary: 155098748 }] },