This repository was archived by the owner on Feb 27, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathschema.sql
More file actions
10802 lines (7516 loc) · 304 KB
/
schema.sql
File metadata and controls
10802 lines (7516 loc) · 304 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
--
-- PostgreSQL database dump
--
\restrict kdLIVbAbvFM3aqS2i7LL1nvUezyGL6o2hhxAG1QW5bNlkxhzXd5YUjt85dQqpGm
-- Dumped from database version 16.11 (Ubuntu 16.11-0ubuntu0.24.04.1)
-- Dumped by pg_dump version 16.11 (Ubuntu 16.11-0ubuntu0.24.04.1)
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: pg_trgm; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public;
--
-- Name: EXTENSION pg_trgm; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION pg_trgm IS 'text similarity measurement and index searching based on trigrams';
--
-- Name: vector; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS vector WITH SCHEMA public;
--
-- Name: EXTENSION vector; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION vector IS 'vector data type and ivfflat and hnsw access methods';
--
-- Name: agent_chat_status; Type: TYPE; Schema: public; Owner: nova
--
CREATE TYPE public.agent_chat_status AS ENUM (
'received',
'routed',
'responded',
'failed'
);
ALTER TYPE public.agent_chat_status OWNER TO nova;
--
-- Name: agent_set_collaborative(integer, boolean, jsonb, text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.agent_set_collaborative(p_agent_id integer, p_collaborative boolean, p_collaborate_config jsonb DEFAULT NULL::jsonb, p_modified_by text DEFAULT 'system'::text) RETURNS TABLE(success boolean, message text)
LANGUAGE plpgsql
AS $$
DECLARE
v_old_collaborative BOOLEAN;
v_old_config JSONB;
BEGIN
-- Get old values
SELECT collaborative, collaborate_config
INTO v_old_collaborative, v_old_config
FROM agents
WHERE id = p_agent_id;
IF NOT FOUND THEN
RETURN QUERY SELECT FALSE, 'Agent not found';
RETURN;
END IF;
-- Update collaborative settings
UPDATE agents
SET collaborative = p_collaborative,
collaborate_config = COALESCE(p_collaborate_config, collaborate_config),
updated_at = CURRENT_TIMESTAMP
WHERE id = p_agent_id;
-- Log collaborative change
PERFORM log_agent_modification(
p_agent_id, p_modified_by, 'collaborative',
v_old_collaborative::TEXT, p_collaborative::TEXT
);
-- Log config change if provided
IF p_collaborate_config IS NOT NULL THEN
PERFORM log_agent_modification(
p_agent_id, p_modified_by, 'collaborate_config',
v_old_config::TEXT, p_collaborate_config::TEXT
);
END IF;
RETURN QUERY SELECT TRUE, 'Collaborative settings updated successfully';
END;
$$;
ALTER FUNCTION public.agent_set_collaborative(p_agent_id integer, p_collaborative boolean, p_collaborate_config jsonb, p_modified_by text) OWNER TO nova;
--
-- Name: agent_set_model(integer, text, text, text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.agent_set_model(p_agent_id integer, p_new_model text, p_new_fallback text DEFAULT NULL::text, p_modified_by text DEFAULT 'system'::text) RETURNS TABLE(success boolean, message text)
LANGUAGE plpgsql
AS $$
DECLARE
v_old_model TEXT;
v_old_fallback TEXT;
BEGIN
-- Get old values
SELECT model, fallback_model INTO v_old_model, v_old_fallback
FROM agents
WHERE id = p_agent_id;
IF NOT FOUND THEN
RETURN QUERY SELECT FALSE, 'Agent not found';
RETURN;
END IF;
-- Update model
UPDATE agents
SET model = p_new_model,
fallback_model = COALESCE(p_new_fallback, fallback_model),
updated_at = CURRENT_TIMESTAMP
WHERE id = p_agent_id;
-- Log model change
PERFORM log_agent_modification(
p_agent_id, p_modified_by, 'model',
v_old_model, p_new_model
);
-- Log fallback change if provided
IF p_new_fallback IS NOT NULL THEN
PERFORM log_agent_modification(
p_agent_id, p_modified_by, 'fallback_model',
v_old_fallback, p_new_fallback
);
END IF;
RETURN QUERY SELECT TRUE, 'Model configuration updated successfully';
END;
$$;
ALTER FUNCTION public.agent_set_model(p_agent_id integer, p_new_model text, p_new_fallback text, p_modified_by text) OWNER TO nova;
--
-- Name: agent_set_status(integer, text, text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.agent_set_status(p_agent_id integer, p_new_status text, p_modified_by text DEFAULT 'system'::text) RETURNS TABLE(success boolean, message text)
LANGUAGE plpgsql
AS $$
DECLARE
v_old_status TEXT;
v_valid_statuses TEXT[] := ARRAY['active', 'inactive', 'suspended', 'archived'];
BEGIN
-- Validate status value
IF NOT (p_new_status = ANY(v_valid_statuses)) THEN
RETURN QUERY SELECT FALSE,
'Invalid status. Must be one of: active, inactive, suspended, archived';
RETURN;
END IF;
-- Get old status
SELECT status INTO v_old_status
FROM agents
WHERE id = p_agent_id;
IF NOT FOUND THEN
RETURN QUERY SELECT FALSE, 'Agent not found';
RETURN;
END IF;
-- Update status
UPDATE agents
SET status = p_new_status,
updated_at = CURRENT_TIMESTAMP
WHERE id = p_agent_id;
-- Log modification
PERFORM log_agent_modification(
p_agent_id, p_modified_by, 'status', v_old_status, p_new_status
);
RETURN QUERY SELECT TRUE, 'Status updated successfully';
END;
$$;
ALTER FUNCTION public.agent_set_status(p_agent_id integer, p_new_status text, p_modified_by text) OWNER TO nova;
--
-- Name: agent_update(integer, text, text, text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.agent_update(p_agent_id integer, p_field_name text, p_new_value text, p_modified_by text DEFAULT 'system'::text) RETURNS TABLE(success boolean, message text)
LANGUAGE plpgsql
AS $_$
DECLARE
v_old_value TEXT;
v_protected_fields TEXT[] := ARRAY['id', 'created_at'];
v_sql TEXT;
BEGIN
-- Check if field is protected
IF p_field_name = ANY(v_protected_fields) THEN
RETURN QUERY SELECT FALSE,
'Cannot modify protected field: ' || p_field_name;
RETURN;
END IF;
-- Verify agent exists and get old value
v_sql := format('SELECT %I::TEXT FROM agents WHERE id = $1', p_field_name);
BEGIN
EXECUTE v_sql INTO v_old_value USING p_agent_id;
EXCEPTION
WHEN undefined_column THEN
RETURN QUERY SELECT FALSE, 'Invalid field name: ' || p_field_name;
RETURN;
WHEN OTHERS THEN
RETURN QUERY SELECT FALSE, 'Error reading field: ' || SQLERRM;
RETURN;
END;
IF v_old_value IS NULL AND NOT FOUND THEN
RETURN QUERY SELECT FALSE, 'Agent not found';
RETURN;
END IF;
-- Update the field
v_sql := format(
'UPDATE agents SET %I = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',
p_field_name
);
BEGIN
EXECUTE v_sql USING p_new_value, p_agent_id;
EXCEPTION
WHEN OTHERS THEN
RETURN QUERY SELECT FALSE, 'Error updating field: ' || SQLERRM;
RETURN;
END;
-- Log modification
PERFORM log_agent_modification(
p_agent_id, p_modified_by, p_field_name, v_old_value, p_new_value
);
RETURN QUERY SELECT TRUE, 'Field updated successfully';
END;
$_$;
ALTER FUNCTION public.agent_update(p_agent_id integer, p_field_name text, p_new_value text, p_modified_by text) OWNER TO nova;
--
-- Name: agent_update_jsonb(integer, text, jsonb, text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.agent_update_jsonb(p_agent_id integer, p_field_name text, p_new_value jsonb, p_modified_by text DEFAULT 'system'::text) RETURNS TABLE(success boolean, message text)
LANGUAGE plpgsql
AS $_$
DECLARE
v_old_value JSONB;
v_protected_fields TEXT[] := ARRAY['id', 'created_at'];
v_sql TEXT;
BEGIN
-- Check if field is protected
IF p_field_name = ANY(v_protected_fields) THEN
RETURN QUERY SELECT FALSE,
'Cannot modify protected field: ' || p_field_name;
RETURN;
END IF;
-- Get old value
v_sql := format('SELECT %I FROM agents WHERE id = $1', p_field_name);
BEGIN
EXECUTE v_sql INTO v_old_value USING p_agent_id;
EXCEPTION
WHEN undefined_column THEN
RETURN QUERY SELECT FALSE, 'Invalid field name: ' || p_field_name;
RETURN;
WHEN OTHERS THEN
RETURN QUERY SELECT FALSE, 'Error reading field: ' || SQLERRM;
RETURN;
END;
IF NOT FOUND THEN
RETURN QUERY SELECT FALSE, 'Agent not found';
RETURN;
END IF;
-- Update the field
v_sql := format(
'UPDATE agents SET %I = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',
p_field_name
);
EXECUTE v_sql USING p_new_value, p_agent_id;
-- Log modification
PERFORM log_agent_modification(
p_agent_id, p_modified_by, p_field_name,
v_old_value::TEXT, p_new_value::TEXT
);
RETURN QUERY SELECT TRUE, 'Field updated successfully';
END;
$_$;
ALTER FUNCTION public.agent_update_jsonb(p_agent_id integer, p_field_name text, p_new_value jsonb, p_modified_by text) OWNER TO nova;
--
-- Name: agent_update_skills(integer, text[], text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.agent_update_skills(p_agent_id integer, p_skills text[], p_modified_by text DEFAULT 'system'::text) RETURNS TABLE(success boolean, message text)
LANGUAGE plpgsql
AS $$
DECLARE
v_old_skills TEXT[];
BEGIN
-- Get old skills
SELECT skills INTO v_old_skills
FROM agents
WHERE id = p_agent_id;
IF NOT FOUND THEN
RETURN QUERY SELECT FALSE, 'Agent not found';
RETURN;
END IF;
-- Update skills
UPDATE agents
SET skills = p_skills,
updated_at = CURRENT_TIMESTAMP
WHERE id = p_agent_id;
-- Log modification
PERFORM log_agent_modification(
p_agent_id, p_modified_by, 'skills',
array_to_string(v_old_skills, ','),
array_to_string(p_skills, ',')
);
RETURN QUERY SELECT TRUE, 'Skills updated successfully';
END;
$$;
ALTER FUNCTION public.agent_update_skills(p_agent_id integer, p_skills text[], p_modified_by text) OWNER TO nova;
--
-- Name: calculate_word_count(); Type: FUNCTION; Schema: public; Owner: erato
--
CREATE FUNCTION public.calculate_word_count() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.word_count = array_length(regexp_split_to_array(trim(NEW.content), '\s+'), 1);
NEW.character_count = length(NEW.content);
RETURN NEW;
END;
$$;
ALTER FUNCTION public.calculate_word_count() OWNER TO erato;
--
-- Name: chat(text, character varying); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.chat(p_message text, p_sender character varying DEFAULT 'nova'::character varying) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
PERFORM send_agent_message(p_sender, p_message, 'system', NULL);
END;
$$;
ALTER FUNCTION public.chat(p_message text, p_sender character varying) OWNER TO nova;
--
-- Name: claim_coder_issue(integer); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.claim_coder_issue(issue_id integer) RETURNS boolean
LANGUAGE sql
AS $$
UPDATE git_issue_queue
SET status = 'implementing', started_at = NOW()
WHERE id = issue_id AND status = 'tests_approved'
RETURNING TRUE;
$$;
ALTER FUNCTION public.claim_coder_issue(issue_id integer) OWNER TO nova;
--
-- Name: cleanup_old_archives(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.cleanup_old_archives() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
deleted_count INTEGER;
BEGIN
DELETE FROM entity_facts_archive
WHERE archived_at < NOW() - INTERVAL '1 year';
GET DIAGNOSTICS deleted_count = ROW_COUNT;
RETURN deleted_count;
END;
$$;
ALTER FUNCTION public.cleanup_old_archives() OWNER TO nova;
--
-- Name: FUNCTION cleanup_old_archives(); Type: COMMENT; Schema: public; Owner: nova
--
COMMENT ON FUNCTION public.cleanup_old_archives() IS 'Hard deletes archived facts older than 1 year. Run via cron or decay script.';
--
-- Name: cleanup_old_embeddings_archive(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.cleanup_old_embeddings_archive() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
deleted_count INTEGER;
BEGIN
DELETE FROM memory_embeddings_archive WHERE archived_at < NOW() - INTERVAL '1 year';
GET DIAGNOSTICS deleted_count = ROW_COUNT;
RETURN deleted_count;
END;
$$;
ALTER FUNCTION public.cleanup_old_embeddings_archive() OWNER TO nova;
--
-- Name: FUNCTION cleanup_old_embeddings_archive(); Type: COMMENT; Schema: public; Owner: nova
--
COMMENT ON FUNCTION public.cleanup_old_embeddings_archive() IS 'Hard deletes archived embeddings older than 1 year.';
--
-- Name: cleanup_old_events_archive(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.cleanup_old_events_archive() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
deleted_count INTEGER;
BEGIN
DELETE FROM events_archive WHERE archived_at < NOW() - INTERVAL '1 year';
GET DIAGNOSTICS deleted_count = ROW_COUNT;
RETURN deleted_count;
END;
$$;
ALTER FUNCTION public.cleanup_old_events_archive() OWNER TO nova;
--
-- Name: FUNCTION cleanup_old_events_archive(); Type: COMMENT; Schema: public; Owner: nova
--
COMMENT ON FUNCTION public.cleanup_old_events_archive() IS 'Hard deletes archived events older than 1 year.';
--
-- Name: cleanup_old_lessons_archive(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.cleanup_old_lessons_archive() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
deleted_count INTEGER;
BEGIN
DELETE FROM lessons_archive WHERE archived_at < NOW() - INTERVAL '1 year';
GET DIAGNOSTICS deleted_count = ROW_COUNT;
RETURN deleted_count;
END;
$$;
ALTER FUNCTION public.cleanup_old_lessons_archive() OWNER TO nova;
--
-- Name: FUNCTION cleanup_old_lessons_archive(); Type: COMMENT; Schema: public; Owner: nova
--
COMMENT ON FUNCTION public.cleanup_old_lessons_archive() IS 'Hard deletes archived lessons older than 1 year.';
--
-- Name: copy_file_to_bootstrap(text, text, text, text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.copy_file_to_bootstrap(p_file_path text, p_file_content text, p_agent_name text DEFAULT NULL::text, p_updated_by text DEFAULT 'migration'::text) RETURNS text
LANGUAGE plpgsql
AS $_$
DECLARE
v_file_key TEXT;
v_result TEXT;
BEGIN
v_file_key := upper(regexp_replace(
regexp_replace(p_file_path, '^.*/([^/]+)\.md$', '\1'),
'-', '_', 'g'
));
IF p_agent_name IS NULL THEN
PERFORM update_universal_context(
v_file_key,
p_file_content,
'Migrated from ' || p_file_path,
p_updated_by
);
v_result := 'universal:' || v_file_key;
ELSE
PERFORM update_agent_context(
p_agent_name,
v_file_key,
p_file_content,
'Migrated from ' || p_file_path,
p_updated_by
);
v_result := p_agent_name || ':' || v_file_key;
END IF;
RETURN v_result;
END;
$_$;
ALTER FUNCTION public.copy_file_to_bootstrap(p_file_path text, p_file_content text, p_agent_name text, p_updated_by text) OWNER TO nova;
--
-- Name: FUNCTION copy_file_to_bootstrap(p_file_path text, p_file_content text, p_agent_name text, p_updated_by text); Type: COMMENT; Schema: public; Owner: nova
--
COMMENT ON FUNCTION public.copy_file_to_bootstrap(p_file_path text, p_file_content text, p_agent_name text, p_updated_by text) IS 'Migrate file content to database (auto-detects universal vs agent)';
--
-- Name: embed_chat_message(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.embed_chat_message() RETURNS trigger
LANGUAGE plpgsql
AS $$
DECLARE
content_text TEXT;
content_hash_val VARCHAR(64);
BEGIN
-- Prepare content for embedding
content_text := NEW.sender || ': ' || NEW.message;
content_hash_val := encode(sha256(content_text::bytea), 'hex');
-- Insert embedding record (embedding vector will be populated by external process)
-- This just creates a placeholder that external embedding service can process
INSERT INTO memory_embeddings (content_hash, content, metadata, embedding)
VALUES (
content_hash_val,
content_text,
json_build_object(
'chat_id', NEW.id,
'sender', NEW.sender,
'channel', NEW.channel,
'created_at', NEW.created_at
),
NULL -- Will be updated by embedding service
)
ON CONFLICT (content_hash) DO NOTHING; -- Skip if already exists
RETURN NEW;
END;
$$;
ALTER FUNCTION public.embed_chat_message() OWNER TO nova;
--
-- Name: expire_old_chat(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.expire_old_chat() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
v_count INTEGER;
BEGIN
DELETE FROM agent_chat
WHERE created_at < now() - interval '30 days'
RETURNING id INTO v_count;
GET DIAGNOSTICS v_count = ROW_COUNT;
RETURN v_count;
END;
$$;
ALTER FUNCTION public.expire_old_chat() OWNER TO nova;
--
-- Name: get_agent_bootstrap(text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.get_agent_bootstrap(p_agent_name text) RETURNS TABLE(filename text, content text, source text)
LANGUAGE plpgsql
AS $$
DECLARE
v_agent_id INTEGER;
BEGIN
-- Resolve agent ID (may be NULL if agent not in agents table)
SELECT id INTO v_agent_id FROM agents WHERE name = p_agent_name LIMIT 1;
RETURN QUERY
SELECT DISTINCT ON (subq.filename)
subq.filename,
subq.content,
subq.source
FROM (
-- 1. UNIVERSAL — everyone gets these
SELECT abc.file_key || '.md' AS filename, abc.content,
'universal'::TEXT AS source, 1 AS priority
FROM agent_bootstrap_context abc
WHERE abc.context_type = 'UNIVERSAL'
UNION ALL
-- 2. GLOBAL — everyone gets these
SELECT abc.file_key || '.md' AS filename, abc.content,
'global'::TEXT AS source, 2 AS priority
FROM agent_bootstrap_context abc
WHERE abc.context_type = 'GLOBAL'
UNION ALL
-- 3. DOMAIN — matched via agent's domains in agent_domains
SELECT abc.file_key || '.md' AS filename, abc.content,
'domain:' || abc.domain_name AS source, 3 AS priority
FROM agent_bootstrap_context abc
JOIN agent_domains ad ON ad.domain_topic = abc.domain_name
WHERE abc.context_type = 'DOMAIN'
AND ad.agent_id = v_agent_id
UNION ALL
-- 4. WORKFLOW — inject workflow SUMMARIES with agent role context
SELECT
'WORKFLOW_' || upper(replace(w.name, '-', '_')) || '.md' AS filename,
w.name || ': ' || w.description ||
E'\n\n' ||
-- Orchestrator note
CASE WHEN EXISTS (
SELECT 1 FROM agent_domains ad
WHERE ad.agent_id = v_agent_id
AND ad.domain_topic = w.orchestrator_domain
)
THEN 'You are the **orchestrator** of this workflow (via ' || w.orchestrator_domain || ' domain). '
|| 'You are responsible for reading and understanding the entire workflow, maintaining state, delegating to domain-appropriate agents, and tracking progress.'
|| E'\n\n'
ELSE ''
END ||
-- Agent's steps
'Your steps: ' || COALESCE(agent_steps.step_list, 'none directly assigned') ||
E'\n' ||
-- All domains
'All domains involved: ' || COALESCE(all_domains.domain_list, 'none') ||
' (' || COALESCE(step_count.cnt, 0) || ' steps total).' ||
E'\n\n' ||
'> When you are employed to participate in this workflow, understand your role and what is expected of you in the steps you own before beginning. ' ||
'Query your steps for full details:' ||
E'\n> ```sql' ||
E'\n> SELECT step_order, domain, requires_discussion, requires_authorization, description' ||
E'\n> FROM workflow_steps WHERE workflow_id = ' || w.id || ' ORDER BY step_order;' ||
E'\n> ```'
AS content,
'workflow:' || w.name AS source,
4 AS priority
FROM workflows w
-- Agent's specific steps (by domain match)
LEFT JOIN LATERAL (
SELECT string_agg(
'Step ' || ws.step_order || ' (' || ws.domain || ')',
', ' ORDER BY ws.step_order
) AS step_list
FROM workflow_steps ws
JOIN agent_domains ad ON ad.agent_id = v_agent_id
WHERE ws.workflow_id = w.id
AND (ad.domain_topic = ws.domain OR ad.domain_topic = ANY(ws.domains))
) agent_steps ON true
-- All domains across all steps
LEFT JOIN LATERAL (
SELECT string_agg(DISTINCT ws.domain, ', ' ORDER BY ws.domain) AS domain_list
FROM workflow_steps ws
WHERE ws.workflow_id = w.id
) all_domains ON true
-- Step count
LEFT JOIN LATERAL (
SELECT count(*)::int AS cnt
FROM workflow_steps ws
WHERE ws.workflow_id = w.id
) step_count ON true
WHERE w.status = 'active'
AND (
-- Workflow's orchestrator domain matches one of the agent's domains
EXISTS (
SELECT 1 FROM agent_domains ad
WHERE ad.agent_id = v_agent_id
AND ad.domain_topic = w.orchestrator_domain
)
OR
-- Workflow step domains overlap with agent's domains
EXISTS (
SELECT 1 FROM workflow_steps ws
JOIN agent_domains ad ON ad.agent_id = v_agent_id
WHERE ws.workflow_id = w.id
AND (ad.domain_topic = ws.domain OR ad.domain_topic = ANY(ws.domains))
)
)
UNION ALL
-- 5. AGENT — the ONLY lookup by agent name directly
SELECT abc.file_key || '.md' AS filename, abc.content,
'agent'::TEXT AS source, 5 AS priority
FROM agent_bootstrap_context abc
WHERE abc.context_type = 'AGENT'
AND abc.agent_name = p_agent_name
) subq
ORDER BY subq.filename, subq.priority;
END;
$$;
ALTER FUNCTION public.get_agent_bootstrap(p_agent_name text) OWNER TO nova;
--
-- Name: get_agent_turn_context(text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.get_agent_turn_context(p_agent_name text) RETURNS TABLE(content text, truncated boolean, records_skipped integer, total_chars integer)
LANGUAGE plpgsql STABLE
AS $$
DECLARE
v_content TEXT := '';
v_budget INT := 2000;
v_total_chars INT := 0;
v_records_skipped INT := 0;
v_truncated BOOLEAN := false;
rec RECORD;
BEGIN
-- Iterate through records in priority order: UNIVERSAL → GLOBAL → DOMAIN → AGENT
FOR rec IN
SELECT atc.content AS rec_content, atc.context_type
FROM agent_turn_context atc
WHERE atc.enabled = true
AND (
atc.context_type IN ('UNIVERSAL', 'GLOBAL')
OR (atc.context_type = 'DOMAIN' AND atc.context_key IN (
SELECT ad.domain_topic FROM agent_domains ad
JOIN agents a ON a.id = ad.agent_id
WHERE a.name = p_agent_name
))
OR (atc.context_type = 'AGENT' AND atc.context_key = p_agent_name)
)
ORDER BY
CASE atc.context_type
WHEN 'UNIVERSAL' THEN 1
WHEN 'GLOBAL' THEN 2
WHEN 'DOMAIN' THEN 3
WHEN 'AGENT' THEN 4
END,
atc.file_key
LOOP
IF v_total_chars + LENGTH(rec.rec_content) > v_budget THEN
v_truncated := true;
v_records_skipped := v_records_skipped + 1;
ELSE
IF v_content != '' THEN
v_content := v_content || E'\n\n';
v_total_chars := v_total_chars + 2;
END IF;
v_content := v_content || rec.rec_content;
v_total_chars := v_total_chars + LENGTH(rec.rec_content);
END IF;
END LOOP;
RETURN QUERY SELECT v_content, v_truncated, v_records_skipped, v_total_chars;
END;
$$;
ALTER FUNCTION public.get_agent_turn_context(p_agent_name text) OWNER TO nova;
--
-- Name: get_next_coder_issue(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.get_next_coder_issue() RETURNS TABLE(id integer, repo text, issue_number integer, title text)
LANGUAGE sql
AS $$
SELECT id, repo, issue_number, title
FROM git_issue_queue
WHERE status = 'tests_approved'
AND NOT should_skip_issue(COALESCE(labels, '{}'))
ORDER BY priority DESC, created_at
LIMIT 1;
$$;
ALTER FUNCTION public.get_next_coder_issue() OWNER TO nova;
--
-- Name: get_ralph_state(text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.get_ralph_state(p_series_id text) RETURNS TABLE(iteration integer, state jsonb, status text)
LANGUAGE sql
AS $$
SELECT iteration, state, status
FROM ralph_sessions
WHERE session_series_id = p_series_id
ORDER BY iteration DESC
LIMIT 1;
$$;
ALTER FUNCTION public.get_ralph_state(p_series_id text) OWNER TO nova;
--
-- Name: insert_workflow_step(integer, integer, text, text, boolean, text, text); Type: FUNCTION; Schema: public; Owner: postgres
--
CREATE FUNCTION public.insert_workflow_step(p_workflow_id integer, p_step_order integer, p_agent_name text, p_description text, p_produces_deliverable boolean DEFAULT false, p_deliverable_type text DEFAULT NULL::text, p_deliverable_description text DEFAULT NULL::text) RETURNS integer
LANGUAGE plpgsql SECURITY DEFINER
AS $$
DECLARE
v_agent_id INT;
v_step_id INT;
BEGIN
SELECT id INTO v_agent_id FROM agents WHERE name = p_agent_name;
IF v_agent_id IS NULL THEN
RAISE EXCEPTION 'Agent not found: %', p_agent_name;
END IF;
INSERT INTO workflow_steps (workflow_id, step_order, agent_id, description, produces_deliverable, deliverable_type, deliverable_description)
VALUES (p_workflow_id, p_step_order, v_agent_id, p_description, p_produces_deliverable, p_deliverable_type, p_deliverable_description)
RETURNING id INTO v_step_id;
RETURN v_step_id;
END;
$$;
ALTER FUNCTION public.insert_workflow_step(p_workflow_id integer, p_step_order integer, p_agent_name text, p_description text, p_produces_deliverable boolean, p_deliverable_type text, p_deliverable_description text) OWNER TO postgres;
--
-- Name: library_works_search_trigger(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.library_works_search_trigger() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('english', coalesce(NEW.title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(NEW.summary, '')), 'B') ||
setweight(to_tsvector('english', coalesce(NEW.abstract, '')), 'B') ||
setweight(to_tsvector('english', coalesce(NEW.insights, '')), 'C') ||
setweight(to_tsvector('english', coalesce(array_to_string(NEW.notable_quotes, ' '), '')), 'B') ||
setweight(to_tsvector('english', coalesce(NEW.content_text, '')), 'D');
NEW.updated_at := CURRENT_TIMESTAMP;
RETURN NEW;
END
$$;
ALTER FUNCTION public.library_works_search_trigger() OWNER TO nova;
--
-- Name: link_github_issue(integer, integer); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.link_github_issue(p_queue_id integer, p_github_issue integer) RETURNS void
LANGUAGE sql
AS $$
UPDATE git_issue_queue
SET issue_number = p_github_issue
WHERE id = p_queue_id;
$$;
ALTER FUNCTION public.link_github_issue(p_queue_id integer, p_github_issue integer) OWNER TO nova;
--
-- Name: list_agent_context(text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.list_agent_context(p_agent_name text) RETURNS TABLE(source_type text, domain_or_scope text, file_key text, content_preview text)
LANGUAGE plpgsql
AS $$
DECLARE
v_agent_id INTEGER;
BEGIN
SELECT id INTO v_agent_id FROM agents WHERE name = p_agent_name;
RETURN QUERY
SELECT
'GLOBAL'::TEXT,
'all agents'::TEXT,
bc.file_key,
LEFT(bc.content, 100) || '...'
FROM agent_bootstrap_context bc
WHERE bc.context_type = 'GLOBAL'
UNION ALL
SELECT
'DOMAIN'::TEXT,
bc.domain_name,
bc.file_key,
LEFT(bc.content, 100) || '...'
FROM agent_bootstrap_context bc
JOIN agent_domains ad ON bc.domain_name = ad.domain_topic
WHERE bc.context_type = 'DOMAIN'
AND ad.agent_id = v_agent_id
UNION ALL
SELECT
'WORKFLOW'::TEXT,
w.name,
'WORKFLOW_CONTEXT'::TEXT,
LEFT(w.description, 100) || '...'
FROM workflow_steps ws
JOIN workflows w ON ws.workflow_id = w.id
WHERE ws.agent_id = v_agent_id
AND w.status = 'active';
END;
$$;
ALTER FUNCTION public.list_agent_context(p_agent_name text) OWNER TO nova;
--
-- Name: log_agent_modification(integer, text, text, text, text); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.log_agent_modification(p_agent_id integer, p_modified_by text, p_field_changed text, p_old_value text, p_new_value text) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO agent_modifications (
agent_id, modified_by, field_changed, old_value, new_value
) VALUES (
p_agent_id, p_modified_by, p_field_changed, p_old_value, p_new_value
);
END;
$$;
ALTER FUNCTION public.log_agent_modification(p_agent_id integer, p_modified_by text, p_field_changed text, p_old_value text, p_new_value text) OWNER TO nova;
--
-- Name: normalize_agent_chat_mentions(); Type: FUNCTION; Schema: public; Owner: nova
--
CREATE FUNCTION public.normalize_agent_chat_mentions() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF NEW.mentions IS NOT NULL THEN
NEW.mentions := ARRAY(SELECT LOWER(unnest(NEW.mentions)));