@thanh01.pmt/research-kit 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/academic/index.cjs +4 -4
  2. package/dist/academic/index.cjs.map +1 -1
  3. package/dist/academic/index.js +2 -2
  4. package/dist/agent/index.cjs +1137 -301
  5. package/dist/agent/index.cjs.map +1 -1
  6. package/dist/agent/index.d.cts +1 -1
  7. package/dist/agent/index.d.ts +1 -1
  8. package/dist/agent/index.js +7 -7
  9. package/dist/chunk-4S6UMYBA.js +1931 -0
  10. package/dist/chunk-4S6UMYBA.js.map +1 -0
  11. package/dist/{chunk-S3JUCDKD.js → chunk-6U2H2DMQ.js} +7 -7
  12. package/dist/{chunk-S3JUCDKD.js.map → chunk-6U2H2DMQ.js.map} +1 -1
  13. package/dist/{chunk-ZNGU4ZYX.js → chunk-7BGR4E37.js} +5 -5
  14. package/dist/{chunk-ZNGU4ZYX.js.map → chunk-7BGR4E37.js.map} +1 -1
  15. package/dist/{chunk-AKEI7H2C.js → chunk-EWIAA2CC.js} +4 -4
  16. package/dist/{chunk-AKEI7H2C.js.map → chunk-EWIAA2CC.js.map} +1 -1
  17. package/dist/{chunk-QQZQNBJC.js → chunk-JV6Z6WUQ.js} +4 -4
  18. package/dist/{chunk-QQZQNBJC.js.map → chunk-JV6Z6WUQ.js.map} +1 -1
  19. package/dist/{chunk-2RMBLKP5.js → chunk-MJIREPKJ.js} +3 -3
  20. package/dist/{chunk-2RMBLKP5.js.map → chunk-MJIREPKJ.js.map} +1 -1
  21. package/dist/{chunk-KXJDQBSJ.js → chunk-PFECHAAR.js} +12 -5
  22. package/dist/chunk-PFECHAAR.js.map +1 -0
  23. package/dist/{chunk-NSY6KU4G.js → chunk-SEHHDO7X.js} +5 -5
  24. package/dist/{chunk-NSY6KU4G.js.map → chunk-SEHHDO7X.js.map} +1 -1
  25. package/dist/{chunk-RYLZYZRF.js → chunk-UCPWBRZ2.js} +3 -3
  26. package/dist/{chunk-RYLZYZRF.js.map → chunk-UCPWBRZ2.js.map} +1 -1
  27. package/dist/evidence/index.cjs +9 -2
  28. package/dist/evidence/index.cjs.map +1 -1
  29. package/dist/evidence/index.js +2 -2
  30. package/dist/harvester/index.cjs +6 -6
  31. package/dist/harvester/index.cjs.map +1 -1
  32. package/dist/harvester/index.js +5 -5
  33. package/dist/{index-onQDKDNo.d.cts → index-BOwJ1jON.d.cts} +317 -71
  34. package/dist/{index-CN8gei7k.d.ts → index-_aiOh8jX.d.ts} +317 -71
  35. package/dist/index.cjs +1145 -302
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.d.cts +1 -1
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.js +25 -18
  40. package/dist/index.js.map +1 -1
  41. package/dist/pipeline/index.cjs +13 -6
  42. package/dist/pipeline/index.cjs.map +1 -1
  43. package/dist/pipeline/index.js +6 -6
  44. package/package.json +1 -1
  45. package/dist/chunk-KXJDQBSJ.js.map +0 -1
  46. package/dist/chunk-WWQ45RQK.js +0 -1114
  47. package/dist/chunk-WWQ45RQK.js.map +0 -1
@@ -3,12 +3,44 @@
3
3
  var zod = require('zod');
4
4
 
5
5
  // src/agent/types.ts
