-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathREDCapAgentRecordTools.php
More file actions
2837 lines (2638 loc) · 128 KB
/
Copy pathREDCapAgentRecordTools.php
File metadata and controls
2837 lines (2638 loc) · 128 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
<?php
namespace Stanford\REDCapAgentRecordTools;
require_once "emLoggerTrait.php";
require_once "classes/PhiFieldPreHook.php";
class REDCapAgentRecordTools extends \ExternalModules\AbstractExternalModule {
use emLoggerTrait;
// No hard cap on records.search results — REDCap itself doesn't cap, and
// the full result set is always cached server-side regardless. This is
// just the DEFAULT page size; past ~500 records the response notes steer
// the agent toward suggesting the user narrow their filter or use
// records.aggregate for "across the whole dataset" questions.
const MAX_RECORDS_RETURNED = 500;
// Byte budget for the one big list-or-map payload in a tool response
// (getMetadata's 'fields', records.get's 'values').
//
// WHY WE SELF-LIMIT: SecureChatAI caps each tool result and its object
// branch drops an oversized key WHOLESALE rather than shortening it — so an
// unscoped getMetadata on any real project used to return the field COUNT
// and nothing else. Trimming here instead means the caller gets a labelled
// partial payload plus an accurate count of what was cut.
//
// COUPLED TO SecureChatAI's `agent_max_tool_result_chars` (default 8000).
// This must stay comfortably below it: the difference covers our wrapper
// keys and the ~700-char explanatory note. If that setting is raised (16k,
// 24k) this can rise with it to return more per call; if it is lowered
// below ~7000 this MUST come down too, or the outer cap starts nuking
// payloads wholesale again — the exact failure this constant exists to
// prevent. Not read directly: that would couple this EM to SecureChatAI's
// settings, which the repo guardrails forbid without explicit instruction.
const CAPPY_PAYLOAD_BUDGET = 6000;
// Field labels can hold entire HTML blocks (descriptive fields). Capped in
// the slim view only; a scoped call returns labels in full.
const CAPPY_METADATA_LABEL_MAX = 120;
public function __construct()
{
parent::__construct();
}
/**
* Tool Router — redcap_module_api()
*
* Standard REDCap hook — entry point for all tool calls.
* Called by SecureChatAI via EM-to-EM:
* getModuleInstance($prefix)->redcap_module_api($action, $payload)
* Also callable externally via the REDCap API:
* POST /api/ ... content=externalModule&prefix=...&action=...
*
* ⚠️ SECURITY — KNOWN CRITICAL ISSUE (deferred):
* This endpoint performs ZERO authorization. Any REDCap API token
* (or EM-to-EM call from a compromised context) can invoke any action
* with any pid, regardless of whether the caller has rights to that
* project. Today the risk surface is contained because:
* 1. This EM is not exposed via the public REDCap API
* (auth-ajax-actions in config.json is empty), and
* 2. The chatbot EM's CappyScopePreHook enforces pid scope inside
* SecureChatAI's agent loop.
* Neither of these is a substitute for real per-pid authorization
* inside routeToolCall. If either of those mitigations is removed
* (auth-ajax-actions added, or SecureChatAI's hook registry edited),
* any authenticated caller can read/write any project's data.
* Fix tracked in CLAUDE.md "Security — known issues" section.
*/
public function redcap_module_api($action = null, $payload = [])
{
// PHI-safe: log action name and payload shape only — never the payload
// contents (which can contain record data, filters with patient info).
$this->emDebug("Agent tool call", [
'action' => $action,
'payload_keys' => is_array($payload) ? array_keys($payload) : [],
'has_filter' => !empty($payload['filter']),
]);
$response = $this->routeToolCall($action, $payload);
// PHI-safe: log response shape only. Full responses (which can contain
// preview_markdown with record IDs, or raw records when include_records)
// are never written to the log.
$isError = !empty($response['error']);
$logEntry = [
'action' => $action,
'response_keys' => is_array($response) ? array_keys($response) : [],
'has_error' => $isError,
'total_record_count' => $response['total_record_count'] ?? null,
'value_count' => $response['value_count'] ?? null,
];
// On failure, log WHY. Every error string in this file is a fixed,
// developer-authored diagnostic ("Reference ref_x not found or expired",
// "Missing required parameter: pid") — no record data, so it's safe here and
// it's the difference between "a tool failed" and a usable answer. Without
// it, has_error=1 was all we had, and diagnosing a failed turn meant
// guessing which of a dozen error branches fired.
if ($isError && isset($response['message'])) {
$logEntry['error_message'] = (string)$response['message'];
}
$this->emDebug("Agent tool response", $logEntry);
return $response;
}
private function routeToolCall($action, $payload)
{
switch ($action) {
case "projects_getMetadata":
return $this->toolGetMetadata($payload);
case "projects_getInstruments":
return $this->toolGetInstruments($payload);
case "records_get":
return $this->toolGetRecord($payload);
case "records_search":
return $this->toolSearchRecords($payload);
case "records_count":
return $this->toolCountRecords($payload);
case "records_aggregate":
return $this->toolAggregateRecords($payload);
case "records_listIds":
return $this->toolListRecordIds($payload);
case "survey_getLink":
return $this->toolGetSurveyLink($payload);
case "records_evaluateLogic":
return $this->toolEvaluateLogic($payload);
case "projects_search":
return $this->toolSearchProjects($payload);
// WRITE DISABLED 2026-08-24: "records_save" intentionally has NO case here, so
// it falls through to default ("Unknown action"). Guarantees no record writes
// via Cappy pending real per-pid authorization (see redcap_module_api() docblock
// above). Also pulled from tools.json and config.json api-actions; toolSaveRecords()
// is a third, independent gate. Restore via git history, not by re-adding a case.
default:
return [
"error" => true,
"message" => "Unknown action: $action"
];
}
}
/**
* Tool 1: projects.getMetadata
* Get data dictionary (field definitions) for a project
*/
public function toolGetMetadata(array $payload)
{
if (empty($payload['pid'])) {
return [
"error" => true,
"message" => "Missing required parameter: pid"
];
}
$pid = (int)$payload['pid'];
$fields = $payload['fields'] ?? null; // Optional: specific fields only
// Did the caller name the fields it wants? That's the path that can
// afford the full per-field shape (choices, validation, branching).
$scoped = is_array($fields) && !empty($fields);
try {
// Get full data dictionary
$metadata = \REDCap::getDataDictionary($pid, 'array', false, $fields);
if (empty($metadata)) {
return [
"error" => true,
"message" => "No metadata found for project $pid (may not exist or no access)"
];
}
// Convert to array of field objects for easier agent consumption.
// Unscoped calls get a SLIM shape: on a 189-field project the full
// shape is ~55KB and the slim one is still ~36KB, so neither fits
// the tool-result cap — but the slim rows at least degrade to a
// useful partial list instead of being dropped en masse.
$fields_array = [];
foreach ($metadata as $field_name => $field_info) {
$row = [
'field_name' => $field_name,
'form_name' => $field_info['form_name'] ?? null,
'field_type' => $field_info['field_type'] ?? null,
'field_label' => $scoped
? ($field_info['field_label'] ?? null)
: $this->cappyTruncate((string)($field_info['field_label'] ?? ''), self::CAPPY_METADATA_LABEL_MAX),
];
if ($scoped) {
$row['select_choices_or_calculations'] = $field_info['select_choices_or_calculations'] ?? null;
$row['required_field'] = $field_info['required_field'] ?? null;
$row['text_validation_type_or_show_slider_number'] = $field_info['text_validation_type_or_show_slider_number'] ?? null;
$row['branching_logic'] = $field_info['branching_logic'] ?? null;
}
$fields_array[] = $row;
}
$total = count($fields_array);
[$kept, $dropped] = $this->cappyFitRows($fields_array, self::CAPPY_PAYLOAD_BUDGET);
// Build the note from what actually happened, so it never claims a
// truncation that didn't occur or stays silent about one that did.
$note = [];
if (!$scoped) {
$note[] = "SLIM VIEW: choices, validation and branching logic are omitted. "
. "To get the answer choices for a coded field (needed to turn a stored "
. "code into a label), call this tool again with fields=[\"field_a\",\"field_b\"] "
. "— a scoped call returns the full definition and fits comfortably.";
}
if ($dropped > 0) {
$note[] = "Returned " . count($kept) . " of $total fields; $dropped omitted to fit the "
. "token budget. This is NOT the whole dictionary — do not conclude a field is "
. "absent from the project because it is missing here. Request specific fields by "
. "name via the 'fields' parameter instead of re-requesting everything.";
}
if ($scoped) {
$note[] = "Coded fields: 'select_choices_or_calculations' holds the "
. "code,label pairs. Note that records.get already returns values with "
. "labels resolved, so you rarely need to map codes by hand.";
}
// Key order matters: SecureChatAI's cap drops trailing keys, so the
// counts and note must precede the (much larger) field list.
return [
"pid" => $pid,
"field_count" => $total,
"returned_field_count" => count($kept),
"view" => $scoped ? "full" : "slim",
"note" => implode(' ', $note),
"fields" => $kept,
];
} catch (\Exception $e) {
$this->emError("getMetadata error for pid $pid: " . $e->getMessage());
return [
"error" => true,
"message" => "Failed to retrieve metadata: " . $e->getMessage()
];
}
}
/**
* Tool 4: projects.getInstruments
* List all instruments/forms in a project
*/
public function toolGetInstruments(array $payload)
{
if (empty($payload['pid'])) {
return [
"error" => true,
"message" => "Missing required parameter: pid"
];
}
$pid = (int)$payload['pid'];
try {
// Returns ['instrument_name' => 'Instrument Label', ...]
$instruments = \REDCap::getInstrumentNames(null, $pid);
if (empty($instruments)) {
return [
"error" => true,
"message" => "No instruments found for project $pid"
];
}
// Convert to array of objects
$instruments_array = [];
foreach ($instruments as $name => $label) {
$instruments_array[] = [
'instrument_name' => $name,
'instrument_label' => $label
];
}
return [
"pid" => $pid,
"instrument_count" => count($instruments_array),
"instruments" => $instruments_array
];
} catch (\Exception $e) {
$this->emError("getInstruments error for pid $pid: " . $e->getMessage());
return [
"error" => true,
"message" => "Failed to retrieve instruments: " . $e->getMessage()
];
}
}
/**
* Tool 5: records.get
* Get specific record data by record ID.
*
* Returns 'values': the record with every coded field ALREADY RESOLVED to
* its choice label, and empty fields omitted. Raw getData output is
* withheld unless include_raw=true.
*
* Why the labeled view is the default (and the raw one is not):
* getData('array') returns codes, and for checkbox fields it returns one
* key per option whether checked or not. On PID 70, record 1 came back as
* ~21KB — over SecureChatAI's 8000-char tool-result cap, whose object
* branch drops an oversized key WHOLESALE, so 'data' vanished and the model
* got nothing at all. When it narrowed to fields=['d_spoken_language'] it
* received 141 keys of `code => '0'|'1'` and knew code 5 was checked but
* not that 5 means "Mixteco Bajo" — so it asked the USER for the mapping.
* Resolving server-side kills that round-trip and shrinks the payload at
* the same time: 141 mostly-zero keys collapse into one string of labels.
*/
public function toolGetRecord(array $payload)
{
if (empty($payload['pid'])) {
return [
"error" => true,
"message" => "Missing required parameter: pid"
];
}
if (empty($payload['record_id'])) {
return [
"error" => true,
"message" => "Missing required parameter: record_id"
];
}
$pid = (int)$payload['pid'];
$record_id = $payload['record_id'];
$fields = $payload['fields'] ?? null; // Optional
$events = $payload['events'] ?? null; // Optional (for longitudinal)
$includeRaw = !empty($payload['include_raw']);
try {
$data = \REDCap::getData($pid, 'array', [$record_id], $fields, $events);
if (empty($data)) {
return [
"error" => true,
"message" => "No data found for record '$record_id' in project $pid"
];
}
// Walk getData's nested shape ourselves rather than reusing
// cappyFlattenRows(): that helper discards event and instance
// identity, which is fine for a preview table but would leave the
// model unable to say WHICH visit or instance a value came from on
// a longitudinal or repeating project — trading the code/label
// round-trip we're fixing for a "which visit did you mean?" one.
$eventNames = [];
$longitudinal = false;
try {
$projObj = new \Project($pid);
$longitudinal = !empty($projObj->longitudinal);
if ($longitudinal) $eventNames = $projObj->getUniqueEventNames();
} catch (\Exception $e) {
// Best effort: fall back to bare event ids below.
}
$rawRows = [];
foreach ($data as $events) {
if (!is_array($events)) continue;
foreach ($events as $eventId => $eventData) {
if ($eventId === 'repeat_instances' || !is_array($eventData)) continue;
$rawRows[] = [
$this->cappyRowContext($longitudinal, $eventNames, $eventId, null, null),
$eventData,
];
}
if (isset($events['repeat_instances']) && is_array($events['repeat_instances'])) {
foreach ($events['repeat_instances'] as $eventId => $instruments) {
if (!is_array($instruments)) continue;
foreach ($instruments as $instrument => $instances) {
if (!is_array($instances)) continue;
foreach ($instances as $instance => $rowFields) {
if (!is_array($rowFields)) continue;
$rawRows[] = [
$this->cappyRowContext($longitudinal, $eventNames, $eventId, $instrument, $instance),
$rowFields,
];
}
}
}
}
}
// Resolve labels for the fields actually present, not the whole
// dictionary — a scoped getDataDictionary call is much cheaper on
// wide projects.
$present = [];
foreach ($rawRows as [, $rowFields]) {
foreach (array_keys($rowFields) as $f) $present[$f] = true;
}
$choiceMaps = $this->cappyChoiceMaps($pid, array_keys($present));
$emptyOmitted = 0;
$built = [];
foreach ($rawRows as [$ctx, $rowFields]) {
$out = [];
foreach ($rowFields as $field => $val) {
$resolved = $this->cappyLabelValue($choiceMaps[$field] ?? [], $val);
// Blank fields are the bulk of a wide record and are almost
// never the question. Omitted, but COUNTED — see the note.
if ($resolved === '') { $emptyOmitted++; continue; }
$out[$field] = $resolved;
}
$built[] = ['ctx' => $ctx, 'fields' => $out];
}
// Drop rows that came back entirely empty, but never return zero
// rows for a record that exists — keep one so the caller can tell
// "record found, all blank" from "record not found".
$withData = array_values(array_filter($built, fn($b) => !empty($b['fields'])));
$use = !empty($withData) ? $withData : array_slice($built, 0, 1);
// Trim to fit rather than letting the outer cap drop 'values'
// entirely. Without this a wide record (PID 70 record 1 is ~14KB
// even after label collapsing) loses the whole payload, and the
// model then receives BOTH our note saying "call again with
// fields=[...]" and SecureChatAI's generic "do not retry" — a
// direct contradiction on the one path that most needs to be clear.
[$use, $sizeOmitted] = $this->cappyFitRecordRows($use, self::CAPPY_PAYLOAD_BUDGET);
// Shape decision, made ONCE for the whole response so every row
// looks the same. A record with one plain event row plus three
// repeating instances would otherwise mix a flat field map (row 0,
// which has no context keys) with wrapped rows — the kind of
// heterogeneous list that invites the model to misread it.
// getData returned something we couldn't walk into rows at all.
// Guarded explicitly: $use[0] below would throw on an empty list.
$useWrapper = count($use) > 1 || !empty($use[0]['ctx']);
if (empty($use)) {
$values = [];
} elseif ($useWrapper) {
$values = array_map(fn($b) => $b['ctx'] + ['fields' => $b['fields']], $use);
} else {
// The common classic-project case (a single non-repeating row)
// collapses to a flat field => value map so the model doesn't
// have to reach through a pointless wrapper.
$values = $use[0]['fields'];
}
// Key order matters: SecureChatAI's cap drops trailing keys, so the
// note (which tells the model how to recover) must land BEFORE the
// payload that might not fit, and raw data goes last.
$response = [
"pid" => $pid,
"record_id" => $record_id,
"row_count" => count($use),
"empty_fields_omitted" => $emptyOmitted,
"fields_omitted_for_size" => $sizeOmitted,
"note" => "'values' holds this record with all coded fields ALREADY "
. "RESOLVED to their choice labels (checkbox fields list the checked "
. "labels, comma-joined). Report those labels to the user as-is — do "
. "NOT translate codes yourself and NEVER ask the user for a code-to-label "
. "mapping; it is already applied here. Empty fields are omitted. "
. ($useWrapper
? "This record has multiple rows (longitudinal events and/or repeating "
. "instrument instances), so 'values' is a LIST: each entry has its "
. "field values under 'fields', plus 'event'/'instrument'/'instance' "
. "identifying where those values live. A row with no 'instrument' is "
. "the non-repeating data for that event. "
: "'values' is a flat field => value map. ")
. ($sizeOmitted > 0
? "NOT ALL FIELDS ARE HERE: $sizeOmitted more had values but were cut to "
. "fit the token budget (fields come in form order, so the tail is "
. "missing). If what you need isn't above, call again with "
. "fields=[...] naming it — that returns it reliably. Do not tell the "
. "user a field is empty just because it is absent here. "
: "")
. "Pass include_raw=true only when you need underlying codes for "
. "computation."
. ($includeRaw ? "" : " Raw getData output withheld by default."),
"values" => $values,
];
if ($includeRaw) {
$response["data"] = $data;
}
return $response;
} catch (\Exception $e) {
$this->emError("getRecord error for pid $pid, record $record_id: " . $e->getMessage());
return [
"error" => true,
"message" => "Failed to retrieve record: " . $e->getMessage()
];
}
}
/**
* Tool 6: records.search
* Search records with optional REDCap logic filter
*/
public function toolSearchRecords(array $payload)
{
if (empty($payload['pid'])) {
return [
"error" => true,
"message" => "Missing required parameter: pid"
];
}
$pid = (int)$payload['pid'];
$filter = $payload['filter'] ?? null; // REDCap logic string like "[age] > 18"
// Validate filter field names against the data dictionary — a typo'd
// field silently returns 0 records and sends the agent flailing.
// Return a hard error with close-match suggestions instead.
if (!empty($filter)) {
$fieldError = $this->cappyValidateFilterFields($pid, $filter);
if ($fieldError !== null) return $fieldError;
}
// Expand any label literals in the filter to (code OR label) so the
// agent can write [d_legal_sex] = "Female" and still match the 2-codes.
// Nerds who already use the code get a no-op expansion.
$filterExpansions = [];
$filterHints = [];
if (!empty($filter)) {
$expanded = $this->cappyExpandFilterLabels($pid, $filter);
$filter = $expanded['filter'];
$filterExpansions = $expanded['translations'];
$filterHints = $expanded['hints'] ?? [];
}
$fields = $payload['fields'] ?? null; // Optional
// DISPLAY columns only — deliberately separate from 'fields'.
// 'fields' narrows what gets FETCHED and therefore what lands in the
// session cache, so narrowing it breaks in-memory follow-up filtering
// (reference + new filter). 'columns' leaves the cache full-width and
// only steers which columns preview_markdown shows.
$columns = $payload['columns'] ?? null;
// Models sometimes send a bare string for a single column, or a
// comma-joined string. Accept both rather than dropping the request.
if (is_string($columns)) {
$columns = array_filter(array_map('trim', explode(',', $columns)), 'strlen');
}
if (is_array($columns)) {
$columns = array_values(array_filter(array_map('strval', $columns), 'strlen'));
}
// An explicitly EMPTY columns list means "go back to auto-picked
// columns". Without this there is no way to undo a previous choice,
// because a cached set inherits its columns (see the reference and
// append paths below) and an omitted param means "inherit".
$columnsReset = array_key_exists('columns', $payload) && is_array($columns) && empty($columns);
if (!is_array($columns) || empty($columns)) $columns = null;
// Same treatment the filter gets: a typo'd column name is reported with
// ranked suggestions so the model can retry, instead of yielding a table
// that quietly lacks the column the user asked for.
if ($columns !== null) {
$colError = $this->cappyValidateFieldNames($pid, $columns, 'columns');
if ($colError !== null) return $colError;
}
// 'columns' is display-only, but it can only display what was FETCHED.
// When the caller also scoped 'fields', a requested column outside that
// scope would be absent from the rows and silently dropped from the
// table — so widen the fetch to cover it. Harmless when 'fields' is
// omitted, since that already fetches everything.
if ($columns !== null && is_array($fields) && !empty($fields)) {
$fields = array_values(array_unique(array_merge($fields, $columns)));
}
$return_format = $payload['return_format'] ?? 'array'; // 'array' or 'json'
$offset = max(0, (int)($payload['offset'] ?? 0));
// No upper clamp — caller may request as many as they want (default
// page size is MAX_RECORDS_RETURNED). The note flags large result
// sets so the agent can suggest narrowing instead of paging forever.
$limit = (int)($payload['limit'] ?? self::MAX_RECORDS_RETURNED);
if ($limit <= 0) {
$limit = self::MAX_RECORDS_RETURNED;
}
// Raw rows are withheld by default — the LLM gets preview_markdown for
// display and a reference for filtering/paging. Inlining hundreds of
// full-width records bloats the context window and makes models
// refuse to render ("due to space limits..."). Set include_records
// only when the raw rows are genuinely needed for computation.
$includeRecords = !empty($payload['include_records']);
$formatRecords = function ($page) use ($return_format, $includeRecords) {
if (!$includeRecords) return [];
return $return_format === 'json' ? json_encode($page) : $page;
};
// What we tell the model about raw rows MUST depend on whether it already
// asked for them. The old note said "rows are withheld, pass
// include_records=true" unconditionally — including to a caller that had
// just passed exactly that. Combined with SecureChatAI's result cap (which
// drops trailing keys, and `records` is the last key), the model got a
// response with `records` amputated plus an instruction to ask again. It
// obliged, repeatedly, until the loop detector killed the turn. Observed on
// PID 70: a 182,943-char result against an 8,000-char cap, five times.
$rawRowsHint = $includeRecords
? "You requested raw rows, so they are in 'records' IF they fit. If 'records' "
. "is missing or the result reports itself truncated, the rows did NOT fit "
. "the token budget — do NOT request them again, and do NOT retry with a "
. "smaller 'limit': what usually overflows is the WIDTH of each record (a "
. "checkbox field with many options costs over a kilobyte per record), so "
. "fewer records truncates the same way. Instead pass 'fields' to ask for "
. "only the columns you actually need, or answer from 'preview_markdown'."
: "Raw rows are withheld by default; pass include_records=true only if you need them for computation.";
// Append path: run the new filter as a fresh query, then UNION the
// results into the referenced cached recordset (the "accumulating
// working set" — e.g. severity=3 set, then "also severity=4" merges
// into one 532-record set). Only the new slice hits the database.
$appendTo = $payload['append_to'] ?? null;
$appendBase = null;
if ($appendTo) {
$appendBase = $this->cappyCacheFetch($appendTo, 'records_search');
if ($appendBase === null) {
return [
"error" => true,
"message" => "append_to reference $appendTo not found or expired. Call the tool again without 'append_to' to start a new query."
];
}
if (($appendBase['pid'] ?? null) !== $pid) {
return [
"error" => true,
"message" => "append_to reference $appendTo was cached for a different project."
];
}
// Same reasoning as the reference path: "also severity 4" should not
// silently reshape the table the user is already looking at.
if ($columns === null && !$columnsReset && !empty($appendBase['columns']) && is_array($appendBase['columns'])) {
$columns = $appendBase['columns'];
}
}
// Reference path: reuse the PHP session cache instead of re-querying.
// Two modes:
// 1. reference + same/no filter → page through the cached recordset
// 2. reference + NEW filter → apply the filter against the cached
// recordset in memory (evaluateLogic with inline record_data, no
// getData round trip), cache the subset under a new reference
$reference = $payload['reference'] ?? null;
if ($reference) {
$cached = $this->cappyCacheFetch($reference, 'records_search');
if ($cached === null) {
return [
"error" => true,
"message" => "Reference $reference not found or expired. Call the tool again without 'reference' to re-query."
];
}
if (($cached['pid'] ?? null) !== $pid) {
return [
"error" => true,
"message" => "Reference $reference was cached for a different project (expected $pid, got " . ($cached['pid'] ?? 'null') . ")."
];
}
$data = $cached['ids'];
$cachedFilter = trim((string)($cached['filter'] ?? ''));
$newFilter = trim((string)($filter ?? ''));
$filteredFromCache = false;
// Inherit the display columns chosen when this set was first built,
// unless this call names its own. Without this, paging silently
// changes the table's shape: the UI's prev/next handler
// (REDCapChatBot::cappyPage) calls records_search with only
// reference/offset/limit, so page 2 would fall back to the
// auto-ranked columns and re-introduce the very name/DOB/MRN
// columns page 1 was asked to leave out.
if ($columns === null && !$columnsReset && !empty($cached['columns']) && is_array($cached['columns'])) {
$columns = $cached['columns'];
}
// Mode 2: new filter → narrow the cached recordset in memory
if ($newFilter !== '' && $newFilter !== $cachedFilter) {
$data = $this->cappyFilterCachedRecords($pid, $data, $newFilter);
$filteredFromCache = true;
// Cache the narrowed subset so follow-ups can chain off it
$reference = $this->cappyCacheStore('records_search', [
'pid' => $pid,
'filter' => $newFilter,
'ids' => $data,
'columns' => $columns,
]);
}
$total = count($data);
$page = array_slice($data, $offset, $limit, true);
$returned_count = count($page);
$activeFilter = $filteredFromCache ? $newFilter : $cachedFilter;
// Key order matters: SecureChatAI caps oversized tool results by
// dropping trailing keys — preview_markdown/note MUST come before
// the (potentially huge) records payload or they get amputated.
$largeSetNote = $total > self::MAX_RECORDS_RETURNED
? " LARGE RESULT SET ($total records) — rather than paging through all of them, suggest the user narrow their search with a more specific filter (pass reference + new filter to narrow in memory)."
: "";
$result = [
"pid" => $pid,
"filter" => $activeFilter,
"reference" => $reference,
"total_record_count" => $total,
"returned_count" => $returned_count,
"offset" => $offset,
"limit" => $limit,
"truncated" => ($offset + $returned_count) < $total,
"preview_markdown" => $this->cappyBuildPreview($pid, $page, $activeFilter, 20, 8, $columns),
"note" => ($filteredFromCache
? "Filtered from the cached recordset in memory (no database re-query). Subset cached as $reference — pass it back with a new filter to narrow further, or with offset/limit to page. "
: "Served from session cache (reference $reference). ")
. "IMPORTANT: render 'preview_markdown' to the user VERBATIM as a markdown table — do not ask which fields to show, do not summarize instead of showing. "
. $rawRowsHint
. $largeSetNote,
"records" => $formatRecords($page),
];
return $result;
}
try {
// Always fetch as 'array' internally so we can slice by record for pagination;
// converted to the requested return_format after slicing.
$data = \REDCap::getData(
$pid,
'array',
null, // all matching records (filter applied via $filterLogic)
$fields,
null, // events
null, // groups
false, // combine checkbox values
false, // DAG
false, // survey fields
$filter // REDCap logic filter
);
$total_record_count = is_array($data) ? count($data) : 0;
// Append mode: union the freshly-queried slice into the referenced
// cached recordset. Fresh rows win on duplicate record IDs.
$mergedFrom = null;
if ($appendBase !== null) {
$baseCount = count($appendBase['ids']);
$newCount = $total_record_count;
$data = array_replace($appendBase['ids'], is_array($data) ? $data : []);
$total_record_count = count($data);
$mergedFrom = [
'base_count' => $baseCount,
'new_count' => $newCount,
'added_count' => $total_record_count - $baseCount,
'base_filter' => $appendBase['filter'] ?? null,
];
}
// Always cache the full result set so follow-up questions can filter
// or page within it without another getData round trip.
$ref = $this->cappyCacheStore('records_search', [
'pid' => $pid,
'filter' => $mergedFrom
? "(" . ($mergedFrom['base_filter'] ?? '') . ") OR (" . ($filter ?? '') . ")"
: $filter,
'ids' => $data,
// Remembered so prev/next page turns keep the same columns.
'columns' => $columns,
]);
$page = is_array($data) ? array_slice($data, $offset, $limit, true) : [];
$returned_count = count($page);
$truncated = ($offset + $returned_count) < $total_record_count;
// Key order matters: SecureChatAI caps oversized tool results by
// dropping trailing keys — preview_markdown/note/message MUST come
// before the (potentially huge) records payload.
$result = [
"pid" => $pid,
"filter" => $filter,
"filter_translations" => $filterExpansions,
// Present only when a filter literal is not a choice of the
// field it was compared against but IS a choice elsewhere —
// turns a true-but-useless 0 into a legible wrong-field hint.
"value_not_on_this_field" => $filterHints,
"reference" => $ref,
"total_record_count" => $total_record_count,
"returned_count" => $returned_count,
"offset" => $offset,
"limit" => $limit,
"truncated" => $truncated,
"preview_markdown" => $this->cappyBuildPreview($pid, $page, $filter, 20, 8, $columns),
"note" => ($mergedFrom
? "APPENDED to the cached working set: {$mergedFrom['new_count']} records matched the new filter, {$mergedFrom['added_count']} were new — merged set is now $total_record_count records (was {$mergedFrom['base_count']}), cached as \"$ref\". The accumulated set is what the user now means by 'the records' — narrow it with reference + new filter, or append more with append_to + new filter. "
: "")
. "IMPORTANT: render 'preview_markdown' to the user VERBATIM as a markdown table — do not ask which fields to show, do not summarize instead of showing. "
. $rawRowsHint
// Be explicit that paging yields the next PREVIEW page, not
// raw rows. Sitting next to the "don't retry with a smaller
// limit" warning above, an unqualified "page with
// offset/limit" reads as permission to keep re-requesting
// rows — which is the loop this note exists to prevent.
. " The full result set is cached as reference \"$ref\" — pass it with offset/limit to get the NEXT PAGE OF preview_markdown (paging does not make withheld raw rows fit), or with a new filter to narrow.",
"records" => $formatRecords($page),
];
if ($truncated) {
// Insert BEFORE records — appended keys get amputated by the
// SecureChatAI result-size cap when records is large.
$pagingMsg = "Showing $returned_count of $total_record_count matching records "
. "(offset $offset). The FULL result set is cached server-side as reference \"$ref\" "
. "(expires in " . (self::CAPPY_CACHE_TTL / 60) . " minutes). For follow-up questions: "
. "pass reference=\"$ref\" with a NEW 'filter' to narrow within this recordset without "
. "re-querying the database, or pass reference + offset/limit to page through it."
. ($total_record_count > self::MAX_RECORDS_RETURNED
? " LARGE RESULT SET ($total_record_count records) — rather than paging through all of them, suggest the user narrow their search with a more specific filter."
: "");
$recordsVal = $result['records'];
unset($result['records']);
$result['message'] = $pagingMsg;
$result['records'] = $recordsVal;
}
return $result;
} catch (\Exception $e) {
$this->emError("searchRecords error for pid $pid: " . $e->getMessage());
return [
"error" => true,
"message" => "Failed to search records: " . $e->getMessage()
];
}
}
/**
* Tool 6b: records.count
* Return only the count of records matching an optional REDCap logic filter.
* No record data is fetched — single cheap call.
*/
public function toolCountRecords(array $payload)
{
if (empty($payload['pid'])) {
return [
"error" => true,
"message" => "Missing required parameter: pid"
];
}
$pid = (int)$payload['pid'];
$filter = $payload['filter'] ?? null;
if (!empty($filter)) {
$fieldError = $this->cappyValidateFilterFields($pid, $filter);
if ($fieldError !== null) return $fieldError;
}
// Expand any label literals in the filter to (code OR label) — same as
// toolSearchRecords so [d_legal_sex] = "Female" still matches code 2.
$filterExpansions = [];
$filterHints = [];
if (!empty($filter)) {
$expanded = $this->cappyExpandFilterLabels($pid, $filter);
$filter = $expanded['filter'];
$filterExpansions = $expanded['translations'];
$filterHints = $expanded['hints'] ?? [];
}
try {
$data = \REDCap::getData(
$pid,
'array',
null, // all matching records
null, // no fields needed — we only count
null, // events
null, // groups
false, // combine checkbox values
false, // DAG
false, // survey fields
$filter // REDCap logic filter
);
$count = is_array($data) ? count($data) : 0;
$recordIdField = \REDCap::getRecordIdField($pid);
return [
"pid" => $pid,
"filter" => $filter,
"filter_translations" => $filterExpansions,
// Present only when a filter literal is not a choice of the
// field it was compared against but IS a choice elsewhere —
// turns a true-but-useless 0 into a legible wrong-field hint.
"value_not_on_this_field" => $filterHints,
"count" => $count,
"record_id_field" => $recordIdField,
"note" => "This is the count of records matching the filter (or all records if no filter). No record data was returned."
];
} catch (\Exception $e) {
$this->emError("countRecords error for pid $pid: " . $e->getMessage());
return [
"error" => true,
"message" => "Failed to count records: " . $e->getMessage()
];
}
}
/**
* Tool 6c: records.listIds
* Return just the record IDs in a project (no field data). Useful when
* the user wants to enumerate record IDs without pulling PHI into context.
* Returns IDs in REDCap's natural order.
*/
public function toolListRecordIds(array $payload)
{
if (empty($payload['pid'])) {
return [
"error" => true,
"message" => "Missing required parameter: pid"
];
}
$pid = (int)$payload['pid'];
$filter = $payload['filter'] ?? null;
$offset = max(0, (int)($payload['offset'] ?? 0));
$limit = (int)($payload['limit'] ?? 50);
if ($limit <= 0 || $limit > 200) $limit = 50;
$reference = $payload['reference'] ?? null;
// Reference path: serve from PHP session cache.
//
// Unlike records.search, this path cannot narrow: it slices stored IDs
// and has no row data to re-evaluate logic against. Silently ignoring
// the filter while echoing it back in the response produced a
// confidently wrong answer (the whole cached list, labelled with a
// filter that was never applied), so refuse the combination and point
// the caller at the tool that can do it.
if ($reference && !empty($filter)) {
return [
"error" => true,
"message" => "records.listIds cannot apply a filter to a cached reference — paging a reference only slices the stored IDs. "
. "Either call records.listIds with the filter and NO reference to run it fresh, or use records.search with reference + filter to narrow an existing set."
];
}
if ($reference) {
$cached = $this->cappyCacheFetch($reference, 'records_listIds');
if ($cached === null) {
return [
"error" => true,
"message" => "Reference $reference not found or expired. Call the tool again without 'reference' to re-query."
];
}
if (($cached['pid'] ?? null) !== $pid) {
return [
"error" => true,
"message" => "Reference $reference was cached for a different project."
];
}
$ids = $cached['ids'];
$slice = array_slice($ids, $offset, $limit);
return [
"pid" => $pid,
"filter" => $filter,
"reference" => $reference,
"count" => count($ids),
"returned_count" => count($slice),
"offset" => $offset,
"limit" => $limit,
"record_id_field" => $cached['record_id_field'] ?? null,
"record_ids" => $slice,
"truncated" => ($offset + count($slice)) < count($ids),
"note" => "Served from session cache (reference $reference).",
];
}
// Validate + expand the filter exactly as toolSearchRecords,
// toolCountRecords and toolAggregateRecords do. This tool used to pass
// the raw filter straight to getData, so a label literal
// ([unit] = "CVICU 220") was compared against the stored CODE and
// matched nothing — reported to the user as a confident "no records
// match" rather than an error. A typo'd field name failed the same
// silent way.
//
// Deliberately AFTER the reference path: paging a cached list slices
// stored ids and never applies $filter, so validating/expanding there
// would spend two data-dictionary lookups per page turn for nothing.
if (!empty($filter)) {
$fieldError = $this->cappyValidateFilterFields($pid, $filter);
if ($fieldError !== null) return $fieldError;
}
$filterExpansions = [];
$filterHints = [];
if (!empty($filter)) {
$expanded = $this->cappyExpandFilterLabels($pid, $filter);
$filter = $expanded['filter'];
$filterExpansions = $expanded['translations'];
$filterHints = $expanded['hints'] ?? [];
}
try {
$data = \REDCap::getData(
$pid,
'array',
null,
null,
null,
null,
false,
false,
false,
$filter