Repository navigation
Expand file tree
/
Copy pathengine.ts
More file actions
1382 lines (1380 loc) · 48.2 KB
/
Copy pathengine.ts
File metadata and controls
1382 lines (1380 loc) · 48.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
prepareBookPayload,
installBookPayload,
abandonBookPayload,
readBookPayload,
lockBookPayload,
} from "./payload-storage.js";
import { readRetryOrigin, readNodeReuse } from "./retry.js";
import {
createBookBatchCheckpoints,
bookBatchCheckpointsEnabled,
type BookBatchCheckpoints,
} from "./batch-checkpoints.js";
import { validateBookModelAccess } from "./model-access.js";
import { isFrozenBookResume } from "./resume.js";
import { readFeedbackOrigin } from "./feedback-origin.js";
import { appendBookRunLog, type BookRunReporter } from "./run-logs.js";
import { randomUUID } from "node:crypto";
import { sql } from "kysely";
import type { DB, Schema } from "@db/index.js";
import { transact } from "@db/transactions.js";
import { bookFail as fail } from "./errors.js";
import { AppError, systemErrorText } from "../../shared/errors.js";
import {
acceptedBookFailures,
assertBookPublicationAcceptance,
} from "./acceptance-overrides.js";
import {
bookAccess,
bookInputSnapshot,
bookNow,
bookHash,
} from "./management.js";
import {
canReadBookFeedback,
readBookSource,
validateBookSource,
validateBookEvidence,
type BookSourceRuntime,
} from "./sources.js";
import {
bookConfigurationSchema,
claimOutputSchema,
pageOutputSchema,
acceptanceOutputSchema,
bookFeedbackInputSchema,
type BookArtifact,
type BookClaim,
type BookPage,
type Evidence,
type BookConfiguration,
type BookCheck,
type ProvenanceNode,
type ProvenanceEdge,
} from "./protocol.js";
export interface BookRuntime extends BookSourceRuntime {
generate(
stage: "extract" | "synthesize" | "organize" | "acceptance",
input: Record<string, unknown>,
signal: AbortSignal,
report?: BookRunReporter,
checkpoints?: BookBatchCheckpoints,
): Promise<unknown>;
}
type NodeOutput = {
evidence: Evidence[];
claims: BookClaim[];
pages: BookPage[];
checks: BookCheck[];
};
const unique = <T extends { id: string }>(items: T[]) => [
...new Map(items.map((item) => [item.id, item])).values(),
];
export function checkClaims(claims: BookClaim[], evidence: Evidence[]) {
const known = new Set(evidence.map((item) => item.id));
if (new Set(claims.map((claim) => claim.id)).size !== claims.length)
fail(502, "Model returned duplicate claim IDs");
for (const claim of claims)
if (claim.evidenceIds.some((id) => !known.has(id)))
fail(502, `Claim ${claim.id} cited unknown evidence`);
for (const claim of claims) {
if (
claim.evidenceIds.some(
(id) => !claim.evidenceQuotes.some((quote) => quote.evidenceId === id),
)
)
fail(502, "Every cited evidence requires a verified excerpt");
for (const quote of claim.evidenceQuotes) {
if (
!claim.evidenceIds.includes(quote.evidenceId) ||
!evidence
.find((item) => item.id === quote.evidenceId)
?.text.includes(quote.quote)
)
fail(
502,
`Claim ${claim.id}: quotation for ${quote.evidenceId} is absent from that evidence. Copy an exact contiguous excerpt.`,
);
}
}
}
function compactOutput(output: NodeOutput): NodeOutput {
return {
...output,
evidence: output.evidence.map((evidence) => ({
...evidence,
text: [
...new Set(
output.claims.flatMap((claim) =>
claim.evidenceQuotes
.filter((quote) => quote.evidenceId === evidence.id)
.map((quote) => quote.quote),
),
),
].join("\n\n"),
})),
};
}
export function checkPages(
pages: BookPage[],
claims: BookClaim[],
depth: number,
) {
const known = new Set(claims.map((claim) => claim.id)),
paragraphIds = new Set<string>(),
paths = new Set<string>();
if (new Set(pages.map((page) => page.id)).size !== pages.length)
fail(502, "Model returned duplicate page IDs");
for (const page of pages) {
if (
page.path.length + 1 > depth ||
[...page.path, page.title].some(
(part) => /[\u0000-\u001f]/.test(part) || [".", ".."].includes(part),
)
)
fail(502, "Invalid generated document path");
const path = JSON.stringify([...page.path, page.title]);
if (paths.has(path)) fail(502, "Generated document paths collide");
paths.add(path);
for (const paragraph of page.paragraphs) {
if (paragraphIds.has(paragraph.id))
fail(502, "Generated paragraph IDs must be unique across the release");
paragraphIds.add(paragraph.id);
if (paragraph.claimIds.some((id) => !known.has(id)))
fail(502, "Paragraph cited unknown claims");
}
}
}
export function createBookProvenance(
runId: string,
configuration: BookConfiguration,
output: NodeOutput,
executions: ReadonlyMap<string, NodeOutput> = new Map(),
reused: ReadonlyMap<string, string> = new Map(),
): BookArtifact["provenance"] {
const nodes: ProvenanceNode[] = [],
edges: ProvenanceEdge[] = [];
const add = (
id: string,
kind: ProvenanceNode["kind"],
label: string,
detail: Record<string, unknown>,
) => {
nodes.push({ id, kind, label, detail });
return id;
};
const link = (
source: string,
target: string,
relation: ProvenanceEdge["relation"],
) => edges.push({ source, target, relation });
const release = add(`release:${runId}`, "release", "", { runId });
const sourceNodes = new Set<string>();
for (const evidence of output.evidence) {
const source = `source:${evidence.sourceId}:${evidence.sourceRevision}:${bookHash([evidence.sourceVersion, evidence.reference, evidence.contentRef])}`;
if (!sourceNodes.has(source)) {
add(source, "source", evidence.title, {
sourceId: evidence.sourceId,
revision: evidence.sourceRevision,
version: evidence.sourceVersion,
reference: evidence.reference,
...(evidence.contentRef ? { contentRef: evidence.contentRef } : {}),
});
sourceNodes.add(source);
}
add(evidence.id, "evidence", evidence.text || evidence.title, {
sourceId: evidence.sourceId,
blockId: evidence.blockId,
text: evidence.text,
cited: !!evidence.text,
contentHash: evidence.contentHash,
});
link(source, evidence.id, "used");
}
for (const claim of output.claims) {
add(`claim:${claim.id}`, "claim", claim.statement, {
reason: claim.reason,
confidence: claim.confidence,
});
for (const id of claim.evidenceIds)
link(id, `claim:${claim.id}`, "supported");
}
const selected = new Set<string>();
for (const page of output.pages) {
const pageId = add(`page:${page.id}`, "page", page.title, {
pageId: page.id,
path: page.path,
});
link(pageId, release, "composed");
for (const paragraph of page.paragraphs) {
const decision = add(
`decision:${paragraph.id}`,
"decision",
paragraph.reason,
{
claimIds: paragraph.claimIds,
workflowVersion: configuration.workflow.version,
parameters: configuration.workflow.nodes
.filter(
(n) =>
["synthesize", "organize"].includes(n.type) &&
executions
.get(n.id)
?.pages.some((p) =>
p.paragraphs.some((q) => q.id === paragraph.id),
),
)
.map((n) => ({ id: n.id, parameters: n.parameters })),
},
);
const paragraphId = add(
`paragraph:${paragraph.id}`,
"paragraph",
paragraph.markdown,
{ pageId: page.id },
);
for (const id of paragraph.claimIds) {
selected.add(id);
link(`claim:${id}`, decision, "adopted");
}
link(decision, paragraphId, "generated");
link(paragraphId, pageId, "composed");
}
}
for (const claim of output.claims)
if (!selected.has(claim.id)) {
const id = add(`unselected:${claim.id}`, "decision", "", {
status: "not_selected_for_release",
claimId: claim.id,
});
link(`claim:${claim.id}`, id, "used");
}
for (const node of configuration.workflow.nodes)
add(`execution:${runId}:${node.id}`, "execution", node.label, {
nodeId: node.id,
type: node.type,
parameters: node.parameters,
});
for (const [nodeId, priorRunId] of reused) {
const priorId = `execution:${priorRunId}:${nodeId}`;
add(priorId, "execution", "", {
nodeId,
runId: priorRunId,
type: configuration.workflow.nodes.find((node) => node.id === nodeId)!
.type,
reuseOrigin: true,
});
const execution = nodes.find(
(node) => node.id === `execution:${runId}:${nodeId}`,
)!;
execution.detail.reusedFromRunId = priorRunId;
link(priorId, execution.id, "used");
}
for (const edge of configuration.workflow.edges)
link(
`execution:${runId}:${edge.source}`,
`execution:${runId}:${edge.target}`,
"used",
);
const known = new Set(nodes.map((node) => node.id));
for (const definition of configuration.workflow.nodes) {
const trace = executions.get(definition.id);
if (!trace) continue;
const execution = `execution:${runId}:${definition.id}`;
for (const evidence of trace.evidence)
if (known.has(evidence.id)) link(evidence.id, execution, "used");
if (definition.type === "extract")
for (const claim of trace.claims)
if (known.has(`claim:${claim.id}`))
link(execution, `claim:${claim.id}`, "generated");
if (definition.type === "organize" || definition.type === "synthesize")
for (const page of trace.pages)
for (const paragraph of page.paragraphs) {
if (known.has(`paragraph:${paragraph.id}`))
link(execution, `paragraph:${paragraph.id}`, "generated");
}
}
const publisher = configuration.workflow.nodes.find(
(node) => node.type === "publish",
)!;
link(`execution:${runId}:${publisher.id}`, release, "generated");
return { nodes, edges };
}
async function actorFor(db: DB, run: Schema["knowledge_book_runs"]) {
const actor = await db
.selectFrom("users")
.select(["id", "display_name", "admin"])
.where("id", "=", run.actor_id)
.where("status", "=", "active")
.executeTakeFirst();
if (!actor) fail(403, "Run actor is unavailable");
return actor;
}
async function assertCurrent(
db: DB,
run: Schema["knowledge_book_runs"],
lease: string,
) {
const current = await db
.selectFrom("knowledge_book_runs")
.select(["status", "lease_id"])
.where("id", "=", run.id)
.executeTakeFirst();
if (current?.status !== "running" || current.lease_id !== lease)
fail(409, "Run was cancelled or its lease changed");
const actor = await actorFor(db, run),
{ book } = await bookAccess(db, actor, run.book_id, 3);
if (
(book.revision !== run.configuration_revision ||
book.configuration !== run.configuration) &&
!(await isFrozenBookResume(db, run.id))
)
fail(409, "Workflow configuration changed; run again");
if ((await bookInputSnapshot(db, run.book_id)).hash !== run.input_hash)
fail(409, "Sources or feedback changed; run again");
return { actor, book };
}
async function publishRun(
db: DB,
run: Schema["knowledge_book_runs"],
lease: string,
artifact: BookArtifact,
runtime: BookRuntime,
) {
await assertCurrent(db, run, lease);
await assertBookPublicationAcceptance(db, run, artifact);
await validateBookEvidence(db, run.book_id, artifact.evidence, runtime);
const id = randomUUID();
const prepared = await prepareBookPayload(
db,
{ bookId: run.book_id, ownerKind: "run", ownerId: run.id, nodeId: "" },
JSON.stringify(artifact),
);
const publisher = bookConfigurationSchema
.parse(JSON.parse(run.configuration))
.workflow.nodes.find((n) => n.type === "publish")!;
const nodePrepared = await prepareBookPayload(
db,
{
bookId: run.book_id,
ownerKind: "node",
ownerId: run.id,
nodeId: publisher.id,
},
JSON.stringify({
evidence: artifact.evidence,
claims: artifact.claims,
pages: artifact.pages,
checks: artifact.checks,
}),
);
try {
return await transact(db, async (tx) => {
await lockBookPayload(tx, run.book_id);
const { actor, book } = await assertCurrent(tx, run, lease);
await assertBookPublicationAcceptance(tx, run, artifact);
const nodeMarker = await installBookPayload(tx, nodePrepared);
await tx
.updateTable("knowledge_book_node_runs")
.set({
output: nodeMarker,
status: "completed",
completed_at: bookNow(),
})
.where("run_id", "=", run.id)
.where("node_id", "=", publisher.id)
.execute();
const runMarker = await installBookPayload(tx, prepared);
const releaseMarker = await installBookPayload(tx, prepared, {
bookId: run.book_id,
ownerKind: "release",
ownerId: id,
nodeId: "",
});
const last = await tx
.selectFrom("knowledge_book_releases")
.select("revision")
.where("book_id", "=", run.book_id)
.orderBy("revision", "desc")
.executeTakeFirst();
const revision = (last?.revision ?? 0) + 1,
now = bookNow();
const updated = await tx
.updateTable("knowledge_books")
.set({ published_release_id: id, updated_at: now })
.where("id", "=", run.book_id)
.where("revision", "=", book.revision)
.where(
"published_release_id",
book.published_release_id === null ? "is" : "=",
book.published_release_id,
)
.executeTakeFirst();
if (!Number(updated.numUpdatedRows))
fail(409, "Another run published a release; run again");
await tx
.insertInto("knowledge_book_releases")
.values({
id,
book_id: run.book_id,
run_id: run.id,
revision,
artifact: releaseMarker,
created_at: now,
})
.execute();
await tx
.updateTable("knowledge_book_runs")
.set({
status: "published",
artifact: runMarker,
lease_id: null,
updated_at: now,
})
.where("id", "=", run.id)
.where("status", "=", "running")
.where("lease_id", "=", lease)
.execute();
await tx
.insertInto("audit_events")
.values({
id: randomUUID(),
actor_id: actor.id,
resource_id: run.book_id,
action: "knowledge_book.published",
created_at: now,
})
.execute();
await appendBookRunLog(tx, run, null, {
code: "run_published",
value: artifact.pages.length,
});
return { id, revision };
});
} catch (error) {
await abandonBookPayload(db, prepared.operationId);
await abandonBookPayload(db, nodePrepared.operationId);
throw error;
}
}
/** The only writer of book releases. Every published artifact comes from validated node outputs. */
export async function executeBookRun(db: DB, id: string, runtime: BookRuntime) {
const storedRun = await db
.selectFrom("knowledge_book_runs")
.selectAll()
.where("id", "=", id)
.executeTakeFirst();
if (
!storedRun ||
!["queued", "queued_publish", "queued_resume"].includes(storedRun.status)
)
return;
let run: Schema["knowledge_book_runs"] = storedRun;
const resumeNodes = run.status === "queued_resume";
const resumePublication = run.status === "queued_publish",
lease = randomUUID(),
now = bookNow();
const claimed = await db
.updateTable("knowledge_book_runs")
.set({
status: "running",
lease_id: lease,
started_at: run.started_at ?? now,
heartbeat_at: now,
updated_at: now,
})
.where("id", "=", id)
.where("status", "=", run.status)
.executeTakeFirst();
if (!Number(claimed.numUpdatedRows)) return;
run = { ...run, status: "running", lease_id: lease };
const ownsLease = sql<boolean>`exists(select 1 from knowledge_book_runs worker where worker.id = ${id} and worker.status = 'running' and worker.lease_id = ${lease})`;
const coordinator = new AbortController();
const signal = AbortSignal.any([
coordinator.signal,
// Whole-book inspection and bounded evidence rechecks can contain hundreds
// of individually bounded calls. Keep a finite run deadline without
// cancelling a healthy long-form worker halfway through its final stage.
AbortSignal.timeout(240 * 60_000),
]);
const heartbeat = setInterval(() => {
void db
.updateTable("knowledge_book_runs")
.set({ heartbeat_at: bookNow() })
.where("id", "=", id)
.where("status", "=", "running")
.where("lease_id", "=", lease)
.executeTakeFirst()
.then((result) => {
if (!Number(result.numUpdatedRows))
coordinator.abort(
new Error("Run was cancelled or its lease changed"),
);
})
.catch((error) => coordinator.abort(error));
}, 15000);
heartbeat.unref();
let activeNode: string | undefined;
try {
await appendBookRunLog(db, run, null, { code: "run_started" });
const configuration = bookConfigurationSchema.parse(
JSON.parse(run.configuration),
);
await assertCurrent(db, run, lease);
if (resumePublication) {
if (!run.artifact) fail(409, "Run has no completed artifact");
const publisher = configuration.workflow.nodes.find(
(node) => node.type === "publish",
)!;
activeNode = publisher.id;
const artifact = await readBookPayload<BookArtifact>(db, run.artifact, {
bookId: run.book_id,
ownerKind: "run",
ownerId: id,
nodeId: "",
});
const task = await db
.selectFrom("knowledge_book_human_tasks")
.select(["id", "resolution"])
.where("run_id", "=", id)
.where("kind", "=", "publication")
.where("status", "=", "resolved")
.executeTakeFirst();
if (task?.resolution) {
const resolution = JSON.parse(task.resolution);
artifact.provenance.nodes.push({
id: `human:${task.id}`,
kind: "decision",
label:
resolution.decision === "publish" ? "publish" : resolution.note,
detail: resolution,
});
artifact.provenance.edges.push(
{
source: `execution:${id}:${publisher.id}`,
target: `human:${task.id}`,
relation: "used",
},
{
source: `human:${task.id}`,
target: `release:${id}`,
relation: "adopted",
},
);
}
await publishRun(db, run, lease, artifact, runtime);
await db
.updateTable("knowledge_book_node_runs")
.set({ status: "completed", completed_at: bookNow() })
.where("run_id", "=", id)
.where("node_id", "=", publisher.id)
.execute();
return;
}
const priorRunId = await readRetryOrigin(db, id);
const rejectedReviews =
priorRunId || resumeNodes
? await db
.selectFrom("knowledge_book_node_runs")
.select(["node_id", "output"])
.where("run_id", "=", priorRunId ?? id)
.where("type", "=", "acceptance")
.where("status", "=", "failed")
.execute()
: [];
const snapshot = await bookInputSnapshot(db, run.book_id),
outputs = new Map<string, NodeOutput>(),
pending = new Set(configuration.workflow.nodes.map((node) => node.id));
const sourceCache = new Map<string, Promise<Evidence[]>>();
if (resumeNodes)
for (const node of await db
.selectFrom("knowledge_book_node_runs")
.selectAll()
.where("run_id", "=", id)
.where("status", "=", "completed")
.execute()) {
outputs.set(
node.node_id,
await readBookPayload<NodeOutput>(db, node.output, {
bookId: run.book_id,
ownerKind: "node",
ownerId: id,
nodeId: node.node_id,
}),
);
pending.delete(node.node_id);
}
if (resumeNodes)
for (const [nodeId, output] of await acceptedBookFailures(db, run)) {
outputs.set(nodeId, output);
pending.delete(nodeId);
}
async function persistNode(
nodeId: string,
output: NodeOutput,
values: Partial<Schema["knowledge_book_node_runs"]>,
transition?: (tx: DB) => Promise<void>,
) {
await assertCurrent(db, run, lease);
const prepared = await prepareBookPayload(
db,
{ bookId: run.book_id, ownerKind: "node", ownerId: id, nodeId },
JSON.stringify(compactOutput(output)),
);
try {
return await transact(db, async (tx) => {
await lockBookPayload(tx, run.book_id);
await assertCurrent(tx, run, lease);
const marker = await installBookPayload(tx, prepared);
const result = await tx
.updateTable("knowledge_book_node_runs")
.set({ ...values, output: marker })
.where("run_id", "=", id)
.where("node_id", "=", nodeId)
.executeTakeFirst();
if (!Number(result.numUpdatedRows))
fail(409, "Run node no longer exists");
await transition?.(tx);
return result;
});
} catch (error) {
await abandonBookPayload(db, prepared.operationId);
throw error;
}
}
async function feedbackText(row: Schema["knowledge_book_feedback"]) {
const detail = bookFeedbackInputSchema.parse(JSON.parse(row.detail));
const origin = await readFeedbackOrigin(db, row.id, row.revision);
const contributor = await db
.selectFrom("users")
.select(["id", "display_name", "admin"])
.where("id", "=", row.author_id)
.where("status", "=", "active")
.executeTakeFirst();
if (!contributor) fail(403, "Feedback contributor is unavailable");
await bookAccess(db, contributor, run!.book_id, 2);
if (!detail.releaseId) return JSON.stringify({ ...detail, origin });
if (!(await canReadBookFeedback(db, contributor, detail)))
fail(403, "Anchored feedback lost original evidence access");
const prior = await db
.selectFrom("knowledge_book_releases")
.select("artifact")
.where("id", "=", detail.releaseId)
.where("book_id", "=", run!.book_id)
.executeTakeFirstOrThrow();
const artifact = await readBookPayload<BookArtifact>(db, prior.artifact),
page = artifact.pages.find((page) => page.id === detail.pageId);
const paragraphs = detail.paragraphId
? page?.paragraphs.filter((p) => p.id === detail.paragraphId)
: page?.paragraphs;
return JSON.stringify({
...detail,
origin,
target: page
? { title: page.title, path: page.path, paragraphs }
: null,
});
}
async function hydrate(items: Evidence[]) {
const result: Evidence[] = [];
const checkedSources = new Set<string>();
for (const item of items) {
if (item.reference.kind === "feedback") {
const feedback = snapshot.feedback.find(
(row) =>
row.id === item.sourceId && row.revision === item.sourceRevision,
);
if (!feedback) fail(409, "Feedback changed during the run");
result.push({
...item,
text: await feedbackText(feedback),
});
} else {
const source = snapshot.sources.find(
(source) =>
source.id === item.sourceId &&
source.revision === item.sourceRevision,
);
if (!source) fail(409, "Source changed during the run");
if (!checkedSources.has(source.id)) {
const contributor = await db
.selectFrom("users")
.select(["id", "display_name", "admin"])
.where("id", "=", source.creator_id)
.where("status", "=", "active")
.executeTakeFirst();
if (!contributor) fail(403, "Source contributor is unavailable");
await bookAccess(db, contributor, run.book_id, 3);
await validateBookSource(
db,
contributor,
JSON.parse(source.configuration),
);
checkedSources.add(source.id);
}
if (!sourceCache.has(source.id))
sourceCache.set(source.id, readBookSource(db, source, runtime));
const live = (await sourceCache.get(source.id)!).find(
(evidence) => evidence.id === item.id,
);
if (!live || live.contentHash !== item.contentHash)
fail(409, "Source content changed during the run");
result.push(live);
}
}
return result;
}
async function executeNode(
node: BookConfiguration["workflow"]["nodes"][number],
) {
const nodeIndex = configuration.workflow.nodes.indexOf(node);
const report: BookRunReporter = async (event) => {
signal.throwIfAborted();
await assertCurrent(db, run, lease);
await appendBookRunLog(db, run, nodeIndex, event);
};
try {
await assertCurrent(db, run, lease);
const upstream = configuration.workflow.edges
.filter((edge) => edge.target === node.id)
.map((edge) => outputs.get(edge.source)!);
const input: NodeOutput = {
evidence: unique(upstream.flatMap((out) => out.evidence)),
claims: unique(upstream.flatMap((out) => out.claims)),
pages: unique(upstream.flatMap((out) => out.pages)),
checks: upstream.flatMap((out) => out.checks),
};
const output: NodeOutput = structuredClone(input);
await db
.insertInto("knowledge_book_node_runs")
.values({
run_id: id,
node_id: node.id,
type: node.type,
status: "running",
input_refs: JSON.stringify(
configuration.workflow.edges
.filter((edge) => edge.target === node.id)
.map((edge) => edge.source),
),
output: "",
error: "",
started_at: bookNow(),
completed_at: null,
})
.onConflict((conflict) =>
conflict
.columns(["run_id", "node_id"])
.doUpdateSet({
status: "running",
error: "",
started_at: bookNow(),
completed_at: null,
})
.where("knowledge_book_node_runs.status", "in", [
"failed",
"cancelled",
]),
)
.execute();
await report({ code: "node_started" });
if (node.type === "sources") {
const selected = node.parameters.sourceIds.length
? snapshot.sources.filter((source) =>
node.parameters.sourceIds.includes(source.id),
)
: snapshot.sources;
if (
node.parameters.sourceIds.some(
(sourceId) => !selected.some((source) => source.id === sourceId),
)
)
fail(409, "Workflow selects a missing or inactive source");
output.evidence = [];
for (const source of selected) {
const ordinal = selected.indexOf(source) + 1;
await report({
code: "source_loading",
value: ordinal,
total: selected.length,
});
if (!sourceCache.has(source.id))
sourceCache.set(source.id, readBookSource(db, source, runtime));
const evidence = await sourceCache.get(source.id)!;
output.evidence.push(...evidence);
await report({
code: "source_loaded",
value: evidence.length,
total: ordinal,
});
}
} else if (node.type === "feedback") {
output.evidence = [];
for (const row of snapshot.feedback) {
const detail = bookFeedbackInputSchema.parse(
JSON.parse(row.detail),
),
text = await feedbackText(row);
output.evidence.push({
id: `feedback_${row.id}_${row.revision}`,
sourceId: row.id,
sourceRevision: row.revision,
sourceVersion: String(row.revision),
title: detail.kind,
text,
contentHash: bookHash(text),
reference: {
kind: "feedback",
feedbackId: row.id,
revision: row.revision,
},
blockId: row.id,
});
}
} else if (node.type === "human_review") {
await persistNode(
node.id,
output,
{ status: "awaiting_input", completed_at: bookNow() },
async (tx) => {
await tx
.insertInto("knowledge_book_human_tasks")
.values({
id: randomUUID(),
book_id: run.book_id,
run_id: id,
node_id: node.id,
kind: "review",
title: node.label || "",
status: "pending",
revision: 1,
input_hash: run.input_hash,
resolution: "",
created_at: bookNow(),
updated_at: bookNow(),
})
.onConflict((conflict) =>
conflict.columns(["run_id", "node_id", "kind"]).doUpdateSet({
status: "pending",
revision: sql`knowledge_book_human_tasks.revision + 1`,
updated_at: bookNow(),
}),
)
.execute();
await tx
.updateTable("knowledge_book_runs")
.set({
status: "awaiting_input",
lease_id: null,
updated_at: bookNow(),
})
.where("id", "=", id)
.where("status", "=", "running")
.where("lease_id", "=", lease)
.execute();
},
);
await appendBookRunLog(db, run, nodeIndex, { code: "waiting_input" });
return;
} else if (node.type === "publish") {
if (!output.pages.length)
fail(422, "Publication requires generated knowledge pages");
checkPages(
output.pages,
output.claims,
configuration.maxDocumentDepth,
);
await assertBookPublicationAcceptance(db, run, output);
const compact = compactOutput(output);
const artifact: BookArtifact = {
version: 1,
...compact,
provenance: createBookProvenance(
id,
configuration,
compact,
outputs,
await readNodeReuse(
db,
id,
configuration.workflow.nodes.map((node) => node.id),
),
),
};
const decisions = await db
.selectFrom("knowledge_book_human_tasks")
.select(["id", "node_id", "resolution"])
.where("run_id", "=", id)
.where("status", "=", "resolved")
.execute();
for (const decision of decisions) {
const resolution = JSON.parse(decision.resolution);
artifact.provenance.nodes.push({
id: `human:${decision.id}`,
kind: "decision",
label:
resolution.decision === "publish" ? "publish" : resolution.note,
detail: resolution,
});
artifact.provenance.edges.push(
{
source: `execution:${id}:${decision.node_id}`,
target: `human:${decision.id}`,
relation: "used",
},
{
source: `human:${decision.id}`,
target: `release:${id}`,
relation: "adopted",
},
);
}
if (JSON.stringify(artifact).length > 10_000_000)
fail(
413,
"Book release exceeds limits; split the workflow into smaller books",
);
if (configuration.autoPublish)
await publishRun(db, run, lease, artifact, runtime);
else {
const preparedArtifact = await prepareBookPayload(
db,
{
bookId: run.book_id,
ownerKind: "run",
ownerId: id,
nodeId: "",
},
JSON.stringify(artifact),
);
try {
await persistNode(
node.id,
output,
{ status: "awaiting_publication", completed_at: bookNow() },
async (tx) => {
await tx
.insertInto("knowledge_book_human_tasks")
.values({
id: randomUUID(),
book_id: run.book_id,
run_id: id,
node_id: node.id,
kind: "publication",
title: node.label || "",
status: "pending",
revision: 1,
input_hash: run.input_hash,
resolution: "",
created_at: bookNow(),
updated_at: bookNow(),
})
.onConflict((conflict) =>
conflict
.columns(["run_id", "node_id", "kind"])
.doUpdateSet({
status: "pending",
revision: sql`knowledge_book_human_tasks.revision + 1`,
updated_at: bookNow(),
}),
)
.execute();
await tx
.updateTable("knowledge_book_runs")
.set({
status: "awaiting_publication",
artifact: await installBookPayload(tx, preparedArtifact),
lease_id: null,
updated_at: bookNow(),
})
.where("id", "=", id)
.where("status", "=", "running")
.where("lease_id", "=", lease)
.execute();
await appendBookRunLog(tx, run, nodeIndex, {
code: "waiting_publication",
});
},