6
+ var RESEARCH_MODE_PRESETS = {
7
+ search: {
8
+ mode: "search",
9
+ timeoutMs: 15e3,
10
+ maxChannels: 1,
11
+ channelConcurrency: 1,
12
+ maxRounds: 1,
13
+ maxQueriesPerRound: 1,
14
+ maxScrapePerRound: 0,
15
+ verifyClaims: false
16
+ },
17
+ research: {
18
+ mode: "research",
19
+ timeoutMs: 18e4,
20
+ maxChannels: 2,
21
+ channelConcurrency: 2,
22
+ maxRounds: 1,
23
+ maxQueriesPerRound: 3,
24
+ maxScrapePerRound: 3,
25
+ verifyClaims: false
26
+ },
27
+ "deep-research": {
28
+ mode: "deep-research",
29
+ timeoutMs: 6e5,
30
+ maxChannels: 5,
31
+ channelConcurrency: 2,
32
+ maxRounds: 3,
33
+ maxQueriesPerRound: 4,
34
+ maxScrapePerRound: 4,
35
+ verifyClaims: true
36
+ }
37
+ };
6
38
  var RESEARCH_PROFILE_PRESETS = {
7
39
  fast_grounded: {
8
- maxRounds: 2,
40
+ maxRounds: 1,
9
41
  maxQueriesPerRound: 3,
10
42
  maxScrapePerRound: 3,
11
- timeoutMs: 35e3,
43
+ timeoutMs: 18e4,
12
44
  enableWeb: true,
13
45
  enableAcademic: false,
14
46
  enableSocialPulse: false,
@@ -18,57 +50,57 @@ var RESEARCH_PROFILE_PRESETS = {
18
50
  maxRounds: 3,
19
51
  maxQueriesPerRound: 4,
20
52
  maxScrapePerRound: 4,
21
- timeoutMs: 12e4,
53
+ timeoutMs: 6e5,
22
54
  enableWeb: true,
23
55
  enableAcademic: true,
24
56
  enableSocialPulse: true,
25
57
  enableStemOer: true
26
58
  },
27
59
  technical: {
28
- maxRounds: 2,
60
+ maxRounds: 1,
29
61
  maxQueriesPerRound: 3,
30
- maxScrapePerRound: 4,
31
- timeoutMs: 45e3,
62
+ maxScrapePerRound: 3,
63
+ timeoutMs: 18e4,
32
64
  enableWeb: true,
33
65
  enableAcademic: false,
34
66
  enableSocialPulse: true,
35
67
  enableStemOer: false
36
68
  },
37
69
  academic: {
38
- maxRounds: 2,
70
+ maxRounds: 1,
39
71
  maxQueriesPerRound: 3,
40
72
  maxScrapePerRound: 2,
41
- timeoutMs: 45e3,
73
+ timeoutMs: 18e4,
42
74
  enableWeb: true,
43
75
  enableAcademic: true,
44
76
  enableSocialPulse: false,
45
77
  enableStemOer: false
46
78
  },
47
79
  social_pulse: {
48
- maxRounds: 2,
80
+ maxRounds: 1,
49
81
  maxQueriesPerRound: 3,
50
82
  maxScrapePerRound: 2,
51
- timeoutMs: 35e3,
83
+ timeoutMs: 18e4,
52
84
  enableWeb: true,
53
85
  enableAcademic: false,
54
86
  enableSocialPulse: true,
55
87
  enableStemOer: false
56
88
  },
57
89
  curriculum_oer: {
58
- maxRounds: 2,
90
+ maxRounds: 1,
59
91
  maxQueriesPerRound: 3,
60
92
  maxScrapePerRound: 3,
61
- timeoutMs: 45e3,
93
+ timeoutMs: 18e4,
62
94
  enableWeb: true,
63
95
  enableAcademic: false,
64
96
  enableSocialPulse: false,
65
97
  enableStemOer: true
66
98
  },
67
99
  general: {
68
- maxRounds: 2,
100
+ maxRounds: 1,
69
101
  maxQueriesPerRound: 3,
70
102
  maxScrapePerRound: 3,
71
- timeoutMs: 45e3,
103
+ timeoutMs: 18e4,
72
104
  enableWeb: true,
73
105
  enableAcademic: false,
74
106
  enableSocialPulse: false,
@@ -378,6 +410,443 @@ ${i.tables.join("\n")}`
378
410
  }
379
411
  };
380
412
 
413
+ // src/agent/decisionRouter.ts
414
+ var QUESTION_FACETS = [
415
+ "official_spec",
416
+ "how_to_example",
417
+ "pitfalls",
418
+ "pedagogy_theory",
419
+ "standards_policy",
420
+ "emerging_trend",
421
+ "learning_resources"
422
+ ];
423
+ var SOURCE_CHANNELS = [
424
+ "web_docs",
425
+ "academic",
426
+ "social_pulse",
427
+ "stem_oer",
428
+ "video_media"
429
+ ];
430
+ var PRIOR_MATRIX = {
431
+ official_spec: {
432
+ web_docs: 0.95,
433
+ academic: 0.2,
434
+ social_pulse: 0.3,
435
+ stem_oer: 0.15,
436
+ video_media: 0.25
437
+ },
438
+ how_to_example: {
439
+ web_docs: 0.9,
440
+ academic: 0.15,
441
+ social_pulse: 0.65,
442
+ stem_oer: 0.35,
443
+ video_media: 0.6
444
+ },
445
+ pitfalls: {
446
+ web_docs: 0.65,
447
+ academic: 0.25,
448
+ social_pulse: 0.9,
449
+ stem_oer: 0.1,
450
+ video_media: 0.35
451
+ },
452
+ pedagogy_theory: {
453
+ web_docs: 0.45,
454
+ academic: 0.95,
455
+ social_pulse: 0.2,
456
+ stem_oer: 0.7,
457
+ video_media: 0.3
458
+ },
459
+ standards_policy: {
460
+ web_docs: 0.75,
461
+ academic: 0.85,
462
+ social_pulse: 0.15,
463
+ stem_oer: 0.6,
464
+ video_media: 0.15
465
+ },
466
+ emerging_trend: {
467
+ web_docs: 0.6,
468
+ academic: 0.45,
469
+ social_pulse: 0.95,
470
+ stem_oer: 0.1,
471
+ video_media: 0.5
472
+ },
473
+ learning_resources: {
474
+ web_docs: 0.65,
475
+ academic: 0.3,
476
+ social_pulse: 0.25,
477
+ stem_oer: 0.95,
478
+ video_media: 0.7
479
+ }
480
+ };
481
+ function clampScore0to4(val, fallback = 1) {
482
+ const n = Number(val);
483
+ if (!Number.isFinite(n)) return fallback;
484
+ return Math.max(0, Math.min(4, n));
485
+ }
486
+ function computeContractComplexityScore(contract) {
487
+ let score = 0;
488
+ const reqAttrs = contract.acceptanceCriteria?.requiredAttributes?.length || 0;
489
+ const reqSecs = contract.requiredSections?.length || 0;
490
+ const totalReqs = reqAttrs + reqSecs;
491
+ if (totalReqs >= 4) score += 2;
492
+ else if (totalReqs >= 2) score += 1;
493
+ if (contract.acceptanceCriteria?.requireCodeExamples || contract.acceptanceCriteria?.requireTables) {
494
+ score += 1;
495
+ }
496
+ if ((contract.acceptanceCriteria?.minSources ?? 2) >= 4 || Boolean(contract.outputSchema)) {
497
+ score += 1;
498
+ }
499
+ return Math.min(4, score);
500
+ }
501
+ function inferFallbackFacetProbabilities(contract) {
502
+ const dist = {
503
+ official_spec: 0.25,
504
+ how_to_example: 0.25,
505
+ pitfalls: 0.15,
506
+ pedagogy_theory: 0.1,
507
+ standards_policy: 0.05,
508
+ emerging_trend: 0.1,
509
+ learning_resources: 0.1
510
+ };
511
+ if (contract.profile === "academic" || (contract.acceptanceCriteria?.minPeerReviewedSources ?? 0) >= 1) {
512
+ return {
513
+ official_spec: 0.05,
514
+ how_to_example: 0.05,
515
+ pitfalls: 0.05,
516
+ pedagogy_theory: 0.5,
517
+ standards_policy: 0.25,
518
+ emerging_trend: 0.05,
519
+ learning_resources: 0.05
520
+ };
521
+ }
522
+ if (contract.profile === "social_pulse") {
523
+ return {
524
+ official_spec: 0.05,
525
+ how_to_example: 0.15,
526
+ pitfalls: 0.35,
527
+ pedagogy_theory: 0.02,
528
+ standards_policy: 0.03,
529
+ emerging_trend: 0.35,
530
+ learning_resources: 0.05
531
+ };
532
+ }
533
+ if (contract.profile === "curriculum_oer") {
534
+ return {
535
+ official_spec: 0.05,
536
+ how_to_example: 0.15,
537
+ pitfalls: 0.05,
538
+ pedagogy_theory: 0.2,
539
+ standards_policy: 0.1,
540
+ emerging_trend: 0.05,
541
+ learning_resources: 0.4
542
+ };
543
+ }
544
+ return dist;
545
+ }
546
+ function rankChannelsByExpectedPrior(facetProbabilities, contract) {
547
+ const scores = {
548
+ web_docs: 0,
549
+ academic: 0,
550
+ social_pulse: 0,
551
+ stem_oer: 0,
552
+ video_media: 0
553
+ };
554
+ for (const facet of QUESTION_FACETS) {
555
+ const p = facetProbabilities[facet] ?? 0;
556
+ const row = PRIOR_MATRIX[facet];
557
+ for (const channel of SOURCE_CHANNELS) {
558
+ scores[channel] += p * row[channel];
559
+ }
560
+ }
561
+ if ((contract.acceptanceCriteria?.minPeerReviewedSources ?? 0) >= 1 || contract.profile === "academic") {
562
+ scores.academic += 0.3;
563
+ }
564
+ if (contract.profile === "social_pulse" || contract.acceptanceCriteria?.recencyDays !== void 0 && contract.acceptanceCriteria.recencyDays <= 30) {
565
+ scores.social_pulse += 0.2;
566
+ }
567
+ if (contract.acceptanceCriteria?.requireCodeExamples || contract.acceptanceCriteria?.requireTables || contract.context?.hardwarePlatform || contract.context?.softwareEnv) {
568
+ scores.web_docs += 0.15;
569
+ }
570
+ if (contract.profile === "curriculum_oer") {
571
+ scores.stem_oer += 0.3;
572
+ }
573
+ if (contract.preferredChannels && contract.preferredChannels.length > 0) {
574
+ contract.preferredChannels.forEach((ch, idx) => {
575
+ if (scores[ch] !== void 0) {
576
+ scores[ch] += Math.max(0.25, 0.6 - idx * 0.1);
577
+ }
578
+ });
579
+ }
580
+ return SOURCE_CHANNELS.map((channel) => ({
581
+ channel,
582
+ score: Number(scores[channel].toFixed(4))
583
+ })).sort((a, b) => b.score - a.score);
584
+ }
585
+ async function classifyModeAndPrior(contract, decision) {
586
+ let requestedMode = contract.mode ?? "auto";
587
+ if (!contract.mode && contract.profile) {
588
+ if (contract.profile === "deep_autonomous") {
589
+ requestedMode = "deep-research";
590
+ } else if (contract.profile !== "auto") {
591
+ requestedMode = "research";
592
+ }
593
+ }
594
+ const contractScore = computeContractComplexityScore(contract);
595
+ const hardEscalated = contract.acceptanceCriteria?.verifyClaims === true || (contract.acceptanceCriteria?.minPeerReviewedSources ?? 0) >= 2;
596
+ let readingDepth = 1.5;
597
+ let sourceDiversity = 1.5;
598
+ let decomposition = 1 + Math.min(2, (contract.acceptanceCriteria?.requiredAttributes?.length || 0) * 0.5);
599
+ let verificationStakes = hardEscalated ? 3.5 : 1.5;
600
+ let decisionEvaluated = false;
601
+ let facetProbabilities = inferFallbackFacetProbabilities(contract);
602
+ if (decision) {
603
+ try {
604
+ const contextLines = [
605
+ `Research Objective: ${contract.objective}`,
606
+ contract.context?.hardwarePlatform ? `Hardware Platform: ${contract.context.hardwarePlatform}` : "",
607
+ contract.context?.softwareEnv ? `Software Environment: ${contract.context.softwareEnv}` : "",
608
+ contract.context?.ageBand ? `Target Learner Age Band: ${contract.context.ageBand[0]}-${contract.context.ageBand[1]}` : "",
609
+ contract.acceptanceCriteria?.requiredAttributes?.length ? `Required Attributes: ${contract.acceptanceCriteria.requiredAttributes.join(", ")}` : "",
610
+ contract.requiredSections?.length ? `Required Report Sections: ${contract.requiredSections.join(", ")}` : ""
611
+ ].filter(Boolean).join("\n");
612
+ const result = await decision({
613
+ context: contextLines,
614
+ questions: [
615
+ {
616
+ id: "reading_depth",
617
+ type: "score",
618
+ criteria: "Evaluate how much document reading depth is required to answer the research objective (0 = single snippet or quick fact lookup, 2 = full document or API tutorial reading, 4 = multi-document cross-comparison and deep synthesis)."
619
+ },
620
+ {
621
+ id: "source_diversity",
622
+ type: "score",
623
+ criteria: "Evaluate how many distinct knowledge modalities (official web docs, peer-reviewed academic papers, developer community pulse, interactive STEM OER simulations) are required (0 = 1 source type suffices, 2 = 2 complementary channels needed, 4 = 3 or more heterogeneous channels required)."
624
+ },
625
+ {
626
+ id: "decomposition",
627
+ type: "score",
628
+ criteria: "Evaluate how many distinct sub-questions, technical constraints, or comparative dimensions must be decomposed and resolved (0 = single atomic question, 2 = 2 to 3 related facets, 4 = 4 or more complex interdependent facets)."
629
+ },
630
+ {
631
+ id: "verification_stakes",
632
+ type: "score",
633
+ criteria: "Evaluate the factual verification stakes and risk of conflicting claims or hallucination (0 = low-stakes lookup, 2 = standard technical or pedagogical grounding, 4 = high-stakes factual or academic audit requiring strict claim verification)."
634
+ },
635
+ {
636
+ id: "question_facet",
637
+ type: "choice",
638
+ criteria: "Classify the primary information need of this research objective into the most fitting facet.",
639
+ options: [...QUESTION_FACETS]
640
+ }
641
+ ]
642
+ });
643
+ const aDepth = result.answers["reading_depth"];
644
+ const aDiv = result.answers["source_diversity"];
645
+ const aDecomp = result.answers["decomposition"];
646
+ const aStakes = result.answers["verification_stakes"];
647
+ const aFacet = result.answers["question_facet"];
648
+ if (aDepth?.type === "score") readingDepth = clampScore0to4(aDepth.score, readingDepth);
649
+ if (aDiv?.type === "score") sourceDiversity = clampScore0to4(aDiv.score, sourceDiversity);
650
+ if (aDecomp?.type === "score") decomposition = clampScore0to4(aDecomp.score, decomposition);
651
+ if (aStakes?.type === "score") verificationStakes = clampScore0to4(aStakes.score, verificationStakes);
652
+ if (aFacet?.type === "choice") {
653
+ const rawProbs = aFacet.probabilities;
654
+ if (rawProbs && Object.keys(rawProbs).length > 0) {
655
+ let sum = 0;
656
+ const nextProbs = {};
657
+ for (const f of QUESTION_FACETS) {
658
+ const v = Math.max(0, Number(rawProbs[f] ?? 0));
659
+ nextProbs[f] = v;
660
+ sum += v;
661
+ }
662
+ if (sum > 0) {
663
+ for (const f of QUESTION_FACETS) {
664
+ nextProbs[f] = Number((nextProbs[f] / sum).toFixed(4));
665
+ }
666
+ facetProbabilities = nextProbs;
667
+ }
668
+ } else if (QUESTION_FACETS.includes(aFacet.choice)) {
669
+ const chosen = aFacet.choice;
670
+ const nextProbs = {};
671
+ for (const f of QUESTION_FACETS) {
672
+ nextProbs[f] = f === chosen ? 0.7 : 0.05;
673
+ }
674
+ facetProbabilities = nextProbs;
675
+ }
676
+ }
677
+ decisionEvaluated = true;
678
+ } catch (e) {
679
+ console.warn("[DecisionRouter] Decision model evaluation failed, using deterministic fallback:", e?.message || e);
680
+ }
681
+ }
682
+ const totalScore = Math.max(
683
+ 0,
684
+ Math.min(20, Math.round(readingDepth + sourceDiversity + decomposition + verificationStakes + contractScore))
685
+ );
686
+ let resolvedMode;
687
+ if (requestedMode !== "auto") {
688
+ resolvedMode = requestedMode;
689
+ } else if (hardEscalated || totalScore >= 13) {
690
+ resolvedMode = "deep-research";
691
+ } else if (totalScore <= 4) {
692
+ resolvedMode = "search";
693
+ } else {
694
+ resolvedMode = "research";
695
+ }
696
+ const channelPriors = rankChannelsByExpectedPrior(facetProbabilities, contract);
697
+ return {
698
+ requestedMode,
699
+ resolvedMode,
700
+ decisionEvaluated,
701
+ hardEscalated,
702
+ rubricBreakdown: {
703
+ readingDepth: Number(readingDepth.toFixed(2)),
704
+ sourceDiversity: Number(sourceDiversity.toFixed(2)),
705
+ decomposition: Number(decomposition.toFixed(2)),
706
+ verificationStakes: Number(verificationStakes.toFixed(2)),
707
+ contractScore,
708
+ totalScore
709
+ },
710
+ facetProbabilities,
711
+ channelPriors
712
+ };
713
+ }
714
+ async function evaluateAttributeCoverageWithDecision(params) {
715
+ const { objective, targetCheckList, receiptsText, decision } = params;
716
+ if (targetCheckList.length === 0) {
717
+ return { satisfied: [], missing: [] };
718
+ }
719
+ try {
720
+ const questions = targetCheckList.map((attr, idx) => ({
721
+ id: `attr_${idx}`,
722
+ type: "noul",
723
+ criteria: `Does the collected evidence contain concrete, substantive information addressing "${attr}" for the research objective "${objective}"?`
724
+ }));
725
+ const res = await decision({
726
+ context: `Research Objective: "${objective}"
727
+
728
+ Collected Citation Receipts:
729
+ ${receiptsText}`,
730
+ questions
731
+ });
732
+ const satisfied = [];
733
+ const missing = [];
734
+ targetCheckList.forEach((attr, idx) => {
735
+ const ans = res.answers[`attr_${idx}`];
736
+ if (ans && ans.type === "noul" && ans.probability >= 0.55) {
737
+ satisfied.push(attr);
738
+ } else {
739
+ missing.push(attr);
740
+ }
741
+ });
742
+ return { satisfied, missing };
743
+ } catch (e) {
744
+ console.warn("[DecisionRouter] Attribute coverage noul check failed:", e?.message || e);
745
+ return null;
746
+ }
747
+ }
748
+
749
+ // src/agent/channelScheduler.ts
750
+ function classifyChannelStatus(itemsAdded, substantiveBytes, error) {
751
+ if (error) return "error";
752
+ if (itemsAdded <= 0) return "empty";
753
+ if (itemsAdded >= 2 || substantiveBytes >= 450) return "ok";
754
+ return "weak";
755
+ }
756
+ async function runConcurrentRefillScheduler(params) {
757
+ const { channelQueue, maxChannels, signal, executeChannel } = params;
758
+ const effectiveMax = Math.max(1, maxChannels);
759
+ const concurrency = Math.max(1, Math.min(params.concurrency ?? 2, effectiveMax));
760
+ const queue = [...channelQueue];
761
+ const traces = [];
762
+ const inFlightControllers = /* @__PURE__ */ new Set();
763
+ let okChannels = 0;
764
+ let stopped = false;
765
+ const abortAllInFlight = () => {
766
+ stopped = true;
767
+ for (const ctrl of inFlightControllers) {
768
+ try {
769
+ ctrl.abort();
770
+ } catch {
771
+ }
772
+ }
773
+ inFlightControllers.clear();
774
+ };
775
+ if (signal) {
776
+ if (signal.aborted) {
777
+ return { traces: [], okChannels: 0 };
778
+ }
779
+ signal.addEventListener("abort", abortAllInFlight, { once: true });
780
+ }
781
+ return new Promise((resolve) => {
782
+ let settled = false;
783
+ const finishIfDone = () => {
784
+ if (settled) return;
785
+ if (stopped || okChannels >= effectiveMax || queue.length === 0 && inFlightControllers.size === 0) {
786
+ settled = true;
787
+ if (signal) {
788
+ signal.removeEventListener("abort", onExternalAbort);
789
+ }
790
+ abortAllInFlight();
791
+ resolve({ traces, okChannels });
792
+ }
793
+ };
794
+ const onExternalAbort = () => {
795
+ abortAllInFlight();
796
+ finishIfDone();
797
+ };
798
+ const scheduleNext = () => {
799
+ if (settled || stopped || signal?.aborted) {
800
+ finishIfDone();
801
+ return;
802
+ }
803
+ const remainingNeeded = effectiveMax - okChannels;
804
+ const targetInFlight = Math.min(concurrency, remainingNeeded);
805
+ while (!stopped && inFlightControllers.size < targetInFlight && queue.length > 0) {
806
+ const next = queue.shift();
807
+ if (!next) break;
808
+ const channelController = new AbortController();
809
+ inFlightControllers.add(channelController);
810
+ const startMs = Date.now();
811
+ executeChannel(next.channel, next.score, channelController.signal).then((trace) => {
812
+ inFlightControllers.delete(channelController);
813
+ if (settled || stopped) {
814
+ finishIfDone();
815
+ return;
816
+ }
817
+ traces.push(trace);
818
+ if (trace.status === "ok") {
819
+ okChannels += 1;
820
+ if (okChannels >= effectiveMax) {
821
+ abortAllInFlight();
822
+ finishIfDone();
823
+ return;
824
+ }
825
+ }
826
+ scheduleNext();
827
+ }).catch((err) => {
828
+ inFlightControllers.delete(channelController);
829
+ if (settled || stopped) {
830
+ finishIfDone();
831
+ return;
832
+ }
833
+ traces.push({
834
+ channel: next.channel,
835
+ status: "error",
836
+ priorScore: next.score,
837
+ itemsAdded: 0,
838
+ durationMs: Date.now() - startMs,
839
+ errorMessage: err?.message || String(err)
840
+ });
841
+ scheduleNext();
842
+ });
843
+ }
844
+ finishIfDone();
845
+ };
846
+ scheduleNext();
847
+ });
848
+ }
849
+
381
850
  // src/academic/arxivClient.ts
382
851
  var ArXivSearchEngine = class {
383
852
  /**
@@ -525,7 +994,7 @@ var AcademicSearchEngine = class {
525
994
  }
526
995
  const res = await fetch(`https://api.semanticscholar.org/graph/v1/paper/search?${params.toString()}`, {
527
996
  headers,
528
- signal: AbortSignal.timeout(6e3)
997
+ signal: AbortSignal.timeout(12e3)
529
998
  });
530
999
  if (res.ok) {
531
1000
  const data = await res.json();
@@ -556,7 +1025,7 @@ var AcademicSearchEngine = class {
556
1025
  try {
557
1026
  const res = await fetch(`https://api.openalex.org/works?search=${encodeURIComponent(query)}&per-page=${limit}`, {
558
1027
  headers: { "User-Agent": "OrchableComposer/1.0 (mailto:team@orchable.app)" },
559
- signal: AbortSignal.timeout(6e3)
1028
+ signal: AbortSignal.timeout(12e3)
560
1029
  });
561
1030
  if (res.ok) {
562
1031
  const data = await res.json();
@@ -643,7 +1112,7 @@ var OpenAlexClient = class {
643
1112
  headers: {
644
1113
  "User-Agent": `OrchableResearchKit/1.3 (mailto:${this.mailto})`
645
1114
  },
646
- signal: AbortSignal.timeout(7e3)
1115
+ signal: AbortSignal.timeout(12e3)
647
1116
  });
648
1117
  if (res.ok) {
649
1118
  const data = await res.json();
@@ -683,7 +1152,7 @@ var OpenAlexClient = class {
683
1152
  headers: {
684
1153
  "User-Agent": `OrchableResearchKit/1.3 (mailto:${this.mailto})`
685
1154
  },
686
- signal: AbortSignal.timeout(7e3)
1155
+ signal: AbortSignal.timeout(12e3)
687
1156
  });
688
1157
  if (res.ok) {
689
1158
  const data = await res.json();
@@ -1222,7 +1691,7 @@ var WebScraper = class {
1222
1691
  }
1223
1692
  const res = await fetch(jinaUrl, {
1224
1693
  headers,
1225
- signal: AbortSignal.timeout(8e3)
1694
+ signal: AbortSignal.timeout(15e3)
1226
1695
  });
1227
1696
  if (res.ok) {
1228
1697
  const markdown = await res.text();
@@ -1264,7 +1733,7 @@ var WebScraper = class {
1264
1733
  try {
1265
1734
  const res = await fetch(targetUrl, {
1266
1735
  headers: { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)" },
1267
- signal: AbortSignal.timeout(1e4)
1736
+ signal: AbortSignal.timeout(15e3)
1268
1737
  });
1269
1738
  if (res.ok) {
1270
1739
  const rawHtml = await res.text();
@@ -1342,6 +1811,13 @@ ${p.replace(/<[^>]+>/g, " ").trim()}
1342
1811
  function tokenizeBilingualKeywords(text) {
1343
1812
  return text.normalize("NFC").toLowerCase().replace(/[.,;:!?()[\]{}"“”‘’/\\|`*_~#-]+/g, " ").split(/\s+/).filter((w) => w.length >= 2 && !/^(and|the|for|with|from|into|của|trong|được|những|các|cho|với|khi|và|hoặc|để|từ|đến|về)$/.test(w));
1344
1813
  }
1814
+ function keywordMatchesText(keyword, lowerText) {
1815
+ if (keyword.length <= 3) {
1816
+ const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1817
+ return new RegExp(`(?:^|[^a-z0-9\\u00C0-\\u1EF9])${escaped}(?:$|[^a-z0-9\\u00C0-\\u1EF9])`, "i").test(lowerText);
1818
+ }
1819
+ return lowerText.includes(keyword);
1820
+ }
1345
1821
  function extractTopSentences(markdown, targetTopic, maxSentences = 3) {
1346
1822
  const keywords = tokenizeBilingualKeywords(targetTopic);
1347
1823
  const withoutCode = markdown.replace(/```[\s\S]*?```/g, " ");
@@ -1354,7 +1830,7 @@ function extractTopSentences(markdown, targetTopic, maxSentences = 3) {
1354
1830
  if (rawSentences.length === 0) return [];
1355
1831
  const scored = rawSentences.map((sentence, idx) => {
1356
1832
  const lower = sentence.normalize("NFC").toLowerCase();
1357
- const matchedCount = keywords.filter((k) => lower.includes(k)).length;
1833
+ const matchedCount = keywords.filter((k) => keywordMatchesText(k, lower)).length;
1358
1834
  const positionBonus = idx < 8 ? 1.5 : idx < 20 ? 0.5 : 0;
1359
1835
  const technicalBonus = /(`[^`]+`|\b(?:api|function|class|actor|async|sensor|pin|loop|state|biến|hàm|cảm biến|vòng lặp|mạch)\b)/i.test(
1360
1836
  sentence
@@ -1375,7 +1851,7 @@ var EvidenceScorer = class {
1375
1851
  let noiseScore = 2;
1376
1852
  const lowerContent = doc.markdownContent.normalize("NFC").toLowerCase();
1377
1853
  const targetKeywords = tokenizeBilingualKeywords(targetTopic);
1378
- const keywordMatches = targetKeywords.filter((k) => lowerContent.includes(k)).length;
1854
+ const keywordMatches = targetKeywords.filter((k) => keywordMatchesText(k, lowerContent)).length;
1379
1855
  const matchRatio = targetKeywords.length > 0 ? keywordMatches / targetKeywords.length : 1;
1380
1856
  if (matchRatio >= 0.75) depthScore += 3;
1381
1857
  else if (matchRatio >= 0.4) depthScore += 2;
@@ -2044,7 +2520,7 @@ var SocialPulseHarvester = class {
2044
2520
  });
2045
2521
  const res = await fetch(`https://hn.algolia.com/api/v1/search?${params.toString()}`, {
2046
2522
  headers: { "User-Agent": "OrchableResearchKit/1.3" },
2047
- signal: AbortSignal.timeout(6500)
2523
+ signal: AbortSignal.timeout(12e3)
2048
2524
  });
2049
2525
  if (res.ok) {
2050
2526
  const data = await res.json();
@@ -2091,7 +2567,7 @@ var SocialPulseHarvester = class {
2091
2567
  Accept: "application/vnd.github+json",
2092
2568
  "User-Agent": "OrchableResearchKit/1.3"
2093
2569
  },
2094
- signal: AbortSignal.timeout(6500)
2570
+ signal: AbortSignal.timeout(12e3)
2095
2571
  });
2096
2572
  if (res.ok) {
2097
2573
  const data = await res.json();
@@ -2734,6 +3210,16 @@ function resolveResearchProfile(contract) {
2734
3210
  }
2735
3211
  return "general";
2736
3212
  }
3213
+ function isSemanticRankedHit(hit) {
3214
+ return hit.engine === "exa" || hit.engine === "tavily" || hit.engine === "academic" || typeof hit.score === "number" && hit.score > 0;
3215
+ }
3216
+ function computeNativeHitScore(hit, defaultSemantic = 8, defaultLexical = 6) {
3217
+ if (typeof hit.score === "number" && hit.score > 0) {
3218
+ const scaled = hit.score <= 1 ? hit.score * 10 : hit.score;
3219
+ return Math.max(6, Math.min(10, Math.round(scaled)));
3220
+ }
3221
+ return isSemanticRankedHit(hit) ? defaultSemantic : defaultLexical;
3222
+ }
2737
3223
  var ResearchSubAgent = class {
2738
3224
  constructor(config = {}) {
2739
3225
  this.config = config;
@@ -2757,6 +3243,7 @@ var ResearchSubAgent = class {
2757
3243
  this.openAlexClient = new OpenAlexClient();
2758
3244
  this.socialPulseHarvester = new SocialPulseHarvester(this.searchEngine);
2759
3245
  this.stemResearcher = new StemResourceResearcher();
3246
+ this.youtubeService = new YouTubeIngestionService();
2760
3247
  this.healthAuditor = new HealthAuditor();
2761
3248
  this.evidenceScorer = new EvidenceScorer();
2762
3249
  this.claimVerifier = new ClaimVerifier();
@@ -2768,6 +3255,7 @@ var ResearchSubAgent = class {
2768
3255
  openAlexClient;
2769
3256
  socialPulseHarvester;
2770
3257
  stemResearcher;
3258
+ youtubeService;
2771
3259
  healthAuditor;
2772
3260
  evidenceScorer;
2773
3261
  claimVerifier;
@@ -2777,70 +3265,122 @@ var ResearchSubAgent = class {
2777
3265
  */
2778
3266
  async run(contract, options) {
2779
3267
  const llm = options?.llm ?? this.config.llm;
3268
+ const decision = options?.decision ?? this.config.decision;
3269
+ const modeTrace = await classifyModeAndPrior(contract, decision);
3270
+ const resolvedMode = modeTrace.resolvedMode;
3271
+ const modePreset = RESEARCH_MODE_PRESETS[resolvedMode];
2780
3272
  const resolvedProfile = resolveResearchProfile(contract);
2781
- const preset = RESEARCH_PROFILE_PRESETS[resolvedProfile];
3273
+ const profilePreset = RESEARCH_PROFILE_PRESETS[resolvedProfile];
2782
3274
  const ctx = contract.context ?? this.config.defaultCourseContext;
2783
3275
  const domain = classifyTechnicalDomain(contract.objective, void 0, ctx).domain;
2784
- const maxRounds = Math.max(1, Math.min(5, contract.budget?.maxRounds ?? preset.maxRounds));
2785
- const maxQueriesPerRound = Math.max(1, Math.min(6, contract.budget?.maxQueriesPerRound ?? preset.maxQueriesPerRound));
2786
- const maxScrapePerRound = Math.max(1, Math.min(6, contract.budget?.maxScrapePerRound ?? preset.maxScrapePerRound));
2787
- const minSources = contract.acceptanceCriteria?.minSources ?? 2;
3276
+ const timeoutMs = Math.max(1e3, contract.budget?.timeoutMs ?? modePreset.timeoutMs);
3277
+ const maxChannels = Math.max(1, Math.min(5, contract.budget?.maxChannels ?? modePreset.maxChannels));
3278
+ const channelConcurrency = Math.max(
3279
+ 1,
3280
+ Math.min(3, contract.budget?.channelConcurrency ?? modePreset.channelConcurrency)
3281
+ );
3282
+ const maxRounds = resolvedMode === "search" ? 1 : Math.max(1, Math.min(5, contract.budget?.maxRounds ?? modePreset.maxRounds));
3283
+ const maxQueriesPerRound = Math.max(
3284
+ 1,
3285
+ Math.min(6, contract.budget?.maxQueriesPerRound ?? modePreset.maxQueriesPerRound)
3286
+ );
3287
+ const maxScrapePerRound = resolvedMode === "search" ? contract.budget?.maxScrapePerRound ?? 0 : Math.max(0, Math.min(6, contract.budget?.maxScrapePerRound ?? modePreset.maxScrapePerRound));
3288
+ const minSources = contract.acceptanceCriteria?.minSources ?? (resolvedMode === "search" ? 1 : 2);
2788
3289
  const minRelevanceScore = contract.acceptanceCriteria?.minRelevanceScore ?? 6;
2789
3290
  const recencyDays = contract.acceptanceCriteria?.recencyDays ?? 30;
3291
+ const shouldVerifyClaims = contract.acceptanceCriteria?.verifyClaims ?? modePreset.verifyClaims;
3292
+ const harvestBudgetMs = resolvedMode === "search" ? timeoutMs : Math.floor(timeoutMs * 0.75);
3293
+ const harvestAbortController = new AbortController();
3294
+ const harvestTimer = setTimeout(() => {
3295
+ harvestAbortController.abort();
3296
+ }, harvestBudgetMs);
3297
+ if (contract.signal) {
3298
+ if (contract.signal.aborted) {
3299
+ harvestAbortController.abort();
3300
+ } else {
3301
+ contract.signal.addEventListener("abort", () => harvestAbortController.abort(), { once: true });
3302
+ }
3303
+ }
2790
3304
  const ledger = new EvidenceLedger();
2791
3305
  const executedQueries = /* @__PURE__ */ new Set();
2792
3306
  const scrapedUrls = /* @__PURE__ */ new Set();
2793
3307
  const roundTraces = [];
3308
+ const allChannelTraces = [];
2794
3309
  let currentMissingGaps = [
2795
3310
  ...contract.acceptanceCriteria?.requiredAttributes || [],
2796
3311
  ...contract.requiredSections || []
2797
3312
  ];
2798
- for (let round = 1; round <= maxRounds; round++) {
2799
- const beforeReceiptCount = ledger.getReceipts().length;
2800
- const plannedQueries = await this.planQueriesForRound({
2801
- round,
2802
- contract,
2803
- profile: resolvedProfile,
2804
- missingGaps: currentMissingGaps,
2805
- receipts: ledger.getReceipts(),
2806
- executedQueries,
2807
- maxQueries: maxQueriesPerRound,
2808
- llm
2809
- });
2810
- for (const q of plannedQueries) {
2811
- executedQueries.add(q.toLowerCase());
2812
- }
2813
- await this.executeHarvestRound({
2814
- round,
2815
- queries: plannedQueries,
2816
- contract,
2817
- preset,
2818
- domain,
2819
- recencyDays,
2820
- maxScrapePerRound,
2821
- scrapedUrls,
2822
- ledger
2823
- });
2824
- const afterReceiptCount = ledger.getReceipts().length;
2825
- const newReceiptsAdded = afterReceiptCount - beforeReceiptCount;
2826
- const evaluation = await this.evaluateRoundGaps({
2827
- contract,
2828
- ledger,
2829
- minSources,
2830
- minRelevanceScore,
2831
- llm
2832
- });
2833
- currentMissingGaps = evaluation.missingGaps;
2834
- roundTraces.push({
2835
- round,
2836
- plannedQueries,
2837
- newReceiptsAdded,
2838
- satisfiedAttributes: evaluation.satisfiedAttributes,
2839
- missingGaps: evaluation.missingGaps
2840
- });
2841
- if (evaluation.missingGaps.length === 0) {
2842
- break;
3313
+ try {
3314
+ for (let round = 1; round <= maxRounds; round++) {
3315
+ if (harvestAbortController.signal.aborted) {
3316
+ break;
3317
+ }
3318
+ const beforeReceiptCount = ledger.getReceipts().length;
3319
+ const plannedQueries = await this.planQueriesForRound({
3320
+ round,
3321
+ contract,
3322
+ mode: resolvedMode,
3323
+ profile: resolvedProfile,
3324
+ missingGaps: currentMissingGaps,
3325
+ receipts: ledger.getReceipts(),
3326
+ executedQueries,
3327
+ maxQueries: maxQueriesPerRound,
3328
+ llm: resolvedMode === "search" ? void 0 : llm
3329
+ });
3330
+ for (const q of plannedQueries) {
3331
+ executedQueries.add(q.toLowerCase());
3332
+ }
3333
+ const roundChannelQueue = this.buildRoundChannelQueue(
3334
+ round,
3335
+ modeTrace.channelPriors,
3336
+ profilePreset,
3337
+ contract
3338
+ );
3339
+ const schedulerResult = await runConcurrentRefillScheduler({
3340
+ channelQueue: roundChannelQueue,
3341
+ maxChannels,
3342
+ concurrency: channelConcurrency,
3343
+ signal: harvestAbortController.signal,
3344
+ executeChannel: (channel, priorScore, channelSignal) => this.executeSingleChannel({
3345
+ channel,
3346
+ priorScore,
3347
+ queries: plannedQueries,
3348
+ contract,
3349
+ domain,
3350
+ recencyDays,
3351
+ maxScrapePerRound,
3352
+ scrapedUrls,
3353
+ ledger,
3354
+ signal: channelSignal
3355
+ })
3356
+ });
3357
+ allChannelTraces.push(...schedulerResult.traces);
3358
+ const afterReceiptCount = ledger.getReceipts().length;
3359
+ const newReceiptsAdded = afterReceiptCount - beforeReceiptCount;
3360
+ const evaluation = await this.evaluateRoundGaps({
3361
+ contract,
3362
+ mode: resolvedMode,
3363
+ ledger,
3364
+ minSources,
3365
+ minRelevanceScore,
3366
+ decision: resolvedMode === "search" ? void 0 : decision,
3367
+ llm: resolvedMode === "search" ? void 0 : llm
3368
+ });
3369
+ currentMissingGaps = evaluation.missingGaps;
3370
+ roundTraces.push({
3371
+ round,
3372
+ plannedQueries,
3373
+ newReceiptsAdded,
3374
+ satisfiedAttributes: evaluation.satisfiedAttributes,
3375
+ missingGaps: evaluation.missingGaps,
3376
+ channelTraces: schedulerResult.traces
3377
+ });
3378
+ if (evaluation.missingGaps.length === 0) {
3379
+ break;
3380
+ }
2843
3381
  }
3382
+ } finally {
3383
+ clearTimeout(harvestTimer);
2844
3384
  }
2845
3385
  const allItems = ledger.getItems();
2846
3386
  const approvedItems = ledger.getApprovedItems(minRelevanceScore);
@@ -2853,6 +3393,7 @@ var ResearchSubAgent = class {
2853
3393
  return {
2854
3394
  status: "failed",
2855
3395
  objective: contract.objective,
3396
+ mode: resolvedMode,
2856
3397
  profile: resolvedProfile,
2857
3398
  roundsExecuted: roundTraces.length,
2858
3399
  data: null,
@@ -2870,36 +3411,306 @@ ${currentMissingGaps.length > 0 ? currentMissingGaps.map((g) => `- ${g}`).join("
2870
3411
  invalidCitationIds: [],
2871
3412
  missingGaps: currentMissingGaps.length > 0 ? currentMissingGaps : ["minSources not met (0 harvested)"],
2872
3413
  roundTraces,
3414
+ modeClassificationTrace: modeTrace,
3415
+ channelTraces: allChannelTraces,
3416
+ provenanceMd: provenanceSidecar.provenanceMd
3417
+ };
3418
+ }
3419
+ if (resolvedMode === "search") {
3420
+ const receipts = ledger.getReceipts();
3421
+ const markdownReport = this.buildDeterministicMarkdownReport(
3422
+ contract.objective,
3423
+ resolvedProfile,
3424
+ allItems,
3425
+ contract.requiredSections
3426
+ );
3427
+ const tier1Summary = allItems.slice(0, 3).map((i) => `[${i.id}] ${i.title}: ${i.keyExcerpts[0] || ""}`).join(" ");
3428
+ const tier2TechnicalDigest = allItems.slice(0, 6).map((i) => `- **[${i.id}] ${i.title}** (${i.url}): ${i.keyExcerpts.slice(0, 2).join(" ")}`).join("\n");
3429
+ return {
3430
+ status: approvedItems.length >= minSources ? "success" : "partial",
3431
+ objective: contract.objective,
3432
+ mode: resolvedMode,
3433
+ profile: resolvedProfile,
3434
+ roundsExecuted: roundTraces.length,
3435
+ data: {
3436
+ objective: contract.objective,
3437
+ mode: resolvedMode,
3438
+ sources: receipts
3439
+ },
3440
+ markdownReport,
3441
+ tier1Summary,
3442
+ tier2TechnicalDigest,
3443
+ ledgerItems: allItems,
3444
+ receipts,
3445
+ validCitationIds: allItems.map((i) => i.id),
3446
+ invalidCitationIds: [],
3447
+ missingGaps: currentMissingGaps,
3448
+ roundTraces,
3449
+ modeClassificationTrace: modeTrace,
3450
+ channelTraces: allChannelTraces,
2873
3451
  provenanceMd: provenanceSidecar.provenanceMd
2874
3452
  };
2875
3453
  }
2876
3454
  return this.synthesizeAndVerify({
2877
3455
  contract,
3456
+ mode: resolvedMode,
2878
3457
  profile: resolvedProfile,
2879
3458
  domain,
2880
3459
  ledger,
2881
3460
  approvedCount: approvedItems.length,
2882
3461
  minSources,
3462
+ shouldVerifyClaims,
2883
3463
  missingGaps: currentMissingGaps,
2884
3464
  roundTraces,
3465
+ modeClassificationTrace: modeTrace,
3466
+ channelTraces: allChannelTraces,
2885
3467
  provenanceMd: provenanceSidecar.provenanceMd,
2886
- llm
3468
+ llm,
3469
+ decision
2887
3470
  });
2888
3471
  }
3472
+ /**
3473
+ * Builds the Prior-sorted channel queue for a specific round.
3474
+ */
3475
+ buildRoundChannelQueue(round, channelPriors, profilePreset, contract) {
3476
+ if (contract.preferredChannels && contract.preferredChannels.length > 0) {
3477
+ const preferredSet = new Set(contract.preferredChannels);
3478
+ const preferred = channelPriors.filter((c) => preferredSet.has(c.channel));
3479
+ const others = channelPriors.filter((c) => !preferredSet.has(c.channel));
3480
+ if (this.config.allowEnvFallback === false) {
3481
+ return preferred;
3482
+ }
3483
+ return [...preferred, ...others];
3484
+ }
3485
+ if (contract.profile && contract.profile !== "auto") {
3486
+ const filtered = channelPriors.filter((c) => {
3487
+ if (c.channel === "web_docs") return profilePreset.enableWeb;
3488
+ if (c.channel === "academic") return profilePreset.enableAcademic;
3489
+ if (c.channel === "social_pulse") return profilePreset.enableSocialPulse;
3490
+ if (c.channel === "stem_oer") return profilePreset.enableStemOer;
3491
+ return false;
3492
+ });
3493
+ if (filtered.length > 0) {
3494
+ return filtered;
3495
+ }
3496
+ }
3497
+ if (this.config.allowEnvFallback === false) {
3498
+ const isolated = channelPriors.filter((c) => {
3499
+ if (c.channel === "web_docs") return Boolean(this.config.customSearchAdapter || this.config.apiKeys);
3500
+ if (c.channel === "academic") return Boolean(this.config.customAcademicSearchAdapter || this.config.apiKeys?.semanticScholar);
3501
+ return false;
3502
+ });
3503
+ if (isolated.length > 0) {
3504
+ return isolated;
3505
+ }
3506
+ }
3507
+ if (round > 1) {
3508
+ return [...channelPriors].sort((a, b) => {
3509
+ const boostA = a.channel === "web_docs" ? 0.3 : a.channel === "academic" ? 0.2 : 0;
3510
+ const boostB = b.channel === "web_docs" ? 0.3 : b.channel === "academic" ? 0.2 : 0;
3511
+ return b.score + boostB - (a.score + boostA);
3512
+ });
3513
+ }
3514
+ return [...channelPriors];
3515
+ }
3516
+ /**
3517
+ * Executes a single source channel and classifies its outcome (`'ok' | 'weak' | 'empty' | 'error'`)
3518
+ * using Non-Redundant Evidence Gating (ADR-0019).
3519
+ */
3520
+ async executeSingleChannel(params) {
3521
+ const {
3522
+ channel,
3523
+ priorScore,
3524
+ queries,
3525
+ contract,
3526
+ domain,
3527
+ recencyDays,
3528
+ maxScrapePerRound,
3529
+ scrapedUrls,
3530
+ ledger,
3531
+ signal
3532
+ } = params;
3533
+ const startMs = Date.now();
3534
+ const beforeItems = ledger.getItems().length;
3535
+ let substantiveBytes = 0;
3536
+ try {
3537
+ if (signal.aborted) {
3538
+ return {
3539
+ channel,
3540
+ status: "empty",
3541
+ priorScore,
3542
+ itemsAdded: 0,
3543
+ durationMs: 0
3544
+ };
3545
+ }
3546
+ if (channel === "web_docs") {
3547
+ const candidateHits = [];
3548
+ for (const q of queries) {
3549
+ if (signal.aborted) break;
3550
+ try {
3551
+ const hits = await this.searchEngine.search(q, { limit: 3 });
3552
+ for (const h of hits) {
3553
+ if (!isCommercialOrNoise({ url: h.url, title: h.title, snippet: h.content })) {
3554
+ if (!candidateHits.some((existing) => existing.url === h.url)) {
3555
+ candidateHits.push(h);
3556
+ }
3557
+ }
3558
+ }
3559
+ } catch {
3560
+ }
3561
+ }
3562
+ const urlsToScrape = maxScrapePerRound > 0 ? candidateHits.filter((h) => !scrapedUrls.has(h.url)).slice(0, maxScrapePerRound) : [];
3563
+ if (urlsToScrape.length > 0 && !signal.aborted) {
3564
+ await Promise.allSettled(
3565
+ urlsToScrape.map(async (hit) => {
3566
+ if (signal.aborted) return;
3567
+ scrapedUrls.add(hit.url);
3568
+ try {
3569
+ const doc = await this.webScraper.scrapeUrl(hit.url);
3570
+ const health = this.healthAuditor.auditDocument(doc);
3571
+ if (health.passed && doc.markdownContent.trim().length > 80) {
3572
+ if (isSemanticRankedHit(hit)) {
3573
+ const nativeScore = computeNativeHitScore(hit, 8, 7);
3574
+ const takeaways = extractTopSentences(doc.markdownContent, contract.objective, 3);
3575
+ const receipt = ledger.addScrapedDocument(doc, nativeScore, takeaways);
3576
+ const added = ledger.getById(receipt.id);
3577
+ substantiveBytes += added?.rawByteSize || doc.byteSize || 1e3;
3578
+ return;
3579
+ } else {
3580
+ const scored = this.evidenceScorer.scoreDocument(doc, domain, contract.objective);
3581
+ const receipt = ledger.addScrapedDocument(doc, scored.score, scored.keyTakeaways);
3582
+ const added = ledger.getById(receipt.id);
3583
+ substantiveBytes += added?.rawByteSize || doc.byteSize || 800;
3584
+ return;
3585
+ }
3586
+ }
3587
+ } catch {
3588
+ }
3589
+ if (hit.content && hit.content.trim().length > 30) {
3590
+ const hitScore = computeNativeHitScore(hit, 7, 6);
3591
+ ledger.addSearchHit(hit, hitScore);
3592
+ substantiveBytes += Buffer.byteLength(hit.content, "utf-8");
3593
+ }
3594
+ })
3595
+ );
3596
+ }
3597
+ const remainingHits = maxScrapePerRound > 0 ? candidateHits.slice(maxScrapePerRound, maxScrapePerRound + 3) : candidateHits.slice(0, 5);
3598
+ for (const hit of remainingHits) {
3599
+ if (hit.content && hit.content.trim().length > 35) {
3600
+ const hitScore = computeNativeHitScore(hit, 7, 6);
3601
+ ledger.addSearchHit(hit, hitScore);
3602
+ substantiveBytes += Math.max(
3603
+ maxScrapePerRound === 0 ? 500 : 100,
3604
+ Buffer.byteLength(hit.content, "utf-8")
3605
+ );
3606
+ }
3607
+ }
3608
+ } else if (channel === "academic") {
3609
+ const primaryQuery = queries[0] || contract.objective;
3610
+ const [s2Papers, oaPapers] = await Promise.all([
3611
+ this.academicEngine.searchPapers(primaryQuery, { limit: 3 }).catch(() => []),
3612
+ this.openAlexClient.searchWorks(primaryQuery, { limit: 3 }).catch(() => [])
3613
+ ]);
3614
+ for (const p of [...s2Papers, ...oaPapers].slice(0, 5)) {
3615
+ const receipt = ledger.addAcademicPaper(p);
3616
+ const item = ledger.getById(receipt.id);
3617
+ substantiveBytes += Math.max(850, item?.rawByteSize || 0);
3618
+ }
3619
+ } else if (channel === "social_pulse") {
3620
+ const pulseReport = await this.socialPulseHarvester.harvest(contract.objective, {
3621
+ recencyDays,
3622
+ limitPerPlatform: 3
3623
+ });
3624
+ for (const item of pulseReport.items.slice(0, 5)) {
3625
+ ledger.addSocialPulseItem(item);
3626
+ substantiveBytes += Math.max(450, Buffer.byteLength(item.snippet || "", "utf-8"));
3627
+ }
3628
+ } else if (channel === "stem_oer") {
3629
+ const oerCatalog = await this.stemResearcher.findResources(contract.objective, {
3630
+ limit: 4
3631
+ });
3632
+ for (const res of oerCatalog.resources.slice(0, 4)) {
3633
+ ledger.addStemResource({
3634
+ title: res.title,
3635
+ url: res.url,
3636
+ description: res.description,
3637
+ provider: res.provider,
3638
+ license: res.license?.type
3639
+ });
3640
+ substantiveBytes += Math.max(500, Buffer.byteLength(res.description || "", "utf-8"));
3641
+ }
3642
+ } else if (channel === "video_media") {
3643
+ const videoQuery = `${queries[0] || contract.objective} site:youtube.com tutorial lecture`;
3644
+ const hits = await this.searchEngine.search(videoQuery, { limit: 3 });
3645
+ for (const h of hits.slice(0, 3)) {
3646
+ if (signal.aborted) break;
3647
+ if (/youtube\.com\/watch|youtu\.be\//i.test(h.url)) {
3648
+ try {
3649
+ const transcript = await this.youtubeService.fetchTranscript(h.url, ["vi", "en"]);
3650
+ if (transcript && transcript.stitchedMarkdown && transcript.stitchedMarkdown.length > 60) {
3651
+ ledger.addScrapedDocument(
3652
+ {
3653
+ url: h.url,
3654
+ title: transcript.title || h.title || "YouTube Educational Video",
3655
+ markdownContent: transcript.stitchedMarkdown,
3656
+ byteSize: Buffer.byteLength(transcript.stitchedMarkdown, "utf-8"),
3657
+ extractedCodeSnippets: [],
3658
+ tablesCount: 0,
3659
+ fetchProvider: "youtube",
3660
+ keyExcerpts: [transcript.stitchedMarkdown.slice(0, 450)]
3661
+ },
3662
+ 8
3663
+ );
3664
+ substantiveBytes += Buffer.byteLength(transcript.stitchedMarkdown, "utf-8");
3665
+ continue;
3666
+ }
3667
+ } catch {
3668
+ }
3669
+ }
3670
+ if (h.content && h.content.trim().length > 30) {
3671
+ ledger.addSearchHit(h, 6);
3672
+ substantiveBytes += Buffer.byteLength(h.content, "utf-8");
3673
+ }
3674
+ }
3675
+ }
3676
+ const itemsAdded = Math.max(0, ledger.getItems().length - beforeItems);
3677
+ const status = classifyChannelStatus(itemsAdded, substantiveBytes);
3678
+ return {
3679
+ channel,
3680
+ status,
3681
+ priorScore,
3682
+ itemsAdded,
3683
+ durationMs: Date.now() - startMs
3684
+ };
3685
+ } catch (err) {
3686
+ const itemsAdded = Math.max(0, ledger.getItems().length - beforeItems);
3687
+ return {
3688
+ channel,
3689
+ status: itemsAdded > 0 ? classifyChannelStatus(itemsAdded, substantiveBytes) : "error",
3690
+ priorScore,
3691
+ itemsAdded,
3692
+ durationMs: Date.now() - startMs,
3693
+ errorMessage: err?.message || String(err)
3694
+ };
3695
+ }
3696
+ }
2889
3697
  /**
2890
3698
  * Plans targeted search queries for Round 1 (initial coverage) or Round > 1 (surgical gap filling).
2891
3699
  */
2892
3700
  async planQueriesForRound(params) {
2893
- const { round, contract, profile, missingGaps, receipts, executedQueries, maxQueries, llm } = params;
3701
+ const { round, contract, mode, profile, missingGaps, receipts, executedQueries, maxQueries, llm } = params;
2894
3702
  const ctx = contract.context ?? this.config.defaultCourseContext;
2895
3703
  const toolAnchor = [ctx?.hardwarePlatform, ctx?.softwareEnv].filter(Boolean).join(" ").trim();
2896
3704
  const baseTopic = toolAnchor ? `${toolAnchor} ${contract.objective}` : contract.objective;
3705
+ if (mode === "search") {
3706
+ return [baseTopic.trim()].slice(0, maxQueries);
3707
+ }
2897
3708
  if (llm) {
2898
3709
  try {
2899
3710
  const promptLines = [
2900
3711
  `You are a Principal Research Planner for an autonomous Plan-and-Execute Research Sub-Agent.`,
2901
3712
  `Objective: "${contract.objective}"`,
2902
- `Profile: ${profile} | Round: ${round}`,
3713
+ `Mode: ${mode} | Profile: ${profile} | Round: ${round}`,
2903
3714
  toolAnchor ? `Hardware/Software Context: ${toolAnchor}` : "",
2904
3715
  ctx?.ageBand ? `Target Learner Age Band: ${ctx.ageBand[0]}-${ctx.ageBand[1]}` : "",
2905
3716
  contract.requiredSections?.length ? `Required Sections: ${contract.requiredSections.join(", ")}` : "",
@@ -2968,122 +3779,13 @@ Generate ${maxQueries} high-precision search queries to fulfill ${round === 1 ?
2968
3779
  }
2969
3780
  return fallbackQueries.filter((q) => !executedQueries.has(q.toLowerCase())).slice(0, maxQueries);
2970
3781
  }
2971
- /**
2972
- * Executes active harvesters in parallel and stores results in the Out-of-Band `EvidenceLedger`.
2973
- */
2974
- async executeHarvestRound(params) {
2975
- const { round, queries, contract, preset, domain, recencyDays, maxScrapePerRound, scrapedUrls, ledger } = params;
2976
- if (queries.length === 0) return;
2977
- const tasks = [];
2978
- if (preset.enableWeb) {
2979
- tasks.push(
2980
- (async () => {
2981
- const candidateHits = [];
2982
- for (const q of queries) {
2983
- try {
2984
- const hits = await this.searchEngine.search(q, { limit: 3 });
2985
- for (const h of hits) {
2986
- if (!isCommercialOrNoise({ url: h.url, title: h.title, snippet: h.content })) {
2987
- if (!candidateHits.some((existing) => existing.url === h.url)) {
2988
- candidateHits.push(h);
2989
- }
2990
- }
2991
- }
2992
- } catch {
2993
- }
2994
- }
2995
- const urlsToScrape = candidateHits.filter((h) => !scrapedUrls.has(h.url)).slice(0, maxScrapePerRound);
2996
- await Promise.allSettled(
2997
- urlsToScrape.map(async (hit) => {
2998
- scrapedUrls.add(hit.url);
2999
- try {
3000
- const doc = await this.webScraper.scrapeUrl(hit.url);
3001
- const health = this.healthAuditor.auditDocument(doc);
3002
- if (health.passed && doc.markdownContent.trim().length > 80) {
3003
- const scored = this.evidenceScorer.scoreDocument(doc, domain, contract.objective);
3004
- ledger.addScrapedDocument(doc, scored.score, scored.keyTakeaways);
3005
- return;
3006
- }
3007
- } catch {
3008
- }
3009
- if (hit.content && hit.content.trim().length > 30) {
3010
- ledger.addSearchHit(hit, 6);
3011
- }
3012
- })
3013
- );
3014
- for (const hit of candidateHits.slice(maxScrapePerRound, maxScrapePerRound + 2)) {
3015
- if (hit.content && hit.content.trim().length > 40) {
3016
- ledger.addSearchHit(hit, 6);
3017
- }
3018
- }
3019
- })()
3020
- );
3021
- }
3022
- if (preset.enableAcademic && round === 1) {
3023
- tasks.push(
3024
- (async () => {
3025
- try {
3026
- const primaryQuery = queries[0] || contract.objective;
3027
- const [s2Papers, oaPapers] = await Promise.all([
3028
- this.academicEngine.searchPapers(primaryQuery, { limit: 3 }),
3029
- this.openAlexClient.searchWorks(primaryQuery, { limit: 3 })
3030
- ]);
3031
- for (const p of [...s2Papers, ...oaPapers].slice(0, 5)) {
3032
- ledger.addAcademicPaper(p);
3033
- }
3034
- } catch (e) {
3035
- console.warn("[ResearchSubAgent] Academic harvest error:", e?.message || e);
3036
- }
3037
- })()
3038
- );
3039
- }
3040
- if (preset.enableSocialPulse && round === 1) {
3041
- tasks.push(
3042
- (async () => {
3043
- try {
3044
- const pulseReport = await this.socialPulseHarvester.harvest(contract.objective, {
3045
- recencyDays,
3046
- limitPerPlatform: 3
3047
- });
3048
- for (const item of pulseReport.items.slice(0, 5)) {
3049
- ledger.addSocialPulseItem(item);
3050
- }
3051
- } catch (e) {
3052
- console.warn("[ResearchSubAgent] Social pulse harvest error:", e?.message || e);
3053
- }
3054
- })()
3055
- );
3056
- }
3057
- if (preset.enableStemOer && round === 1) {
3058
- tasks.push(
3059
- (async () => {
3060
- try {
3061
- const oerCatalog = await this.stemResearcher.findResources(contract.objective, {
3062
- limit: 4
3063
- });
3064
- for (const res of oerCatalog.resources.slice(0, 4)) {
3065
- ledger.addStemResource({
3066
- title: res.title,
3067
- url: res.url,
3068
- description: res.description,
3069
- provider: res.provider,
3070
- license: res.license?.type
3071
- });
3072
- }
3073
- } catch (e) {
3074
- console.warn("[ResearchSubAgent] STEM OER harvest error:", e?.message || e);
3075
- }
3076
- })()
3077
- );
3078
- }
3079
- await Promise.allSettled(tasks);
3080
- }
3081
3782
  /**
3082
3783
  * Evaluates whether the current `EvidenceLedger` satisfies `acceptanceCriteria`,
3083
3784
  * `requiredAttributes`, and `requiredSections`.
3785
+ * Prioritizes Decision Model (`noul`) over Generative LLM when available (ADR-0019).
3084
3786
  */
3085
3787
  async evaluateRoundGaps(params) {
3086
- const { contract, ledger, minSources, minRelevanceScore, llm } = params;
3788
+ const { contract, ledger, minSources, minRelevanceScore, decision, llm } = params;
3087
3789
  const missingGaps = [];
3088
3790
  const satisfiedAttributes = [];
3089
3791
  const approved = ledger.getApprovedItems(minRelevanceScore);
@@ -3092,6 +3794,16 @@ Generate ${maxQueries} high-precision search queries to fulfill ${round === 1 ?
3092
3794
  } else {
3093
3795
  satisfiedAttributes.push(`minSources(${approved.length}/${minSources})`);
3094
3796
  }
3797
+ if (contract.acceptanceCriteria?.minPeerReviewedSources) {
3798
+ const academicCount = ledger.getItems().filter((i) => i.sourceType === "academic").length;
3799
+ if (academicCount < contract.acceptanceCriteria.minPeerReviewedSources) {
3800
+ missingGaps.push(
3801
+ `Need at least ${contract.acceptanceCriteria.minPeerReviewedSources} peer-reviewed academic sources (currently ${academicCount})`
3802
+ );
3803
+ } else {
3804
+ satisfiedAttributes.push(`peerReviewedSources(${academicCount}/${contract.acceptanceCriteria.minPeerReviewedSources})`);
3805
+ }
3806
+ }
3095
3807
  if (contract.acceptanceCriteria?.requireCodeExamples && ledger.getTotalCodeBlocks() === 0) {
3096
3808
  missingGaps.push("Missing verified code examples / syntax snippets");
3097
3809
  } else if (contract.acceptanceCriteria?.requireCodeExamples) {
@@ -3110,53 +3822,141 @@ Generate ${maxQueries} high-precision search queries to fulfill ${round === 1 ?
3110
3822
  const receipts = ledger.getReceipts();
3111
3823
  if (receipts.length === 0) {
3112
3824
  missingGaps.push(...targetCheckList);
3113
- } else if (llm) {
3114
- try {
3115
- const prompt = [
3116
- `Evaluate which of the required attributes/sections are covered by the collected Citation Receipts for "${contract.objective}".`,
3117
- `Required Items: ${JSON.stringify(targetCheckList)}`,
3118
- `Collected Citation Receipts:
3119
- ${receipts.map((r) => `- [${r.id}] ${r.title} (headings: ${r.headings.join(", ")}): ${r.briefExcerpt}`).join("\n")}`,
3120
- `Return ONLY a JSON object: {"satisfied": ["item1"], "missing": ["item2"]}`
3121
- ].join("\n");
3122
- const raw = await llm(prompt, {
3123
- system: 'Output strictly valid JSON object with "satisfied" and "missing" string arrays.',
3124
- temperature: 0.1,
3125
- jsonMode: true
3825
+ } else {
3826
+ const receiptsText = receipts.map((r) => `- [${r.id}] ${r.title} (headings: ${r.headings.join(", ")}): ${r.briefExcerpt}`).join("\n");
3827
+ if (decision) {
3828
+ const decEval = await evaluateAttributeCoverageWithDecision({
3829
+ objective: contract.objective,
3830
+ targetCheckList,
3831
+ receiptsText,
3832
+ decision
3126
3833
  });
3127
- const match = raw.match(/\{[\s\S]*\}/);
3128
- if (match) {
3129
- const parsed = JSON.parse(match[0]);
3130
- if (Array.isArray(parsed.satisfied)) {
3131
- satisfiedAttributes.push(...parsed.satisfied.map(String));
3132
- }
3133
- if (Array.isArray(parsed.missing)) {
3134
- missingGaps.push(...parsed.missing.map(String));
3135
- }
3834
+ if (decEval) {
3835
+ satisfiedAttributes.push(...decEval.satisfied);
3836
+ missingGaps.push(...decEval.missing);
3136
3837
  return { satisfiedAttributes, missingGaps };
3137
3838
  }
3138
- } catch {
3139
3839
  }
3140
- }
3141
- const lowerCorpus = ledger.buildFullRawCorpus().toLowerCase();
3142
- for (const reqItem of targetCheckList) {
3143
- const tokens = reqItem.toLowerCase().replace(/[^a-z0-9\u00C0-\u1EF9]+/g, " ").split(/\s+/).filter((t) => t.length >= 3);
3144
- const matched = tokens.filter((t) => lowerCorpus.includes(t)).length;
3145
- if (tokens.length === 0 || matched / tokens.length >= 0.5) {
3146
- satisfiedAttributes.push(reqItem);
3147
- } else {
3148
- missingGaps.push(reqItem);
3840
+ if (llm) {
3841
+ try {
3842
+ const prompt = [
3843
+ `Evaluate which of the required attributes/sections are covered by the collected Citation Receipts for "${contract.objective}".`,
3844
+ `Required Items: ${JSON.stringify(targetCheckList)}`,
3845
+ `Collected Citation Receipts:
3846
+ ${receiptsText}`,
3847
+ `Return ONLY a JSON object: {"satisfied": ["item1"], "missing": ["item2"]}`
3848
+ ].join("\n");
3849
+ const raw = await llm(prompt, {
3850
+ system: 'Output strictly valid JSON object with "satisfied" and "missing" string arrays.',
3851
+ temperature: 0.1,
3852
+ jsonMode: true
3853
+ });
3854
+ const match = raw.match(/\{[\s\S]*\}/);
3855
+ if (match) {
3856
+ const parsed = JSON.parse(match[0]);
3857
+ if (Array.isArray(parsed.satisfied)) {
3858
+ satisfiedAttributes.push(...parsed.satisfied.map(String));
3859
+ }
3860
+ if (Array.isArray(parsed.missing)) {
3861
+ missingGaps.push(...parsed.missing.map(String));
3862
+ }
3863
+ return { satisfiedAttributes, missingGaps };
3864
+ }
3865
+ } catch {
3866
+ }
3867
+ }
3868
+ const lowerCorpus = ledger.buildFullRawCorpus().toLowerCase();
3869
+ for (const reqItem of targetCheckList) {
3870
+ const tokens = reqItem.toLowerCase().replace(/[^a-z0-9\u00C0-\u1EF9]+/g, " ").split(/\s+/).filter((t) => t.length >= 3);
3871
+ const matched = tokens.filter((t) => lowerCorpus.includes(t)).length;
3872
+ if (tokens.length === 0 || matched / tokens.length >= 0.5) {
3873
+ satisfiedAttributes.push(reqItem);
3874
+ } else {
3875
+ missingGaps.push(reqItem);
3876
+ }
3149
3877
  }
3150
3878
  }
3151
3879
  }
3152
3880
  return { satisfiedAttributes, missingGaps };
3153
3881
  }
3882
+ /**
3883
+ * Verifies claims using Decision Model `choice` (`supported | refuted | not_enough_evidence`)
3884
+ * or Generative LLM NLI (`ClaimVerifier.verifyClaims`) when `shouldVerifyClaims` is enabled (e.g., `deep-research`).
3885
+ */
3886
+ async verifyClaimsWithDecisionOrLlm(claims, sourceCorpus, options) {
3887
+ if (claims.length === 0) {
3888
+ return this.claimVerifier.verifyClaimsDeterministic([], sourceCorpus);
3889
+ }
3890
+ if (options.decision) {
3891
+ try {
3892
+ const detBaseline = this.claimVerifier.verifyClaimsDeterministic(claims, sourceCorpus);
3893
+ const res = await options.decision({
3894
+ context: `Verified Evidence Corpus:
3895
+ ${sourceCorpus.slice(0, 6e3)}`,
3896
+ questions: claims.map((claim, idx) => ({
3897
+ id: `claim_${idx}`,
3898
+ type: "choice",
3899
+ criteria: `Evaluate whether the following claim is strictly supported, directly refuted, or has not_enough_evidence in the Verified Evidence Corpus: "${claim}"`,
3900
+ options: ["supported", "refuted", "not_enough_evidence"]
3901
+ }))
3902
+ });
3903
+ const verifiedClaims = claims.map((claim, idx) => {
3904
+ const ans = res.answers[`claim_${idx}`];
3905
+ const verdict = ans?.type === "choice" && ["supported", "refuted", "not_enough_evidence"].includes(ans.choice) ? ans.choice : detBaseline.claims[idx]?.isSupported ? "supported" : "not_enough_evidence";
3906
+ const prob = ans?.probabilities?.[verdict] ?? (verdict === "supported" ? 0.85 : 0.4);
3907
+ return {
3908
+ claimText: claim,
3909
+ verdict,
3910
+ isSupported: verdict === "supported",
3911
+ isLlmVerified: true,
3912
+ confidenceScore: Math.round(prob * 100),
3913
+ extractedQuote: detBaseline.claims[idx]?.extractedQuote,
3914
+ explanation: `Evaluated via Decision Model NLI choice (${verdict}).`
3915
+ };
3916
+ });
3917
+ const supportedCount = verifiedClaims.filter((c) => c.verdict === "supported").length;
3918
+ const refutedCount = verifiedClaims.filter((c) => c.verdict === "refuted").length;
3919
+ const supportPct = supportedCount / claims.length * 100;
3920
+ const hallucinationRisk = refutedCount > 0 ? "high" : supportPct >= 75 ? "low" : "medium";
3921
+ return {
3922
+ totalClaimsChecked: claims.length,
3923
+ supportedClaimsCount: supportedCount,
3924
+ refutedClaimsCount: refutedCount,
3925
+ unverifiedClaimsCount: claims.length - supportedCount,
3926
+ hallucinationRisk,
3927
+ isLlmVerified: true,
3928
+ claims: verifiedClaims,
3929
+ reportMd: detBaseline.reportMd
3930
+ };
3931
+ } catch {
3932
+ }
3933
+ }
3934
+ if (options.llm) {
3935
+ return this.claimVerifier.verifyClaims(claims, sourceCorpus, { llm: options.llm });
3936
+ }
3937
+ return this.claimVerifier.verifyClaimsDeterministic(claims, sourceCorpus);
3938
+ }
3154
3939
  /**
3155
3940
  * Stage B: Synthesizes `EvidenceLedger` excerpts into `outputSchema<T>` + `markdownReport`
3156
3941
  * and runs deterministic schema, citation, and claim verification gates.
3157
3942
  */
3158
3943
  async synthesizeAndVerify(params) {
3159
- const { contract, profile, ledger, approvedCount, minSources, missingGaps, roundTraces, provenanceMd, llm } = params;
3944
+ const {
3945
+ contract,
3946
+ mode,
3947
+ profile,
3948
+ ledger,
3949
+ approvedCount,
3950
+ minSources,
3951
+ shouldVerifyClaims,
3952
+ missingGaps,
3953
+ roundTraces,
3954
+ modeClassificationTrace,
3955
+ channelTraces,
3956
+ provenanceMd,
3957
+ llm,
3958
+ decision
3959
+ } = params;
3160
3960
  const synthesisCorpus = ledger.buildSynthesisCorpus(12);
3161
3961
  const items = ledger.getItems();
3162
3962
  const receipts = ledger.getReceipts();
@@ -3173,7 +3973,7 @@ ${receipts.map((r) => `- [${r.id}] ${r.title} (headings: ${r.headings.join(", ")
3173
3973
  const prompt = [
3174
3974
  `You are a Principal Research Synthesizer. Synthesize the verified EvidenceLedger sources below to fulfill the Research Contract.`,
3175
3975
  `Objective: "${contract.objective}"`,
3176
- `Profile: ${profile}`,
3976
+ `Mode: ${mode} | Profile: ${profile}`,
3177
3977
  contract.context?.ageBand ? `Learner Age Band: ${contract.context.ageBand[0]}-${contract.context.ageBand[1]}` : "",
3178
3978
  contract.context?.hardwarePlatform ? `Hardware Platform: ${contract.context.hardwarePlatform}` : "",
3179
3979
  contract.context?.softwareEnv ? `Software/Tools: ${contract.context.softwareEnv}` : "",
@@ -3262,6 +4062,7 @@ Return ONLY a valid JSON object with the exact envelope:`,
3262
4062
  if (synthesizedData === null && !contract.outputSchema) {
3263
4063
  synthesizedData = {
3264
4064
  objective: contract.objective,
4065
+ mode,
3265
4066
  profile,
3266
4067
  sources: receipts,
3267
4068
  codeSnippets: items.flatMap((i) => i.codeBlocks).slice(0, 4),
@@ -3290,7 +4091,10 @@ ${JSON.stringify(synthesizedData || {})}`;
3290
4091
  }
3291
4092
  }
3292
4093
  const claimsToVerify = keyClaims.length > 0 ? keyClaims : items.slice(0, 4).map((i) => i.keyExcerpts[0]).filter((e) => Boolean(e && e.length > 25));
3293
- const claimVerification = claimsToVerify.length > 0 ? this.claimVerifier.verifyClaimsDeterministic(claimsToVerify, ledger.buildFullRawCorpus()) : void 0;
4094
+ const claimVerification = claimsToVerify.length > 0 ? shouldVerifyClaims ? await this.verifyClaimsWithDecisionOrLlm(claimsToVerify, ledger.buildFullRawCorpus(), {
4095
+ decision,
4096
+ llm
4097
+ }) : this.claimVerifier.verifyClaimsDeterministic(claimsToVerify, ledger.buildFullRawCorpus()) : void 0;
3294
4098
  let status = "success";
3295
4099
  if (!isLlmSynthesized && llm) {
3296
4100
  status = "degraded";
@@ -3302,140 +4106,172 @@ ${JSON.stringify(synthesizedData || {})}`;
3302
4106
  return {
3303
4107
  status,
3304
4108
  objective: contract.objective,
4109
+ mode,
3305
4110
  profile,
3306
4111
  roundsExecuted: roundTraces.length,
3307
4112
  data: synthesizedData,
3308
4113
  markdownReport,
3309
- tier1Summary: tier1Summary.slice(0, 1800),
3310
- tier2TechnicalDigest: tier2TechnicalDigest.slice(0, 4e3),
4114
+ tier1Summary,
4115
+ tier2TechnicalDigest,
3311
4116
  ledgerItems: items,
3312
4117
  receipts,
3313
4118
  validCitationIds,
3314
4119
  invalidCitationIds,
3315
- missingGaps: Array.from(new Set(missingGaps)),
4120
+ missingGaps,
3316
4121
  roundTraces,
4122
+ modeClassificationTrace,
4123
+ channelTraces,
3317
4124
  claimVerification,
3318
4125
  provenanceMd
3319
4126
  };
3320
4127
  }
3321
4128
  buildDeterministicMarkdownReport(objective, profile, items, requiredSections) {
4129
+ const sections = requiredSections && requiredSections.length > 0 ? requiredSections : [
4130
+ "Executive Summary",
4131
+ "Verified Technical & Domain Findings",
4132
+ "Code Exemplars & Specifications",
4133
+ "Verified Source Ledger"
4134
+ ];
3322
4135
  const lines = [
3323
- `# \u{1F52C} Autonomous Research Dossier: ${objective}`,
3324
- `> **Profile:** \`${profile.toUpperCase()}\` | **Verified Ledger Sources:** \`${items.length}\``
4136
+ `# Research Synthesis Report: ${objective}`,
4137
+ `> **Profile:** \`${profile}\` | **Verified Sources:** \`${items.length}\``,
4138
+ ""
3325
4139
  ];
3326
- if (requiredSections && requiredSections.length > 0) {
3327
- for (const section of requiredSections) {
3328
- lines.push(`
3329
- ## ${section}`);
3330
- for (const item of items.slice(0, 4)) {
3331
- if (item.keyExcerpts[0]) {
3332
- lines.push(`- **[${item.id}] ${item.title}**: ${item.keyExcerpts[0]}`);
4140
+ for (const sec of sections) {
4141
+ lines.push(`## ${sec}`);
4142
+ const lower = sec.toLowerCase();
4143
+ if (lower.includes("code") || lower.includes("spec") || lower.includes("table") || lower.includes("exemplar")) {
4144
+ const blocks = items.flatMap((i) => i.codeBlocks.map((cb) => ({ id: i.id, cb }))).slice(0, 3);
4145
+ const tables = items.flatMap((i) => i.tables.map((tb) => ({ id: i.id, tb }))).slice(0, 2);
4146
+ if (blocks.length === 0 && tables.length === 0) {
4147
+ lines.push(
4148
+ ...items.slice(0, 3).map((i) => `- **[${i.id}] ${i.title}**: ${i.keyExcerpts[0] || ""}`)
4149
+ );
4150
+ } else {
4151
+ for (const b of blocks) {
4152
+ lines.push(`From **[${b.id}]**:
4153
+ \`\`\`${b.cb.language || "text"}
4154
+ ${b.cb.code.slice(0, 500)}
4155
+ \`\`\``);
4156
+ }
4157
+ for (const t of tables) {
4158
+ lines.push(`From **[${t.id}]**:
4159
+
4160
+ ${t.tb}`);
3333
4161
  }
3334
4162
  }
4163
+ } else if (lower.includes("source") || lower.includes("reference") || lower.includes("ledger")) {
4164
+ for (const item of items) {
4165
+ lines.push(`- **[${item.id}]** [${item.title}](${item.url}) (${item.sourceType}, Score: ${item.relevanceScore}/10)`);
4166
+ }
4167
+ } else {
4168
+ for (const item of items.slice(0, 6)) {
4169
+ const excerpt = item.keyExcerpts[0] || item.title;
4170
+ lines.push(`- **[${item.id}] ${item.title}**: ${excerpt}`);
4171
+ }
3335
4172
  }
3336
- } else {
3337
- lines.push(`
3338
- ## 1. Executive Summary & Verified Findings`);
3339
- for (const item of items) {
3340
- lines.push(
3341
- `### [${item.id}] ${item.title} (${item.sourceType.toUpperCase()} \xB7 Score \`${item.relevanceScore}/10\`)`,
3342
- `- **URL:** ${item.url}`,
3343
- ...item.keyExcerpts.slice(0, 3).map((ex) => `- ${ex}`)
3344
- );
3345
- }
3346
- }
3347
- const allCode = items.flatMap((i) => i.codeBlocks.map((cb) => ({ id: i.id, ...cb }))).slice(0, 4);
3348
- if (allCode.length > 0) {
3349
- lines.push(
3350
- `
3351
- ## Extracted Code Examples`,
3352
- ...allCode.map((c) => `From **[${c.id}]**:
3353
- \`\`\`${c.language || "text"}
3354
- ${c.code}
3355
- \`\`\``)
3356
- );
3357
- }
3358
- const allTables = items.flatMap((i) => i.tables.map((t) => ({ id: i.id, table: t }))).slice(0, 4);
3359
- if (allTables.length > 0) {
3360
- lines.push(
3361
- `
3362
- ## Extracted Specification Tables`,
3363
- ...allTables.map((t) => `From **[${t.id}]**:
3364
-
3365
- ${t.table}`)
3366
- );
4173
+ lines.push("");
3367
4174
  }
3368
- lines.push(
3369
- `
3370
- ## Evidence Ledger Citations`,
3371
- ...items.map((i) => `- **[${i.id}]** [${i.title}](${i.url}) \u2014 *${i.sourceType}, score ${i.relevanceScore}/10*`)
3372
- );
3373
4175
  return lines.join("\n");
3374
4176
  }
3375
4177
  };
4178
+ var ResearchAgentToolInputSchema = zod.z.object({
4179
+ objective: zod.z.string().min(3).describe("Core research question or objective to investigate"),
4180
+ mode: zod.z.enum(["auto", "search", "research", "deep-research"]).optional().describe("Execution mode: auto, search (<=8s), research (<=90s, 2 channels), or deep-research (<=300s, 5 channels)"),
4181
+ preferredChannels: zod.z.array(zod.z.enum(["web_docs", "academic", "social_pulse", "stem_oer", "video_media"])).optional().describe("Optional preferred source channels to prioritize"),
4182
+ profile: zod.z.enum([
4183
+ "auto",
4184
+ "fast_grounded",
4185
+ "deep_autonomous",
4186
+ "technical",
4187
+ "academic",
4188
+ "social_pulse",
4189
+ "curriculum_oer",
4190
+ "general"
4191
+ ]).optional().describe("Legacy domain profile"),
4192
+ requiredAttributes: zod.z.array(zod.z.string()).optional().describe("Specific technical attributes, specs, or sub-questions that must be covered"),
4193
+ requiredSections: zod.z.array(zod.z.string()).optional().describe("Required Markdown sections in the synthesized report"),
4194
+ requireCodeExamples: zod.z.boolean().optional().describe("Whether verified code snippets are required"),
4195
+ requireTables: zod.z.boolean().optional().describe("Whether markdown specification/pinout tables are required"),
4196
+ verifyClaims: zod.z.boolean().optional().describe("Whether to run semantic NLI claim verification"),
4197
+ minSources: zod.z.number().int().min(1).max(10).optional().describe("Minimum number of verified sources (default: 2)"),
4198
+ maxChannels: zod.z.number().int().min(1).max(5).optional().describe("Maximum number of ok channels to harvest"),
4199
+ maxRounds: zod.z.number().int().min(1).max(4).optional().describe("Maximum Plan-Harvest-Evaluate rounds"),
4200
+ recencyDays: zod.z.number().int().min(1).max(365).optional().describe("Recency window in days for social pulse signals"),
4201
+ hardwarePlatform: zod.z.string().optional().describe("Optional hardware context (e.g., Arduino Uno, ESP32)"),
4202
+ softwareEnv: zod.z.string().optional().describe("Optional software/IDE context (e.g., mBlock 5, Roblox Studio, Swift 6)")
4203
+ });
3376
4204
  async function runResearchSubAgent(contract, config = {}) {
3377
4205
  const agent = new ResearchSubAgent(config);
3378
- return agent.run(contract, { llm: config.llm });
4206
+ return agent.run(contract);
3379
4207
  }
3380
- var ResearchAgentToolInputSchema = zod.z.object({
3381
- objective: zod.z.string().min(3).describe("The specific research question, topic, or technical requirement to investigate."),
3382
- profile: zod.z.enum(["auto", "fast_grounded", "deep_autonomous", "technical", "academic", "social_pulse", "curriculum_oer", "general"]).optional().default("auto").describe("Execution profile selecting the appropriate multi-source harvesters and loop budget."),
3383
- requiredSections: zod.z.array(zod.z.string()).optional().describe("Optional list of required Markdown sections in the synthesized report."),
3384
- requiredAttributes: zod.z.array(zod.z.string()).optional().describe("Optional list of specific technical attributes, specs, or sub-questions that must be verified."),
3385
- requireCodeExamples: zod.z.boolean().optional().describe("Set true if verified code examples are mandatory."),
3386
- requireTables: zod.z.boolean().optional().describe("Set true if pinout or specification tables are mandatory."),
3387
- recencyDays: zod.z.number().int().min(1).max(365).optional().describe("Recency window in days for social/community pulse."),
3388
- maxRounds: zod.z.number().int().min(1).max(4).optional().describe("Maximum Plan-Harvest-Evaluate rounds (1-4).")
3389
- });
3390
4208
  function createResearchAgentTool(config = {}) {
3391
- const subAgent = new ResearchSubAgent(config);
4209
+ const agent = new ResearchSubAgent(config);
3392
4210
  return {
3393
- name: "research_subagent",
3394
- description: "Autonomous Plan-and-Execute Research Sub-Agent. Plans multi-source queries (Web, Official Docs, Semantic Scholar, OpenAlex, HackerNews/GitHub 30-day Pulse, STEM OER), verifies sources into an immutable EvidenceLedger [RES-xx], checks for coverage gaps, and returns a citation-grounded report.",
4211
+ name: "run_research_subagent",
4212
+ description: "Delegate a research objective to the autonomous Plan-and-Execute Research Sub-Agent (supports mode: auto | search | research | deep-research).",
3395
4213
  parameters: ResearchAgentToolInputSchema,
3396
- inputSchema: ResearchAgentToolInputSchema,
3397
4214
  execute: async (input) => {
3398
- const result = await subAgent.run({
4215
+ const result = await agent.run({
3399
4216
  objective: input.objective,
3400
- profile: input.profile,
4217
+ mode: input.mode ?? "auto",
4218
+ preferredChannels: input.preferredChannels,
4219
+ profile: input.profile ?? "auto",
3401
4220
  requiredSections: input.requiredSections,
3402
4221
  acceptanceCriteria: {
3403
- requiredAttributes: input.requiredAttributes,
4222
+ minSources: input.minSources ?? 2,
3404
4223
  requireCodeExamples: input.requireCodeExamples,
3405
4224
  requireTables: input.requireTables,
3406
- recencyDays: input.recencyDays
4225
+ verifyClaims: input.verifyClaims,
4226
+ recencyDays: input.recencyDays ?? 30,
4227
+ requiredAttributes: input.requiredAttributes
3407
4228
  },
3408
4229
  budget: {
3409
- maxRounds: input.maxRounds
3410
- }
4230
+ maxRounds: input.maxRounds,
4231
+ maxChannels: input.maxChannels
4232
+ },
4233
+ context: input.hardwarePlatform || input.softwareEnv ? {
4234
+ ...config.defaultCourseContext,
4235
+ hardwarePlatform: input.hardwarePlatform ?? config.defaultCourseContext?.hardwarePlatform,
4236
+ softwareEnv: input.softwareEnv ?? config.defaultCourseContext?.softwareEnv
4237
+ } : config.defaultCourseContext
3411
4238
  });
3412
4239
  return {
3413
4240
  status: result.status,
3414
- objective: result.objective,
4241
+ mode: result.mode,
3415
4242
  profile: result.profile,
3416
4243
  roundsExecuted: result.roundsExecuted,
3417
4244
  tier1Summary: result.tier1Summary,
3418
4245
  tier2TechnicalDigest: result.tier2TechnicalDigest,
3419
- citations: result.receipts.map((r) => ({
3420
- id: r.id,
3421
- title: r.title,
3422
- url: r.url,
3423
- sourceType: r.sourceType,
3424
- score: r.relevanceScore
3425
- })),
4246
+ markdownReport: result.markdownReport,
4247
+ citations: result.receipts,
4248
+ validCitationIds: result.validCitationIds,
3426
4249
  missingGaps: result.missingGaps,
3427
- fullResult: result
4250
+ modeClassificationTrace: result.modeClassificationTrace,
4251
+ channelTraces: result.channelTraces
3428
4252
  };
3429
4253
  }
3430
4254
  };
3431
4255
  }
3432
4256
 
3433
4257
  exports.EvidenceLedger = EvidenceLedger;
4258
+ exports.PRIOR_MATRIX = PRIOR_MATRIX;
4259
+ exports.QUESTION_FACETS = QUESTION_FACETS;
4260
+ exports.RESEARCH_MODE_PRESETS = RESEARCH_MODE_PRESETS;
3434
4261
  exports.RESEARCH_PROFILE_PRESETS = RESEARCH_PROFILE_PRESETS;
3435
4262
  exports.ResearchAgentToolInputSchema = ResearchAgentToolInputSchema;
3436
4263
  exports.ResearchSubAgent = ResearchSubAgent;
4264
+ exports.SOURCE_CHANNELS = SOURCE_CHANNELS;
4265
+ exports.classifyChannelStatus = classifyChannelStatus;
4266
+ exports.classifyModeAndPrior = classifyModeAndPrior;
4267
+ exports.computeContractComplexityScore = computeContractComplexityScore;
3437
4268
  exports.createResearchAgentTool = createResearchAgentTool;
4269
+ exports.evaluateAttributeCoverageWithDecision = evaluateAttributeCoverageWithDecision;
4270
+ exports.inferFallbackFacetProbabilities = inferFallbackFacetProbabilities;
4271
+ exports.isSemanticRankedHit = isSemanticRankedHit;
4272
+ exports.rankChannelsByExpectedPrior = rankChannelsByExpectedPrior;
3438
4273
  exports.resolveResearchProfile = resolveResearchProfile;
4274
+ exports.runConcurrentRefillScheduler = runConcurrentRefillScheduler;
3439
4275
  exports.runResearchSubAgent = runResearchSubAgent;
3440
4276
  //# sourceMappingURL=index.cjs.map
3441
4277
  //# sourceMappingURL=index.cjs.map