-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-types.ts
More file actions
1317 lines (1167 loc) · 45.5 KB
/
api-types.ts
File metadata and controls
1317 lines (1167 loc) · 45.5 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
/**
* Shared API Types — Canonical Zod schemas for wiki-server request/response shapes.
*
* These schemas are the single source of truth for API validation. They are imported
* by both the wiki-server route handlers (for runtime validation) and the crux client
* library (for TypeScript type inference via `z.infer<>`).
*
* Convention:
* - `XyzSchema` — Zod schema for runtime validation
* - `Xyz` — TypeScript type inferred from the schema (`z.infer<typeof XyzSchema>`)
* - Input types — Shapes the client sends to the server
* - Result types — Shapes the server returns to the client (not validated here;
* defined as plain TS interfaces for documentation)
*/
import { z } from "zod";
// ---------------------------------------------------------------------------
// Shared constants
// ---------------------------------------------------------------------------
/** Default maximum items per batch for most endpoints. */
export const MAX_BATCH_SIZE = 200;
// ---------------------------------------------------------------------------
// Common patterns
// ---------------------------------------------------------------------------
export const DateStringSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
export const PageIdSchema = z.string().min(1).max(200);
// ---------------------------------------------------------------------------
// Edit Logs
// ---------------------------------------------------------------------------
export const VALID_TOOLS = [
"crux-create",
"crux-improve",
"crux-grade",
"crux-fix",
"crux-fix-escalated",
"crux-audit",
"crux-audit-escalated",
"crux-audit-source-replace",
"crux-audit-pass2",
"claude-code",
"manual",
"bulk-script",
] as const;
export const VALID_AGENCIES = ["human", "ai-directed", "automated"] as const;
export const EditLogEntrySchema = z.object({
pageId: PageIdSchema,
date: DateStringSchema,
tool: z.enum(VALID_TOOLS),
agency: z.enum(VALID_AGENCIES),
requestedBy: z.string().max(200).nullable().optional(),
note: z.string().max(5000).nullable().optional(),
});
export type EditLogEntry = z.infer<typeof EditLogEntrySchema>;
export const EditLogBatchSchema = z.object({
items: z.array(EditLogEntrySchema).min(1).max(MAX_BATCH_SIZE),
});
export type EditLogBatch = z.infer<typeof EditLogBatchSchema>;
// ---------------------------------------------------------------------------
// Citation Quotes
// ---------------------------------------------------------------------------
export const UpsertCitationQuoteSchema = z.object({
pageId: PageIdSchema,
footnote: z.number().int().min(0),
url: z.string().max(2000).nullable().optional(),
resourceId: z.string().max(200).nullable().optional(),
claimText: z.string().min(1).max(10000),
claimContext: z.string().max(10000).nullable().optional(),
sourceQuote: z.string().max(10000).nullable().optional(),
sourceLocation: z.string().max(1000).nullable().optional(),
quoteVerified: z.boolean().optional(),
verificationMethod: z.string().max(200).nullable().optional(),
verificationScore: z.number().min(0).max(1).nullable().optional(),
sourceTitle: z.string().max(1000).nullable().optional(),
sourceType: z.string().max(100).nullable().optional(),
extractionModel: z.string().max(200).nullable().optional(),
});
export type UpsertCitationQuote = z.infer<typeof UpsertCitationQuoteSchema>;
export const UpsertCitationQuoteBatchSchema = z.object({
items: z.array(UpsertCitationQuoteSchema).min(1).max(100),
});
// ---------------------------------------------------------------------------
// Citation Accuracy
// ---------------------------------------------------------------------------
export const AccuracyVerdictSchema = z.enum([
"accurate",
"inaccurate",
"unsupported",
"minor_issues",
"not_verifiable",
]);
export type AccuracyVerdict = z.infer<typeof AccuracyVerdictSchema>;
/** Runtime-accessible array of valid verdict values — use for iteration/aggregation. */
export const ACCURACY_VERDICTS = AccuracyVerdictSchema.options;
export const MarkAccuracySchema = z.object({
pageId: PageIdSchema,
footnote: z.number().int().min(0),
verdict: AccuracyVerdictSchema,
score: z.number().min(0).max(1),
issues: z.string().max(10000).nullable().optional(),
supportingQuotes: z.string().max(10000).nullable().optional(),
verificationDifficulty: z
.enum(["easy", "moderate", "hard"])
.nullable()
.optional(),
});
export type MarkAccuracy = z.infer<typeof MarkAccuracySchema>;
export const MarkAccuracyBatchSchema = z.object({
items: z.array(MarkAccuracySchema).min(1).max(100),
});
export interface AccuracyDashboardData {
exportedAt: string;
summary: {
totalCitations: number;
checkedCitations: number;
accurateCitations: number;
inaccurateCitations: number;
unsupportedCitations: number;
minorIssueCitations: number;
uncheckedCitations: number;
averageScore: number | null;
};
verdictDistribution: Record<string, number>;
difficultyDistribution: Record<string, number>;
pages: Array<{
pageId: string;
totalCitations: number;
checked: number;
accurate: number;
inaccurate: number;
unsupported: number;
minorIssues: number;
accuracyRate: number | null;
avgScore: number | null;
}>;
flaggedCitations: Array<{
pageId: string;
footnote: number;
claimText: string;
sourceTitle: string | null;
url: string | null;
verdict: string;
score: number | null;
issues: string | null;
difficulty: string | null;
checkedAt: string | null;
}>;
domainAnalysis: Array<{
domain: string;
totalCitations: number;
checked: number;
accurate: number;
inaccurate: number;
unsupported: number;
minorIssues: number;
inaccuracyRate: number | null;
}>;
}
// ---------------------------------------------------------------------------
// Citation Content
// ---------------------------------------------------------------------------
/** Maximum size for the full-text preview field (50 KB). */
export const CITATION_CONTENT_PREVIEW_MAX = 50 * 1024;
/** Maximum size for the full_text field (5 MB). */
export const CITATION_CONTENT_FULL_TEXT_MAX = 5 * 1024 * 1024;
export const UpsertCitationContentSchema = z.object({
url: z.string().min(1).max(2000),
resourceId: z.string().max(200).nullable().optional(),
fetchedAt: z.string().datetime(),
httpStatus: z.number().int().nullable().optional(),
contentType: z.string().max(200).nullable().optional(),
pageTitle: z.string().max(1000).nullable().optional(),
fullTextPreview: z.string().max(CITATION_CONTENT_PREVIEW_MAX).nullable().optional(),
fullText: z.string().max(CITATION_CONTENT_FULL_TEXT_MAX).nullable().optional(),
contentLength: z.number().int().nullable().optional(),
contentHash: z.string().max(64).nullable().optional(),
});
export type UpsertCitationContent = z.infer<typeof UpsertCitationContentSchema>;
// -- Citation Content: Response types -----------------------------------------
export interface CitationContentRow {
url: string;
resourceId: string | null;
fetchedAt: string;
httpStatus: number | null;
contentType: string | null;
pageTitle: string | null;
fullTextPreview: string | null;
fullText: string | null;
contentLength: number | null;
contentHash: string | null;
createdAt: string;
updatedAt: string;
}
export interface CitationContentListEntry {
url: string;
fetchedAt: string;
httpStatus: number | null;
contentType: string | null;
pageTitle: string | null;
contentLength: number | null;
contentHash: string | null;
hasFullText: boolean;
hasPreview: boolean;
createdAt: string;
updatedAt: string;
}
export interface CitationContentListResult {
entries: CitationContentListEntry[];
total: number;
withFullText: number;
withPreview: number;
limit: number;
offset: number;
}
export interface CitationContentStatsResult {
total: number;
withFullText: number;
withPreview: number;
coverage: number;
okCount: number;
deadCount: number;
avgContentLength: number | null;
}
// ---------------------------------------------------------------------------
// Sessions
// ---------------------------------------------------------------------------
export const CreateSessionSchema = z.object({
date: DateStringSchema,
branch: z.string().max(500).nullable().optional(),
title: z.string().min(1).max(1000),
summary: z.string().max(10000).nullable().optional(),
model: z.string().max(100).nullable().optional(),
duration: z.string().max(100).nullable().optional(),
cost: z.string().max(100).nullable().optional(),
/** Numeric cost in integer cents, auto-parsed from `cost` string if not provided. Enables aggregation and alerting. */
costCents: z.number().int().min(0).nullable().optional(),
/** Numeric duration in minutes (float), auto-parsed from `duration` string if not provided. Enables aggregation. */
durationMinutes: z.number().min(0).nullable().optional(),
prUrl: z.string().max(1000).nullable().optional(),
checksYaml: z.string().max(10000).nullable().optional(),
issuesJson: z.unknown().nullable().optional(),
learningsJson: z.unknown().nullable().optional(),
recommendationsJson: z.unknown().nullable().optional(),
/** Whether /review-pr was run during this session. NULL = unknown (pre-feature). */
reviewed: z.boolean().nullable().optional(),
pages: z
.array(z.string().min(1).max(200))
.optional()
.default([])
.transform((arr) => [...new Set(arr)]),
});
export type CreateSession = z.infer<typeof CreateSessionSchema>;
export const CreateSessionBatchSchema = z.object({
items: z.array(CreateSessionSchema).min(1).max(MAX_BATCH_SIZE),
});
// ---------------------------------------------------------------------------
// Auto-Update Runs
// ---------------------------------------------------------------------------
export const AutoUpdateResultSchema = z.object({
pageId: z.string().min(1).max(200),
status: z.enum(["success", "failed", "skipped"]),
tier: z.string().max(50).nullable().optional(),
durationMs: z.number().int().min(0).nullable().optional(),
errorMessage: z.string().max(5000).nullable().optional(),
});
export type AutoUpdateResult = z.infer<typeof AutoUpdateResultSchema>;
export const RecordAutoUpdateRunSchema = z.object({
date: DateStringSchema,
startedAt: z.string().datetime(),
completedAt: z.string().datetime().nullable().optional(),
trigger: z.enum(["scheduled", "manual"]),
budgetLimit: z.number().min(0).nullable().optional(),
budgetSpent: z.number().min(0).nullable().optional(),
sourcesChecked: z.number().int().min(0).nullable().optional(),
sourcesFailed: z.number().int().min(0).nullable().optional(),
itemsFetched: z.number().int().min(0).nullable().optional(),
itemsRelevant: z.number().int().min(0).nullable().optional(),
pagesPlanned: z.number().int().min(0).nullable().optional(),
pagesUpdated: z.number().int().min(0).nullable().optional(),
pagesFailed: z.number().int().min(0).nullable().optional(),
pagesSkipped: z.number().int().min(0).nullable().optional(),
newPagesCreated: z.array(z.string()).optional(),
results: z.array(AutoUpdateResultSchema).max(100).optional(),
});
export type RecordAutoUpdateRun = z.infer<typeof RecordAutoUpdateRunSchema>;
// ---------------------------------------------------------------------------
// Auto-Update News Items
// ---------------------------------------------------------------------------
export const AutoUpdateNewsItemSchema = z.object({
title: z.string().min(1).max(2000),
url: z.string().min(1).max(5000),
sourceId: z.string().min(1).max(200),
publishedAt: z.string().max(100).nullable().optional(),
summary: z.string().max(5000).nullable().optional(),
relevanceScore: z.number().int().min(0).max(100).nullable().optional(),
topics: z.array(z.string().max(200)).optional().default([]),
entities: z.array(z.string().max(200)).optional().default([]),
routedToPageId: z.string().max(200).nullable().optional(),
routedToPageTitle: z.string().max(500).nullable().optional(),
routedTier: z.string().max(50).nullable().optional(),
});
export type AutoUpdateNewsItemInput = z.infer<typeof AutoUpdateNewsItemSchema>;
export const AutoUpdateNewsBatchSchema = z.object({
runId: z.number().int().positive(),
items: z.array(AutoUpdateNewsItemSchema).min(1).max(500),
});
// ---------------------------------------------------------------------------
// Hallucination Risk
// ---------------------------------------------------------------------------
export const RiskSnapshotSchema = z.object({
pageId: z.string().min(1).max(300),
score: z.number().int().min(0).max(100),
level: z.enum(["low", "medium", "high"]),
factors: z.array(z.string()).nullable().optional(),
integrityIssues: z.array(z.string()).nullable().optional(),
});
export type RiskSnapshotInput = z.infer<typeof RiskSnapshotSchema>;
export const RiskSnapshotBatchSchema = z.object({
snapshots: z.array(RiskSnapshotSchema).min(1).max(700),
});
// ---------------------------------------------------------------------------
// Summaries
// ---------------------------------------------------------------------------
export const UpsertSummarySchema = z.object({
entityId: z.string().min(1).max(300),
entityType: z.string().min(1).max(100),
oneLiner: z.string().max(1000).nullable().optional(),
summary: z.string().max(50000).nullable().optional(),
review: z.string().max(50000).nullable().optional(),
keyPoints: z.array(z.string().max(2000)).max(50).nullable().optional(),
keyClaims: z.array(z.string().max(2000)).max(50).nullable().optional(),
model: z.string().max(200).nullable().optional(),
tokensUsed: z.number().int().min(0).nullable().optional(),
});
export type UpsertSummary = z.infer<typeof UpsertSummarySchema>;
export const UpsertSummaryBatchSchema = z.object({
items: z.array(UpsertSummarySchema).min(1).max(MAX_BATCH_SIZE),
});
// ---------------------------------------------------------------------------
// Claims
// ---------------------------------------------------------------------------
/**
* Claim category taxonomy — high-level grouping for how a claim should be
* treated, verified, and displayed.
*/
export const ClaimCategorySchema = z.enum([
"factual", // Verifiable against sources (dates, events, numbers)
"opinion", // Subjective evaluations, value judgments
"analytical", // Wiki's own inferences drawn from evidence
"speculative", // Uncertain projections, predictions
"relational", // Cross-entity comparisons or relationships
]);
export type ClaimCategory = z.infer<typeof ClaimCategorySchema>;
/**
* Claim type — granular classification matching the claim-first architecture
* taxonomy (E892). These map to different verification strategies.
*/
export const ClaimTypeSchema = z.enum([
// Core types (existing)
"factual", // Verifiable against a single source
"evaluative", // Subjective assessments or judgments
"causal", // Cause-effect assertions
"historical", // Historical events with dates
// Extended types (from claim-first architecture)
"numeric", // Numeric values that should link to fact system
"consensus", // Claims requiring multiple source agreement
"speculative", // Explicit predictions or uncertain projections
"relational", // Cross-entity comparisons
]);
export type ClaimType = z.infer<typeof ClaimTypeSchema>;
export const InferenceTypeSchema = z.enum([
"direct_assertion",
"derived",
"aggregated",
"interpreted",
"editorial",
]);
export type InferenceType = z.infer<typeof InferenceTypeSchema>;
export const ClaimModeSchema = z.enum(["endorsed", "attributed"]);
export type ClaimMode = z.infer<typeof ClaimModeSchema>;
export const ClaimVerdictSchema = z.enum([
"verified",
"unsupported",
"disputed",
"unverified",
]);
export type ClaimVerdict = z.infer<typeof ClaimVerdictSchema>;
export const VerdictDifficultySchema = z.enum(["easy", "moderate", "hard"]);
export type VerdictDifficulty = z.infer<typeof VerdictDifficultySchema>;
export const InsertClaimSchema = z.object({
entityId: z.string().min(1).max(300),
entityType: z.string().min(1).max(100),
claimType: z.string().min(1).max(100),
claimText: z.string().min(1).max(10000),
// @deprecated — legacy text fields; use valueNumeric/valueLow/valueHigh + measure instead.
// Still accepted for backward compat but not used by new code paths.
value: z.string().max(1000).nullable().optional(),
unit: z.string().max(100).nullable().optional(),
/** @deprecated Use claimVerdict instead. Kept for backward compatibility. */
confidence: z.string().max(100).nullable().optional(),
/** @deprecated Use sources[] (claim_sources table) instead. Kept for backward compat (double-write). */
sourceQuote: z.string().max(10000).nullable().optional(),
// Enhanced fields (migration 0028)
claimCategory: ClaimCategorySchema.nullable().optional(),
relatedEntities: z.array(z.string().max(300)).nullable().optional(),
factId: z.string().max(300).nullable().optional(),
resourceIds: z.array(z.string().max(300)).nullable().optional(),
section: z.string().max(1000).nullable().optional(),
/** @deprecated Use claim_page_references table instead. Kept for backward compat. */
footnoteRefs: z.string().max(500).nullable().optional(),
// Phase 2 fields (migration 0029)
claimMode: ClaimModeSchema.nullable().optional(),
attributedTo: z.string().max(300).nullable().optional(),
asOf: z.string().max(20).nullable().optional(), // YYYY-MM or YYYY-MM-DD
measure: z.string().max(200).nullable().optional(),
valueNumeric: z.number().nullable().optional(),
valueLow: z.number().nullable().optional(),
valueHigh: z.number().nullable().optional(),
// Verdict fields (migration 0031)
claimVerdict: ClaimVerdictSchema.nullable().optional(),
claimVerdictScore: z.number().min(0).max(1).nullable().optional(),
claimVerdictIssues: z.string().max(10000).nullable().optional(),
claimVerdictQuotes: z.string().max(10000).nullable().optional(),
claimVerdictDifficulty: VerdictDifficultySchema.nullable().optional(),
claimVerdictModel: z.string().max(200).nullable().optional(),
// Structured claim fields (migration 0032)
subjectEntity: z.string().max(300).nullable().optional(), // entity_id this claim is about
property: z.string().max(200).nullable().optional(), // property from controlled vocabulary
structuredValue: z.string().max(2000).nullable().optional(), // normalized value
valueUnit: z.string().max(100).nullable().optional(), // unit of measurement (USD, percent, count, etc.)
valueDate: z.string().max(20).nullable().optional(), // YYYY-MM-DD when the value was true/measured
qualifiers: z.record(z.string()).nullable().optional(), // additional context (e.g. {"round": "Series B"})
// Reasoning traces (migration 0034)
inferenceType: InferenceTypeSchema.nullable().optional(),
// Inline sources — optional list of sources to create in claim_sources table
sources: z.array(z.object({
resourceId: z.string().max(300).nullable().optional(),
url: z.string().max(2000).nullable().optional(),
sourceQuote: z.string().max(10000).nullable().optional(),
isPrimary: z.boolean().optional(),
sourceTitle: z.string().max(1000).nullable().optional(),
sourceType: z.string().max(100).nullable().optional(),
sourceLocation: z.string().max(1000).nullable().optional(),
sourceVerdict: z.string().max(100).nullable().optional(),
sourceVerdictScore: z.number().min(0).max(1).nullable().optional(),
sourceCheckedAt: z.string().nullable().optional(),
})).nullable().optional(),
});
export type InsertClaim = z.infer<typeof InsertClaimSchema>;
export const InsertClaimBatchSchema = z.object({
items: z.array(InsertClaimSchema).min(1).max(500),
});
export const ClearClaimsSchema = z.object({
entityId: z.string().min(1).max(300),
});
/** Clear only claims for a specific entity+section combination (used by --force on resource ingestion). */
export const ClearClaimsBySectionSchema = z.object({
entityId: z.string().min(1).max(300),
section: z.string().min(1).max(500),
});
// -- Claims: Response types ---------------------------------------------------
export interface ClaimSourceRow {
id: number;
claimId: number;
resourceId: string | null;
url: string | null;
sourceQuote: string | null;
isPrimary: boolean;
addedAt: string;
sourceVerdict: string | null;
sourceVerdictScore: number | null;
sourceVerdictIssues: string | null;
sourceCheckedAt: string | null;
sourceTitle: string | null;
sourceType: string | null;
sourceLocation: string | null;
}
export interface ClaimRow {
id: number;
entityId: string;
entityType: string;
claimType: string;
claimText: string;
/** @deprecated Use valueNumeric/valueLow/valueHigh instead */
value: string | null;
/** @deprecated Use measure instead */
unit: string | null;
/** @deprecated Use claimVerdict instead. */
confidence: string | null;
/** @deprecated Use sources[] (from claim_sources table) instead. */
sourceQuote: string | null;
// Enhanced fields (migration 0028)
claimCategory: string | null;
relatedEntities: string[] | null;
factId: string | null;
resourceIds: string[] | null;
section: string | null;
/** @deprecated Use claim_page_references table instead. Kept for backward compat. */
footnoteRefs: string | null;
// Phase 2 fields (migration 0029)
claimMode: string | null; // 'endorsed' | 'attributed'
attributedTo: string | null; // entity_id of person/org making claim
asOf: string | null; // YYYY-MM or YYYY-MM-DD
measure: string | null; // measure ID from facts taxonomy
valueNumeric: number | null; // central numeric value
valueLow: number | null; // lower bound
valueHigh: number | null; // upper bound
// Verdict fields (migration 0031)
claimVerdict: string | null;
claimVerdictScore: number | null;
claimVerdictIssues: string | null;
claimVerdictQuotes: string | null;
claimVerdictDifficulty: string | null;
claimVerifiedAt: string | null;
claimVerdictModel: string | null;
// Structured claim fields (migration 0032)
subjectEntity: string | null;
property: string | null;
structuredValue: string | null;
valueUnit: string | null;
valueDate: string | null;
qualifiers: Record<string, string> | null;
// Pinned claims (migration 0034)
isPinned: boolean;
sources: ClaimSourceRow[]; // populated when ?includeSources=true
createdAt: string;
updatedAt: string;
}
export interface InsertClaimResult {
id: number;
entityId: string;
claimType: string;
}
export interface InsertClaimBatchResult {
inserted: number;
results: Array<{ id: number; entityId: string; claimType: string }>;
}
export interface ClearClaimsResult {
deleted: number;
}
export interface GetClaimsResult {
claims: ClaimRow[];
}
export interface ClaimStatsResult {
total: number;
byClaimType: Record<string, number>;
byEntityType: Record<string, number>;
byClaimCategory: Record<string, number>;
byClaimMode: Record<string, number>;
byClaimVerdict: Record<string, number>;
multiEntityClaims: number;
factLinkedClaims: number;
withSourcesClaims: number;
attributedClaims: number;
numericClaims?: number;
structuredClaims?: number;
byProperty?: Record<string, number>;
}
// -- Claims: Page References types -------------------------------------------
export interface ClaimPageReferenceRow {
id: number;
claimId: number;
pageId: string;
footnote: number | null;
section: string | null;
quoteText: string | null;
referenceId: string | null;
createdAt: string;
}
export const ClaimPageReferenceInsertSchema = z.object({
claimId: z.number().int().positive(),
pageId: PageIdSchema,
footnote: z.number().int().min(0).nullable().optional(),
section: z.string().max(1000).nullable().optional(),
quoteText: z.string().max(10000).nullable().optional(),
referenceId: z.string().max(500).nullable().optional(),
});
export type ClaimPageReferenceInsert = z.infer<typeof ClaimPageReferenceInsertSchema>;
export const ClaimPageReferenceBatchSchema = z.object({
items: z.array(ClaimPageReferenceInsertSchema.omit({ claimId: true })).min(1).max(200),
});
// -- Page Citations types (non-claim footnotes) -------------------------------
export const PageCitationInsertSchema = z.object({
referenceId: z.string().min(1).max(500),
pageId: PageIdSchema,
title: z.string().max(2000).optional(),
url: z.string().max(5000).optional(),
note: z.string().max(10000).optional(),
resourceId: z.string().max(200).optional(),
});
export type PageCitationInsert = z.infer<typeof PageCitationInsertSchema>;
export const PageCitationBatchSchema = z.object({
items: z.array(PageCitationInsertSchema).min(1).max(200),
});
export interface PageCitationRow {
id: number;
referenceId: string;
pageId: string;
title: string | null;
url: string | null;
note: string | null;
resourceId: string | null;
createdAt: string;
}
// -- Claims: Citation linking types ------------------------------------------
export const LinkCitationClaimSchema = z.object({
claimId: z.number().int().positive(),
});
export type LinkCitationClaim = z.infer<typeof LinkCitationClaimSchema>;
export const LinkCitationsClaimsBatchSchema = z.object({
items: z.array(z.object({
quoteId: z.number().int().positive(),
claimId: z.number().int().positive(),
})).min(1).max(200),
});
// -- Claims: Backward propagation — REMOVED in #1310 -----------
// PropagateFromClaimsSchema was deleted. Claims are now the single source of truth.
// The old endpoint POST /quotes/propagate-from-claims no longer exists.
// ---------------------------------------------------------------------------
// Page Links
// ---------------------------------------------------------------------------
export const LinkTypeSchema = z.enum([
"yaml_related",
"entity_link",
"name_prefix",
"similarity",
"shared_tag",
]);
export const PageLinkSchema = z.object({
sourceId: z.string().min(1).max(300),
targetId: z.string().min(1).max(300),
linkType: LinkTypeSchema,
relationship: z.string().max(100).nullable().optional(),
weight: z.number().min(0).max(100).default(1.0),
});
export type PageLink = z.infer<typeof PageLinkSchema>;
export const SyncLinksBatchSchema = z.object({
links: z.array(PageLinkSchema).min(1).max(5000),
replace: z.boolean().optional().default(false),
});
export interface PageSearchResult {
results: Array<{
id: string;
numericId: string | null;
title: string;
description: string | null;
entityType: string | null;
category: string | null;
readerImportance: number | null;
quality: number | null;
score: number;
snippet: string | null;
}>;
query: string;
total: number;
}
export interface PageDetailRow {
id: string;
numericId: string | null;
title: string;
description: string | null;
llmSummary: string | null;
category: string | null;
subcategory: string | null;
entityType: string | null;
tags: string | null;
quality: number | null;
readerImportance: number | null;
hallucinationRiskLevel: string | null;
hallucinationRiskScore: number | null;
contentPlaintext: string | null;
wordCount: number | null;
lastUpdated: string | null;
contentFormat: string | null;
syncedAt: string;
createdAt: string;
updatedAt: string;
}
export interface RelatedEntry {
id: string;
type: string;
title: string;
score: number;
label?: string;
}
export interface RelatedPagesResult {
entityId: string;
related: RelatedEntry[];
total: number;
}
export interface BacklinkEntry {
id: string;
type: string;
title: string;
relationship?: string;
linkType: string;
weight: number;
}
export interface BacklinksResult {
targetId: string;
backlinks: BacklinkEntry[];
total: number;
}
// ---------------------------------------------------------------------------
// Resources
// ---------------------------------------------------------------------------
/** Canonical resource types — mirrors data/schema.ts ResourceType. */
export const ResourceTypeSchema = z.enum([
"paper",
"blog",
"report",
"book",
"talk",
"podcast",
"government",
"reference",
"web",
]);
export type ResourceType = z.infer<typeof ResourceTypeSchema>;
export const RESOURCE_TYPES = ResourceTypeSchema.options;
export const UpsertResourceSchema = z.object({
id: z.string().min(1).max(200),
url: z.string().url().max(2000),
title: z.string().max(1000).nullable().optional(),
type: ResourceTypeSchema.nullable().optional(),
summary: z.string().max(50000).nullable().optional(),
review: z.string().max(50000).nullable().optional(),
abstract: z.string().max(50000).nullable().optional(),
keyPoints: z.array(z.string().max(2000)).max(50).nullable().optional(),
publicationId: z.string().max(200).nullable().optional(),
authors: z.array(z.string().max(500)).max(5000).nullable().optional(),
publishedDate: DateStringSchema.nullable().optional(),
tags: z.array(z.string().max(200)).max(50).nullable().optional(),
localFilename: z.string().max(500).nullable().optional(),
credibilityOverride: z.number().min(0).max(1).nullable().optional(),
fetchedAt: z.string().datetime().nullable().optional(),
contentHash: z.string().max(200).nullable().optional(),
citedBy: z.array(z.string().min(1).max(200)).max(500).nullable().optional(),
});
export type UpsertResource = z.infer<typeof UpsertResourceSchema>;
export const UpsertResourceBatchSchema = z.object({
items: z.array(UpsertResourceSchema).min(1).max(MAX_BATCH_SIZE),
});
// -- Resources: Response types ------------------------------------------------
export interface UpsertResourceResult {
id: string;
url: string;
}
export interface ResourceRow {
id: string;
url: string;
title: string | null;
type: string | null;
summary: string | null;
review: string | null;
abstract: string | null;
keyPoints: string[] | null;
publicationId: string | null;
authors: string[] | null;
publishedDate: string | null;
tags: string[] | null;
localFilename: string | null;
credibilityOverride: number | null;
fetchedAt: string | null;
contentHash: string | null;
createdAt: string;
updatedAt: string;
}
export interface ResourceStatsResult {
totalResources: number;
totalCitations: number;
citedPages: number;
byType: Record<string, number>;
/** Resources that exist in the DB but have zero citation links. */
orphanedCount: number;
/** Resources with a summary, review, or key_points filled in. */
withMetadata: number;
/** Resources that have been fetched (fetchedAt is set). */
fetched: number;
}
export interface ResourceSearchResult {
results: ResourceRow[];
count: number;
query: string;
}
export interface ResourceListResult {
resources: ResourceRow[];
total: number;
limit: number;
offset: number;
}
// ---------------------------------------------------------------------------
// Entities
// ---------------------------------------------------------------------------
export const SyncEntitySchema = z.object({
id: z.string().min(1).max(300),
numericId: z.string().max(20).nullable().optional(),
entityType: z.string().min(1).max(100),
title: z.string().min(1).max(500),
description: z.string().max(50000).nullable().optional(),
website: z.string().max(2000).nullable().optional(),
tags: z.array(z.string().max(200)).max(100).nullable().optional(),
clusters: z.array(z.string().max(200)).max(50).nullable().optional(),
status: z.string().max(100).nullable().optional(),
lastUpdated: z.string().max(50).nullable().optional(),
customFields: z
.array(
z.object({
label: z.string().max(200),
value: z.string().max(5000),
link: z.string().max(2000).optional(),
})
)
.max(50)
.nullable()
.optional(),
relatedEntries: z
.array(
z.object({
id: z.string().max(300),
type: z.string().max(100),
relationship: z.string().max(100).optional(),
})
)
.max(200)
.nullable()
.optional(),
sources: z
.array(
z.object({
title: z.string().max(500),
url: z.string().max(2000).optional(),
author: z.string().max(300).optional(),
date: z.string().max(50).optional(),
})
)
.max(100)
.nullable()
.optional(),
});
export type SyncEntity = z.infer<typeof SyncEntitySchema>;
export const SyncEntitiesBatchSchema = z.object({
entities: z.array(SyncEntitySchema).min(1).max(MAX_BATCH_SIZE),
});
// ---------------------------------------------------------------------------
// Facts
// ---------------------------------------------------------------------------
export const SyncFactSchema = z.object({
entityId: z.string().min(1).max(300),
factId: z.string().min(1).max(100),
label: z.string().max(500).nullable().optional(),
value: z.string().max(5000).nullable().optional(),
numeric: z.number().nullable().optional(),
low: z.number().nullable().optional(),
high: z.number().nullable().optional(),
asOf: z.string().max(20).nullable().optional(),
measure: z.string().max(100).nullable().optional(),
subject: z.string().max(300).nullable().optional(),
note: z.string().max(5000).nullable().optional(),
source: z.string().max(2000).nullable().optional(),
sourceResource: z.string().max(200).nullable().optional(),
format: z.string().max(100).nullable().optional(),
formatDivisor: z.number().nullable().optional(),
});
export type SyncFact = z.infer<typeof SyncFactSchema>;
export const SyncFactsBatchSchema = z.object({
facts: z.array(SyncFactSchema).min(1).max(500),
});
// -- Facts: Response types ----------------------------------------------------
// Removed in favour of Hono RPC-inferred types (PR #1004).
// Canonical response types are now derived from the server route definition
// via `InferResponseType` in crux/lib/wiki-server/facts.ts and
// apps/web/src/lib/wiki-server.ts. See FactsRoute in routes/facts.ts.
// ---------------------------------------------------------------------------
// Jobs
// ---------------------------------------------------------------------------
export const VALID_JOB_STATUSES = [
"pending",
"claimed",
"running",
"completed",
"failed",
"cancelled",
] as const;
export type JobStatus = (typeof VALID_JOB_STATUSES)[number];
/** Maximum jobs per batch create request. */
export const JOBS_MAX_BATCH_SIZE = 50;
/** Default minutes before a stale claimed/running job is reset by sweep. */
export const STALE_JOB_TIMEOUT_MINUTES = 60;
export const CreateJobSchema = z.object({
type: z.string().min(1).max(100),
params: z.record(z.unknown()).nullable().optional(),
priority: z.number().int().min(0).max(1000).default(0),
maxRetries: z.number().int().min(0).max(10).default(3),
});
/** Output type (server-resolved, defaults applied). */