@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
@@ -0,0 +1,1931 @@
1
+ import { OpenAlexClient } from './chunk-SEHHDO7X.js';
2
+ import { SocialPulseHarvester, StemResourceResearcher } from './chunk-7BGR4E37.js';
3
+ import { ClaimVerifier } from './chunk-32B5PVTQ.js';
4
+ import { MultiSourceSearchEngine, HealthAuditor, classifyTechnicalDomain, isCommercialOrNoise } from './chunk-MJIREPKJ.js';
5
+ import { AcademicSearchEngine } from './chunk-EWIAA2CC.js';
6
+ import { EvidenceScorer, ProvenanceTracker, extractTopSentences } from './chunk-PFECHAAR.js';
7
+ import { WebScraper, YouTubeIngestionService } from './chunk-JV6Z6WUQ.js';
8
+ import { z } from 'zod';
9
+
10
+ // src/agent/types.ts
11
+ var RESEARCH_MODE_PRESETS = {
12
+ search: {
13
+ mode: "search",
14
+ timeoutMs: 15e3,
15
+ maxChannels: 1,
16
+ channelConcurrency: 1,
17
+ maxRounds: 1,
18
+ maxQueriesPerRound: 1,
19
+ maxScrapePerRound: 0,
20
+ verifyClaims: false
21
+ },
22
+ research: {
23
+ mode: "research",
24
+ timeoutMs: 18e4,
25
+ maxChannels: 2,
26
+ channelConcurrency: 2,
27
+ maxRounds: 1,
28
+ maxQueriesPerRound: 3,
29
+ maxScrapePerRound: 3,
30
+ verifyClaims: false
31
+ },
32
+ "deep-research": {
33
+ mode: "deep-research",
34
+ timeoutMs: 6e5,
35
+ maxChannels: 5,
36
+ channelConcurrency: 2,
37
+ maxRounds: 3,
38
+ maxQueriesPerRound: 4,
39
+ maxScrapePerRound: 4,
40
+ verifyClaims: true
41
+ }
42
+ };
43
+ var RESEARCH_PROFILE_PRESETS = {
44
+ fast_grounded: {
45
+ maxRounds: 1,
46
+ maxQueriesPerRound: 3,
47
+ maxScrapePerRound: 3,
48
+ timeoutMs: 18e4,
49
+ enableWeb: true,
50
+ enableAcademic: false,
51
+ enableSocialPulse: false,
52
+ enableStemOer: false
53
+ },
54
+ deep_autonomous: {
55
+ maxRounds: 3,
56
+ maxQueriesPerRound: 4,
57
+ maxScrapePerRound: 4,
58
+ timeoutMs: 6e5,
59
+ enableWeb: true,
60
+ enableAcademic: true,
61
+ enableSocialPulse: true,
62
+ enableStemOer: true
63
+ },
64
+ technical: {
65
+ maxRounds: 1,
66
+ maxQueriesPerRound: 3,
67
+ maxScrapePerRound: 3,
68
+ timeoutMs: 18e4,
69
+ enableWeb: true,
70
+ enableAcademic: false,
71
+ enableSocialPulse: true,
72
+ enableStemOer: false
73
+ },
74
+ academic: {
75
+ maxRounds: 1,
76
+ maxQueriesPerRound: 3,
77
+ maxScrapePerRound: 2,
78
+ timeoutMs: 18e4,
79
+ enableWeb: true,
80
+ enableAcademic: true,
81
+ enableSocialPulse: false,
82
+ enableStemOer: false
83
+ },
84
+ social_pulse: {
85
+ maxRounds: 1,
86
+ maxQueriesPerRound: 3,
87
+ maxScrapePerRound: 2,
88
+ timeoutMs: 18e4,
89
+ enableWeb: true,
90
+ enableAcademic: false,
91
+ enableSocialPulse: true,
92
+ enableStemOer: false
93
+ },
94
+ curriculum_oer: {
95
+ maxRounds: 1,
96
+ maxQueriesPerRound: 3,
97
+ maxScrapePerRound: 3,
98
+ timeoutMs: 18e4,
99
+ enableWeb: true,
100
+ enableAcademic: false,
101
+ enableSocialPulse: false,
102
+ enableStemOer: true
103
+ },
104
+ general: {
105
+ maxRounds: 1,
106
+ maxQueriesPerRound: 3,
107
+ maxScrapePerRound: 3,
108
+ timeoutMs: 18e4,
109
+ enableWeb: true,
110
+ enableAcademic: false,
111
+ enableSocialPulse: false,
112
+ enableStemOer: false
113
+ }
114
+ };
115
+
116
+ // src/agent/evidenceLedger.ts
117
+ function normalizeUrlKey(rawUrl) {
118
+ try {
119
+ const u = new URL(rawUrl.trim());
120
+ u.hash = "";
121
+ for (const param of ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "ref"]) {
122
+ u.searchParams.delete(param);
123
+ }
124
+ return u.toString().replace(/\/$/, "").toLowerCase();
125
+ } catch {
126
+ return rawUrl.trim().replace(/\/$/, "").toLowerCase();
127
+ }
128
+ }
129
+ var EvidenceLedger = class {
130
+ items = [];
131
+ urlIndex = /* @__PURE__ */ new Map();
132
+ idIndex = /* @__PURE__ */ new Map();
133
+ allocateId() {
134
+ const nextNum = this.items.length + 1;
135
+ return `RES-${String(nextNum).padStart(2, "0")}`;
136
+ }
137
+ /**
138
+ * Records or upgrades a ledger entry from a full `ScrapedDocument`.
139
+ */
140
+ addScrapedDocument(doc, relevanceScore, extraTakeaways = []) {
141
+ const key = normalizeUrlKey(doc.url);
142
+ const existing = this.urlIndex.get(key);
143
+ const mergedExcerpts = Array.from(
144
+ new Set([
145
+ ...extraTakeaways,
146
+ ...doc.keyExcerpts || [],
147
+ doc.markdownContent.replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, 450)
148
+ ].filter((e) => e && e.trim().length > 20))
149
+ ).slice(0, 6);
150
+ const sourceType = doc.fetchProvider === "youtube" ? "youtube" : "web";
151
+ if (existing) {
152
+ existing.title = doc.title || existing.title;
153
+ existing.relevanceScore = Math.max(existing.relevanceScore, relevanceScore);
154
+ existing.headings = doc.extractedHeadings?.slice(0, 8) || existing.headings;
155
+ existing.keyExcerpts = mergedExcerpts.length > 0 ? mergedExcerpts : existing.keyExcerpts;
156
+ existing.codeBlocks = (doc.extractedCodeBlocks || []).slice(0, 4);
157
+ existing.tables = (doc.extractedTables || []).slice(0, 4);
158
+ existing.rawByteSize = Math.max(existing.rawByteSize, doc.byteSize || 0);
159
+ return this.toCompactReceipt(existing);
160
+ }
161
+ const item = {
162
+ id: this.allocateId(),
163
+ sourceType,
164
+ title: doc.title || "Untitled Document",
165
+ url: doc.url,
166
+ relevanceScore: Math.max(1, Math.min(10, Math.round(relevanceScore))),
167
+ headings: (doc.extractedHeadings || []).slice(0, 8),
168
+ keyExcerpts: mergedExcerpts,
169
+ codeBlocks: (doc.extractedCodeBlocks || []).slice(0, 4),
170
+ tables: (doc.extractedTables || []).slice(0, 4),
171
+ rawByteSize: doc.byteSize || Buffer.byteLength(doc.markdownContent || "", "utf-8"),
172
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
173
+ };
174
+ this.items.push(item);
175
+ this.urlIndex.set(key, item);
176
+ this.idIndex.set(item.id, item);
177
+ return this.toCompactReceipt(item);
178
+ }
179
+ /**
180
+ * Records a lightweight search hit when full scraping is skipped or pending.
181
+ */
182
+ addSearchHit(hit, relevanceScore = 6) {
183
+ const key = normalizeUrlKey(hit.url);
184
+ const existing = this.urlIndex.get(key);
185
+ if (existing) {
186
+ return this.toCompactReceipt(existing);
187
+ }
188
+ const snippet = (hit.content || "").replace(/\s+/g, " ").trim();
189
+ const item = {
190
+ id: this.allocateId(),
191
+ sourceType: hit.engine === "academic" ? "academic" : "web",
192
+ title: hit.title || "Search Result",
193
+ url: hit.url,
194
+ relevanceScore: Math.max(1, Math.min(10, Math.round(relevanceScore))),
195
+ headings: [],
196
+ keyExcerpts: snippet ? [snippet.slice(0, 450)] : [],
197
+ codeBlocks: [],
198
+ tables: [],
199
+ rawByteSize: Buffer.byteLength(snippet, "utf-8"),
200
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
201
+ };
202
+ this.items.push(item);
203
+ this.urlIndex.set(key, item);
204
+ this.idIndex.set(item.id, item);
205
+ return this.toCompactReceipt(item);
206
+ }
207
+ /**
208
+ * Records a peer-reviewed or preprint paper from Semantic Scholar, OpenAlex, Crossref, or arXiv.
209
+ */
210
+ addAcademicPaper(paper) {
211
+ const url = paper.url || paper.pdfUrl || (paper.doi ? `https://doi.org/${paper.doi}` : `https://openalex.org/${paper.id}`);
212
+ const key = normalizeUrlKey(url);
213
+ const existing = this.urlIndex.get(key);
214
+ if (existing) {
215
+ return this.toCompactReceipt(existing);
216
+ }
217
+ const abstractOrTldr = [paper.tldr, paper.abstract].filter(Boolean).join(" \u2014 ").trim();
218
+ const citationBonus = paper.citationCount >= 50 ? 9 : paper.citationCount >= 10 ? 8 : 7;
219
+ const item = {
220
+ id: this.allocateId(),
221
+ sourceType: "academic",
222
+ title: paper.title,
223
+ url,
224
+ authorOrVenue: [paper.authors?.slice(0, 3).join(", "), paper.venue, paper.year].filter(Boolean).join(" \xB7 "),
225
+ publishedDate: paper.year ? String(paper.year) : void 0,
226
+ relevanceScore: citationBonus,
227
+ headings: paper.fieldsOfStudy || [],
228
+ keyExcerpts: abstractOrTldr ? [abstractOrTldr.slice(0, 600)] : [`Academic paper: ${paper.title}`],
229
+ codeBlocks: [],
230
+ tables: [],
231
+ rawByteSize: Buffer.byteLength(abstractOrTldr || paper.title, "utf-8"),
232
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
233
+ };
234
+ this.items.push(item);
235
+ this.urlIndex.set(key, item);
236
+ this.idIndex.set(item.id, item);
237
+ return this.toCompactReceipt(item);
238
+ }
239
+ /**
240
+ * Records a 30-day social/developer pulse signal (HackerNews, GitHub, Reddit).
241
+ */
242
+ addSocialPulseItem(pulse) {
243
+ const key = normalizeUrlKey(pulse.url);
244
+ const existing = this.urlIndex.get(key);
245
+ if (existing) {
246
+ return this.toCompactReceipt(existing);
247
+ }
248
+ const item = {
249
+ id: this.allocateId(),
250
+ sourceType: "social_pulse",
251
+ title: pulse.title,
252
+ url: pulse.url,
253
+ authorOrVenue: `${pulse.platform.toUpperCase()}${pulse.author ? ` (@${pulse.author})` : ""}`,
254
+ publishedDate: pulse.createdAt,
255
+ relevanceScore: Math.max(1, Math.min(10, pulse.engagementScore)),
256
+ headings: [pulse.platform.toUpperCase()],
257
+ keyExcerpts: [pulse.snippet.slice(0, 450)],
258
+ codeBlocks: [],
259
+ tables: [],
260
+ rawByteSize: Buffer.byteLength(pulse.snippet, "utf-8"),
261
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
262
+ };
263
+ this.items.push(item);
264
+ this.urlIndex.set(key, item);
265
+ this.idIndex.set(item.id, item);
266
+ return this.toCompactReceipt(item);
267
+ }
268
+ /**
269
+ * Records a verified STEM OER simulation/resource (PhET, OpenStax, NASA, CS Unplugged).
270
+ */
271
+ addStemResource(resource) {
272
+ const key = normalizeUrlKey(resource.url);
273
+ const existing = this.urlIndex.get(key);
274
+ if (existing) {
275
+ return this.toCompactReceipt(existing);
276
+ }
277
+ const excerpt = `${resource.description} [Provider: ${resource.provider}${resource.license ? `, License: ${resource.license}` : ""}]`;
278
+ const item = {
279
+ id: this.allocateId(),
280
+ sourceType: "stem_oer",
281
+ title: resource.title,
282
+ url: resource.url,
283
+ authorOrVenue: resource.provider,
284
+ relevanceScore: 8,
285
+ headings: [resource.provider],
286
+ keyExcerpts: [excerpt.slice(0, 450)],
287
+ codeBlocks: [],
288
+ tables: [],
289
+ rawByteSize: Buffer.byteLength(excerpt, "utf-8"),
290
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
291
+ };
292
+ this.items.push(item);
293
+ this.urlIndex.set(key, item);
294
+ this.idIndex.set(item.id, item);
295
+ return this.toCompactReceipt(item);
296
+ }
297
+ /**
298
+ * Projects a full `LedgerItem` into a compact receipt (<= 150 tokens) for Stage A planning & gap analysis.
299
+ */
300
+ toCompactReceipt(item) {
301
+ const rawExcerpt = item.keyExcerpts[0] || item.title;
302
+ return {
303
+ id: item.id,
304
+ sourceType: item.sourceType,
305
+ title: item.title.slice(0, 140),
306
+ url: item.url,
307
+ relevanceScore: item.relevanceScore,
308
+ headings: item.headings.slice(0, 5),
309
+ codeBlockCount: item.codeBlocks.length,
310
+ tableCount: item.tables.length,
311
+ briefExcerpt: rawExcerpt.slice(0, 300)
312
+ };
313
+ }
314
+ getItems() {
315
+ return [...this.items];
316
+ }
317
+ getApprovedItems(minScore = 6) {
318
+ return this.items.filter((i) => i.relevanceScore >= minScore);
319
+ }
320
+ getReceipts() {
321
+ return this.items.map((i) => this.toCompactReceipt(i));
322
+ }
323
+ getById(id) {
324
+ return this.idIndex.get(id.toUpperCase());
325
+ }
326
+ getTotalCodeBlocks() {
327
+ return this.items.reduce((sum, i) => sum + i.codeBlocks.length, 0);
328
+ }
329
+ getTotalTables() {
330
+ return this.items.reduce((sum, i) => sum + i.tables.length, 0);
331
+ }
332
+ /**
333
+ * Formats the top verified items with `[RES-xx]` tags, substantive excerpts, code blocks,
334
+ * and tables for Stage B Contract Synthesis.
335
+ */
336
+ buildSynthesisCorpus(maxItems = 12) {
337
+ const sorted = [...this.items].sort((a, b) => b.relevanceScore - a.relevanceScore).slice(0, maxItems);
338
+ if (sorted.length === 0) {
339
+ return "No verified sources recorded in EvidenceLedger.";
340
+ }
341
+ return sorted.map((item) => {
342
+ const parts = [
343
+ `[${item.id}] (${item.sourceType.toUpperCase()} \xB7 Score ${item.relevanceScore}/10) Title: ${item.title}`,
344
+ `URL: ${item.url}`
345
+ ];
346
+ if (item.authorOrVenue) {
347
+ parts.push(`Source/Author: ${item.authorOrVenue}`);
348
+ }
349
+ if (item.headings.length > 0) {
350
+ parts.push(`Sections: ${item.headings.join(" | ")}`);
351
+ }
352
+ if (item.keyExcerpts.length > 0) {
353
+ parts.push(`Verified Excerpts:
354
+ ${item.keyExcerpts.map((e) => `- ${e}`).join("\n")}`);
355
+ }
356
+ if (item.codeBlocks.length > 0) {
357
+ parts.push(
358
+ `Extracted Code Blocks:
359
+ ` + item.codeBlocks.slice(0, 2).map((cb) => `\`\`\`${cb.language || "text"}
360
+ ${cb.code.slice(0, 600)}
361
+ \`\`\``).join("\n")
362
+ );
363
+ }
364
+ if (item.tables.length > 0) {
365
+ parts.push(`Extracted Tables:
366
+ ${item.tables.slice(0, 2).join("\n\n")}`);
367
+ }
368
+ return parts.join("\n");
369
+ }).join("\n\n---\n\n");
370
+ }
371
+ /**
372
+ * Returns concatenated plain text of all ledger items for deterministic/LLM `ClaimVerifier` checks.
373
+ */
374
+ buildFullRawCorpus() {
375
+ return this.items.map(
376
+ (i) => `${i.title}
377
+ ${i.keyExcerpts.join("\n")}
378
+ ${i.codeBlocks.map((c) => c.code).join("\n")}
379
+ ${i.tables.join("\n")}`
380
+ ).join("\n\n");
381
+ }
382
+ /**
383
+ * Scans any synthesized report or JSON string for `[RES-xx]` citation markers
384
+ * and verifies every marker against the ledger.
385
+ */
386
+ verifyCitationTags(synthesizedText) {
387
+ const matches = [...synthesizedText.matchAll(/\[?(RES-\d{2,3})\]?/gi)];
388
+ const validSet = /* @__PURE__ */ new Set();
389
+ const invalidSet = /* @__PURE__ */ new Set();
390
+ for (const m of matches) {
391
+ const tag = m[1].toUpperCase();
392
+ if (this.idIndex.has(tag)) {
393
+ validSet.add(tag);
394
+ } else {
395
+ invalidSet.add(tag);
396
+ }
397
+ }
398
+ return {
399
+ validCitationIds: Array.from(validSet),
400
+ invalidCitationIds: Array.from(invalidSet)
401
+ };
402
+ }
403
+ /**
404
+ * Maps ledger items into `ProvenanceRecord[]` for `ProvenanceTracker`.
405
+ */
406
+ toProvenanceRecords(defaultDomain = "general") {
407
+ return this.items.map((item) => ({
408
+ resourceId: item.id,
409
+ sourceUrl: item.url,
410
+ accessedAt: item.accessedAt,
411
+ domain: item.sourceType || defaultDomain,
412
+ relevanceScore: item.relevanceScore,
413
+ byteSize: item.rawByteSize
414
+ }));
415
+ }
416
+ };
417
+
418
+ // src/agent/decisionRouter.ts
419
+ var QUESTION_FACETS = [
420
+ "official_spec",
421
+ "how_to_example",
422
+ "pitfalls",
423
+ "pedagogy_theory",
424
+ "standards_policy",
425
+ "emerging_trend",
426
+ "learning_resources"
427
+ ];
428
+ var SOURCE_CHANNELS = [
429
+ "web_docs",
430
+ "academic",
431
+ "social_pulse",
432
+ "stem_oer",
433
+ "video_media"
434
+ ];
435
+ var PRIOR_MATRIX = {
436
+ official_spec: {
437
+ web_docs: 0.95,
438
+ academic: 0.2,
439
+ social_pulse: 0.3,
440
+ stem_oer: 0.15,
441
+ video_media: 0.25
442
+ },
443
+ how_to_example: {
444
+ web_docs: 0.9,
445
+ academic: 0.15,
446
+ social_pulse: 0.65,
447
+ stem_oer: 0.35,
448
+ video_media: 0.6
449
+ },
450
+ pitfalls: {
451
+ web_docs: 0.65,
452
+ academic: 0.25,
453
+ social_pulse: 0.9,
454
+ stem_oer: 0.1,
455
+ video_media: 0.35
456
+ },
457
+ pedagogy_theory: {
458
+ web_docs: 0.45,
459
+ academic: 0.95,
460
+ social_pulse: 0.2,
461
+ stem_oer: 0.7,
462
+ video_media: 0.3
463
+ },
464
+ standards_policy: {
465
+ web_docs: 0.75,
466
+ academic: 0.85,
467
+ social_pulse: 0.15,
468
+ stem_oer: 0.6,
469
+ video_media: 0.15
470
+ },
471
+ emerging_trend: {
472
+ web_docs: 0.6,
473
+ academic: 0.45,
474
+ social_pulse: 0.95,
475
+ stem_oer: 0.1,
476
+ video_media: 0.5
477
+ },
478
+ learning_resources: {
479
+ web_docs: 0.65,
480
+ academic: 0.3,
481
+ social_pulse: 0.25,
482
+ stem_oer: 0.95,
483
+ video_media: 0.7
484
+ }
485
+ };
486
+ function clampScore0to4(val, fallback = 1) {
487
+ const n = Number(val);
488
+ if (!Number.isFinite(n)) return fallback;
489
+ return Math.max(0, Math.min(4, n));
490
+ }
491
+ function computeContractComplexityScore(contract) {
492
+ let score = 0;
493
+ const reqAttrs = contract.acceptanceCriteria?.requiredAttributes?.length || 0;
494
+ const reqSecs = contract.requiredSections?.length || 0;
495
+ const totalReqs = reqAttrs + reqSecs;
496
+ if (totalReqs >= 4) score += 2;
497
+ else if (totalReqs >= 2) score += 1;
498
+ if (contract.acceptanceCriteria?.requireCodeExamples || contract.acceptanceCriteria?.requireTables) {
499
+ score += 1;
500
+ }
501
+ if ((contract.acceptanceCriteria?.minSources ?? 2) >= 4 || Boolean(contract.outputSchema)) {
502
+ score += 1;
503
+ }
504
+ return Math.min(4, score);
505
+ }
506
+ function inferFallbackFacetProbabilities(contract) {
507
+ const dist = {
508
+ official_spec: 0.25,
509
+ how_to_example: 0.25,
510
+ pitfalls: 0.15,
511
+ pedagogy_theory: 0.1,
512
+ standards_policy: 0.05,
513
+ emerging_trend: 0.1,
514
+ learning_resources: 0.1
515
+ };
516
+ if (contract.profile === "academic" || (contract.acceptanceCriteria?.minPeerReviewedSources ?? 0) >= 1) {
517
+ return {
518
+ official_spec: 0.05,
519
+ how_to_example: 0.05,
520
+ pitfalls: 0.05,
521
+ pedagogy_theory: 0.5,
522
+ standards_policy: 0.25,
523
+ emerging_trend: 0.05,
524
+ learning_resources: 0.05
525
+ };
526
+ }
527
+ if (contract.profile === "social_pulse") {
528
+ return {
529
+ official_spec: 0.05,
530
+ how_to_example: 0.15,
531
+ pitfalls: 0.35,
532
+ pedagogy_theory: 0.02,
533
+ standards_policy: 0.03,
534
+ emerging_trend: 0.35,
535
+ learning_resources: 0.05
536
+ };
537
+ }
538
+ if (contract.profile === "curriculum_oer") {
539
+ return {
540
+ official_spec: 0.05,
541
+ how_to_example: 0.15,
542
+ pitfalls: 0.05,
543
+ pedagogy_theory: 0.2,
544
+ standards_policy: 0.1,
545
+ emerging_trend: 0.05,
546
+ learning_resources: 0.4
547
+ };
548
+ }
549
+ return dist;
550
+ }
551
+ function rankChannelsByExpectedPrior(facetProbabilities, contract) {
552
+ const scores = {
553
+ web_docs: 0,
554
+ academic: 0,
555
+ social_pulse: 0,
556
+ stem_oer: 0,
557
+ video_media: 0
558
+ };
559
+ for (const facet of QUESTION_FACETS) {
560
+ const p = facetProbabilities[facet] ?? 0;
561
+ const row = PRIOR_MATRIX[facet];
562
+ for (const channel of SOURCE_CHANNELS) {
563
+ scores[channel] += p * row[channel];
564
+ }
565
+ }
566
+ if ((contract.acceptanceCriteria?.minPeerReviewedSources ?? 0) >= 1 || contract.profile === "academic") {
567
+ scores.academic += 0.3;
568
+ }
569
+ if (contract.profile === "social_pulse" || contract.acceptanceCriteria?.recencyDays !== void 0 && contract.acceptanceCriteria.recencyDays <= 30) {
570
+ scores.social_pulse += 0.2;
571
+ }
572
+ if (contract.acceptanceCriteria?.requireCodeExamples || contract.acceptanceCriteria?.requireTables || contract.context?.hardwarePlatform || contract.context?.softwareEnv) {
573
+ scores.web_docs += 0.15;
574
+ }
575
+ if (contract.profile === "curriculum_oer") {
576
+ scores.stem_oer += 0.3;
577
+ }
578
+ if (contract.preferredChannels && contract.preferredChannels.length > 0) {
579
+ contract.preferredChannels.forEach((ch, idx) => {
580
+ if (scores[ch] !== void 0) {
581
+ scores[ch] += Math.max(0.25, 0.6 - idx * 0.1);
582
+ }
583
+ });
584
+ }
585
+ return SOURCE_CHANNELS.map((channel) => ({
586
+ channel,
587
+ score: Number(scores[channel].toFixed(4))
588
+ })).sort((a, b) => b.score - a.score);
589
+ }
590
+ async function classifyModeAndPrior(contract, decision) {
591
+ let requestedMode = contract.mode ?? "auto";
592
+ if (!contract.mode && contract.profile) {
593
+ if (contract.profile === "deep_autonomous") {
594
+ requestedMode = "deep-research";
595
+ } else if (contract.profile !== "auto") {
596
+ requestedMode = "research";
597
+ }
598
+ }
599
+ const contractScore = computeContractComplexityScore(contract);
600
+ const hardEscalated = contract.acceptanceCriteria?.verifyClaims === true || (contract.acceptanceCriteria?.minPeerReviewedSources ?? 0) >= 2;
601
+ let readingDepth = 1.5;
602
+ let sourceDiversity = 1.5;
603
+ let decomposition = 1 + Math.min(2, (contract.acceptanceCriteria?.requiredAttributes?.length || 0) * 0.5);
604
+ let verificationStakes = hardEscalated ? 3.5 : 1.5;
605
+ let decisionEvaluated = false;
606
+ let facetProbabilities = inferFallbackFacetProbabilities(contract);
607
+ if (decision) {
608
+ try {
609
+ const contextLines = [
610
+ `Research Objective: ${contract.objective}`,
611
+ contract.context?.hardwarePlatform ? `Hardware Platform: ${contract.context.hardwarePlatform}` : "",
612
+ contract.context?.softwareEnv ? `Software Environment: ${contract.context.softwareEnv}` : "",
613
+ contract.context?.ageBand ? `Target Learner Age Band: ${contract.context.ageBand[0]}-${contract.context.ageBand[1]}` : "",
614
+ contract.acceptanceCriteria?.requiredAttributes?.length ? `Required Attributes: ${contract.acceptanceCriteria.requiredAttributes.join(", ")}` : "",
615
+ contract.requiredSections?.length ? `Required Report Sections: ${contract.requiredSections.join(", ")}` : ""
616
+ ].filter(Boolean).join("\n");
617
+ const result = await decision({
618
+ context: contextLines,
619
+ questions: [
620
+ {
621
+ id: "reading_depth",
622
+ type: "score",
623
+ 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)."
624
+ },
625
+ {
626
+ id: "source_diversity",
627
+ type: "score",
628
+ 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)."
629
+ },
630
+ {
631
+ id: "decomposition",
632
+ type: "score",
633
+ 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)."
634
+ },
635
+ {
636
+ id: "verification_stakes",
637
+ type: "score",
638
+ 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)."
639
+ },
640
+ {
641
+ id: "question_facet",
642
+ type: "choice",
643
+ criteria: "Classify the primary information need of this research objective into the most fitting facet.",
644
+ options: [...QUESTION_FACETS]
645
+ }
646
+ ]
647
+ });
648
+ const aDepth = result.answers["reading_depth"];
649
+ const aDiv = result.answers["source_diversity"];
650
+ const aDecomp = result.answers["decomposition"];
651
+ const aStakes = result.answers["verification_stakes"];
652
+ const aFacet = result.answers["question_facet"];
653
+ if (aDepth?.type === "score") readingDepth = clampScore0to4(aDepth.score, readingDepth);
654
+ if (aDiv?.type === "score") sourceDiversity = clampScore0to4(aDiv.score, sourceDiversity);
655
+ if (aDecomp?.type === "score") decomposition = clampScore0to4(aDecomp.score, decomposition);
656
+ if (aStakes?.type === "score") verificationStakes = clampScore0to4(aStakes.score, verificationStakes);
657
+ if (aFacet?.type === "choice") {
658
+ const rawProbs = aFacet.probabilities;
659
+ if (rawProbs && Object.keys(rawProbs).length > 0) {
660
+ let sum = 0;
661
+ const nextProbs = {};
662
+ for (const f of QUESTION_FACETS) {
663
+ const v = Math.max(0, Number(rawProbs[f] ?? 0));
664
+ nextProbs[f] = v;
665
+ sum += v;
666
+ }
667
+ if (sum > 0) {
668
+ for (const f of QUESTION_FACETS) {
669
+ nextProbs[f] = Number((nextProbs[f] / sum).toFixed(4));
670
+ }
671
+ facetProbabilities = nextProbs;
672
+ }
673
+ } else if (QUESTION_FACETS.includes(aFacet.choice)) {
674
+ const chosen = aFacet.choice;
675
+ const nextProbs = {};
676
+ for (const f of QUESTION_FACETS) {
677
+ nextProbs[f] = f === chosen ? 0.7 : 0.05;
678
+ }
679
+ facetProbabilities = nextProbs;
680
+ }
681
+ }
682
+ decisionEvaluated = true;
683
+ } catch (e) {
684
+ console.warn("[DecisionRouter] Decision model evaluation failed, using deterministic fallback:", e?.message || e);
685
+ }
686
+ }
687
+ const totalScore = Math.max(
688
+ 0,
689
+ Math.min(20, Math.round(readingDepth + sourceDiversity + decomposition + verificationStakes + contractScore))
690
+ );
691
+ let resolvedMode;
692
+ if (requestedMode !== "auto") {
693
+ resolvedMode = requestedMode;
694
+ } else if (hardEscalated || totalScore >= 13) {
695
+ resolvedMode = "deep-research";
696
+ } else if (totalScore <= 4) {
697
+ resolvedMode = "search";
698
+ } else {
699
+ resolvedMode = "research";
700
+ }
701
+ const channelPriors = rankChannelsByExpectedPrior(facetProbabilities, contract);
702
+ return {
703
+ requestedMode,
704
+ resolvedMode,
705
+ decisionEvaluated,
706
+ hardEscalated,
707
+ rubricBreakdown: {
708
+ readingDepth: Number(readingDepth.toFixed(2)),
709
+ sourceDiversity: Number(sourceDiversity.toFixed(2)),
710
+ decomposition: Number(decomposition.toFixed(2)),
711
+ verificationStakes: Number(verificationStakes.toFixed(2)),
712
+ contractScore,
713
+ totalScore
714
+ },
715
+ facetProbabilities,
716
+ channelPriors
717
+ };
718
+ }
719
+ async function evaluateAttributeCoverageWithDecision(params) {
720
+ const { objective, targetCheckList, receiptsText, decision } = params;
721
+ if (targetCheckList.length === 0) {
722
+ return { satisfied: [], missing: [] };
723
+ }
724
+ try {
725
+ const questions = targetCheckList.map((attr, idx) => ({
726
+ id: `attr_${idx}`,
727
+ type: "noul",
728
+ criteria: `Does the collected evidence contain concrete, substantive information addressing "${attr}" for the research objective "${objective}"?`
729
+ }));
730
+ const res = await decision({
731
+ context: `Research Objective: "${objective}"
732
+
733
+ Collected Citation Receipts:
734
+ ${receiptsText}`,
735
+ questions
736
+ });
737
+ const satisfied = [];
738
+ const missing = [];
739
+ targetCheckList.forEach((attr, idx) => {
740
+ const ans = res.answers[`attr_${idx}`];
741
+ if (ans && ans.type === "noul" && ans.probability >= 0.55) {
742
+ satisfied.push(attr);
743
+ } else {
744
+ missing.push(attr);
745
+ }
746
+ });
747
+ return { satisfied, missing };
748
+ } catch (e) {
749
+ console.warn("[DecisionRouter] Attribute coverage noul check failed:", e?.message || e);
750
+ return null;
751
+ }
752
+ }
753
+
754
+ // src/agent/channelScheduler.ts
755
+ function classifyChannelStatus(itemsAdded, substantiveBytes, error) {
756
+ if (error) return "error";
757
+ if (itemsAdded <= 0) return "empty";
758
+ if (itemsAdded >= 2 || substantiveBytes >= 450) return "ok";
759
+ return "weak";
760
+ }
761
+ async function runConcurrentRefillScheduler(params) {
762
+ const { channelQueue, maxChannels, signal, executeChannel } = params;
763
+ const effectiveMax = Math.max(1, maxChannels);
764
+ const concurrency = Math.max(1, Math.min(params.concurrency ?? 2, effectiveMax));
765
+ const queue = [...channelQueue];
766
+ const traces = [];
767
+ const inFlightControllers = /* @__PURE__ */ new Set();
768
+ let okChannels = 0;
769
+ let stopped = false;
770
+ const abortAllInFlight = () => {
771
+ stopped = true;
772
+ for (const ctrl of inFlightControllers) {
773
+ try {
774
+ ctrl.abort();
775
+ } catch {
776
+ }
777
+ }
778
+ inFlightControllers.clear();
779
+ };
780
+ if (signal) {
781
+ if (signal.aborted) {
782
+ return { traces: [], okChannels: 0 };
783
+ }
784
+ signal.addEventListener("abort", abortAllInFlight, { once: true });
785
+ }
786
+ return new Promise((resolve) => {
787
+ let settled = false;
788
+ const finishIfDone = () => {
789
+ if (settled) return;
790
+ if (stopped || okChannels >= effectiveMax || queue.length === 0 && inFlightControllers.size === 0) {
791
+ settled = true;
792
+ if (signal) {
793
+ signal.removeEventListener("abort", onExternalAbort);
794
+ }
795
+ abortAllInFlight();
796
+ resolve({ traces, okChannels });
797
+ }
798
+ };
799
+ const onExternalAbort = () => {
800
+ abortAllInFlight();
801
+ finishIfDone();
802
+ };
803
+ const scheduleNext = () => {
804
+ if (settled || stopped || signal?.aborted) {
805
+ finishIfDone();
806
+ return;
807
+ }
808
+ const remainingNeeded = effectiveMax - okChannels;
809
+ const targetInFlight = Math.min(concurrency, remainingNeeded);
810
+ while (!stopped && inFlightControllers.size < targetInFlight && queue.length > 0) {
811
+ const next = queue.shift();
812
+ if (!next) break;
813
+ const channelController = new AbortController();
814
+ inFlightControllers.add(channelController);
815
+ const startMs = Date.now();
816
+ executeChannel(next.channel, next.score, channelController.signal).then((trace) => {
817
+ inFlightControllers.delete(channelController);
818
+ if (settled || stopped) {
819
+ finishIfDone();
820
+ return;
821
+ }
822
+ traces.push(trace);
823
+ if (trace.status === "ok") {
824
+ okChannels += 1;
825
+ if (okChannels >= effectiveMax) {
826
+ abortAllInFlight();
827
+ finishIfDone();
828
+ return;
829
+ }
830
+ }
831
+ scheduleNext();
832
+ }).catch((err) => {
833
+ inFlightControllers.delete(channelController);
834
+ if (settled || stopped) {
835
+ finishIfDone();
836
+ return;
837
+ }
838
+ traces.push({
839
+ channel: next.channel,
840
+ status: "error",
841
+ priorScore: next.score,
842
+ itemsAdded: 0,
843
+ durationMs: Date.now() - startMs,
844
+ errorMessage: err?.message || String(err)
845
+ });
846
+ scheduleNext();
847
+ });
848
+ }
849
+ finishIfDone();
850
+ };
851
+ scheduleNext();
852
+ });
853
+ }
854
+ function describeZodSchemaKeys(schema) {
855
+ if (!schema) return void 0;
856
+ const def = schema?._def;
857
+ if (def?.typeName === "ZodObject" && typeof def.shape === "function") {
858
+ const shapeObj = def.shape();
859
+ const keys = Object.keys(shapeObj);
860
+ if (keys.length > 0) {
861
+ return `JSON object with required top-level keys: ${keys.map((k) => `"${k}"`).join(", ")}`;
862
+ }
863
+ }
864
+ return void 0;
865
+ }
866
+ function resolveResearchProfile(contract) {
867
+ if (contract.profile && contract.profile !== "auto") {
868
+ return contract.profile;
869
+ }
870
+ const text = `${contract.objective} ${contract.context?.positioning || ""}`.toLowerCase();
871
+ if (/\b(hackernews|reddit|social|pulse|trend|last 30 days|community sentiment|github stars)\b/.test(text)) {
872
+ return "social_pulse";
873
+ }
874
+ if (/\b(literature review|academic|peer-reviewed|openalex|arxiv|citation|paper|cs2023)\b/.test(text)) {
875
+ return "academic";
876
+ }
877
+ if (/\b(phet|oer|openstax|simulation|worksheet|unplugged)\b/.test(text)) {
878
+ return "curriculum_oer";
879
+ }
880
+ if (contract.context?.hardwarePlatform || contract.context?.softwareEnv || /\b(pinout|datasheet|gpio|i2c|pwm|api|sdk|compiler|microcontroller|arduino|esp32|roblox|swift|python)\b/.test(text)) {
881
+ return "technical";
882
+ }
883
+ return "general";
884
+ }
885
+ function isSemanticRankedHit(hit) {
886
+ return hit.engine === "exa" || hit.engine === "tavily" || hit.engine === "academic" || typeof hit.score === "number" && hit.score > 0;
887
+ }
888
+ function computeNativeHitScore(hit, defaultSemantic = 8, defaultLexical = 6) {
889
+ if (typeof hit.score === "number" && hit.score > 0) {
890
+ const scaled = hit.score <= 1 ? hit.score * 10 : hit.score;
891
+ return Math.max(6, Math.min(10, Math.round(scaled)));
892
+ }
893
+ return isSemanticRankedHit(hit) ? defaultSemantic : defaultLexical;
894
+ }
895
+ var ResearchSubAgent = class {
896
+ constructor(config = {}) {
897
+ this.config = config;
898
+ this.searchEngine = new MultiSourceSearchEngine({
899
+ apiKeys: config.apiKeys,
900
+ allowEnvFallback: config.allowEnvFallback,
901
+ customAdapter: config.customSearchAdapter
902
+ });
903
+ this.webScraper = new WebScraper({
904
+ crawl4aiHost: config.crawl4aiHost,
905
+ jinaKey: config.apiKeys?.jina,
906
+ brightDataKey: config.apiKeys?.brightdata || config.apiKeys?.brightData,
907
+ allowEnvFallback: config.allowEnvFallback,
908
+ customAdapter: config.customCrawlerAdapter
909
+ });
910
+ this.academicEngine = new AcademicSearchEngine({
911
+ apiKey: config.apiKeys?.semanticScholar,
912
+ allowEnvFallback: config.allowEnvFallback,
913
+ customAdapter: config.customAcademicSearchAdapter
914
+ });
915
+ this.openAlexClient = new OpenAlexClient();
916
+ this.socialPulseHarvester = new SocialPulseHarvester(this.searchEngine);
917
+ this.stemResearcher = new StemResourceResearcher();
918
+ this.youtubeService = new YouTubeIngestionService();
919
+ this.healthAuditor = new HealthAuditor();
920
+ this.evidenceScorer = new EvidenceScorer();
921
+ this.claimVerifier = new ClaimVerifier();
922
+ this.provenanceTracker = new ProvenanceTracker();
923
+ }
924
+ searchEngine;
925
+ webScraper;
926
+ academicEngine;
927
+ openAlexClient;
928
+ socialPulseHarvester;
929
+ stemResearcher;
930
+ youtubeService;
931
+ healthAuditor;
932
+ evidenceScorer;
933
+ claimVerifier;
934
+ provenanceTracker;
935
+ /**
936
+ * Executes a complete Plan-and-Execute research campaign governed by `contract`.
937
+ */
938
+ async run(contract, options) {
939
+ const llm = options?.llm ?? this.config.llm;
940
+ const decision = options?.decision ?? this.config.decision;
941
+ const modeTrace = await classifyModeAndPrior(contract, decision);
942
+ const resolvedMode = modeTrace.resolvedMode;
943
+ const modePreset = RESEARCH_MODE_PRESETS[resolvedMode];
944
+ const resolvedProfile = resolveResearchProfile(contract);
945
+ const profilePreset = RESEARCH_PROFILE_PRESETS[resolvedProfile];
946
+ const ctx = contract.context ?? this.config.defaultCourseContext;
947
+ const domain = classifyTechnicalDomain(contract.objective, void 0, ctx).domain;
948
+ const timeoutMs = Math.max(1e3, contract.budget?.timeoutMs ?? modePreset.timeoutMs);
949
+ const maxChannels = Math.max(1, Math.min(5, contract.budget?.maxChannels ?? modePreset.maxChannels));
950
+ const channelConcurrency = Math.max(
951
+ 1,
952
+ Math.min(3, contract.budget?.channelConcurrency ?? modePreset.channelConcurrency)
953
+ );
954
+ const maxRounds = resolvedMode === "search" ? 1 : Math.max(1, Math.min(5, contract.budget?.maxRounds ?? modePreset.maxRounds));
955
+ const maxQueriesPerRound = Math.max(
956
+ 1,
957
+ Math.min(6, contract.budget?.maxQueriesPerRound ?? modePreset.maxQueriesPerRound)
958
+ );
959
+ const maxScrapePerRound = resolvedMode === "search" ? contract.budget?.maxScrapePerRound ?? 0 : Math.max(0, Math.min(6, contract.budget?.maxScrapePerRound ?? modePreset.maxScrapePerRound));
960
+ const minSources = contract.acceptanceCriteria?.minSources ?? (resolvedMode === "search" ? 1 : 2);
961
+ const minRelevanceScore = contract.acceptanceCriteria?.minRelevanceScore ?? 6;
962
+ const recencyDays = contract.acceptanceCriteria?.recencyDays ?? 30;
963
+ const shouldVerifyClaims = contract.acceptanceCriteria?.verifyClaims ?? modePreset.verifyClaims;
964
+ const harvestBudgetMs = resolvedMode === "search" ? timeoutMs : Math.floor(timeoutMs * 0.75);
965
+ const harvestAbortController = new AbortController();
966
+ const harvestTimer = setTimeout(() => {
967
+ harvestAbortController.abort();
968
+ }, harvestBudgetMs);
969
+ if (contract.signal) {
970
+ if (contract.signal.aborted) {
971
+ harvestAbortController.abort();
972
+ } else {
973
+ contract.signal.addEventListener("abort", () => harvestAbortController.abort(), { once: true });
974
+ }
975
+ }
976
+ const ledger = new EvidenceLedger();
977
+ const executedQueries = /* @__PURE__ */ new Set();
978
+ const scrapedUrls = /* @__PURE__ */ new Set();
979
+ const roundTraces = [];
980
+ const allChannelTraces = [];
981
+ let currentMissingGaps = [
982
+ ...contract.acceptanceCriteria?.requiredAttributes || [],
983
+ ...contract.requiredSections || []
984
+ ];
985
+ try {
986
+ for (let round = 1; round <= maxRounds; round++) {
987
+ if (harvestAbortController.signal.aborted) {
988
+ break;
989
+ }
990
+ const beforeReceiptCount = ledger.getReceipts().length;
991
+ const plannedQueries = await this.planQueriesForRound({
992
+ round,
993
+ contract,
994
+ mode: resolvedMode,
995
+ profile: resolvedProfile,
996
+ missingGaps: currentMissingGaps,
997
+ receipts: ledger.getReceipts(),
998
+ executedQueries,
999
+ maxQueries: maxQueriesPerRound,
1000
+ llm: resolvedMode === "search" ? void 0 : llm
1001
+ });
1002
+ for (const q of plannedQueries) {
1003
+ executedQueries.add(q.toLowerCase());
1004
+ }
1005
+ const roundChannelQueue = this.buildRoundChannelQueue(
1006
+ round,
1007
+ modeTrace.channelPriors,
1008
+ profilePreset,
1009
+ contract
1010
+ );
1011
+ const schedulerResult = await runConcurrentRefillScheduler({
1012
+ channelQueue: roundChannelQueue,
1013
+ maxChannels,
1014
+ concurrency: channelConcurrency,
1015
+ signal: harvestAbortController.signal,
1016
+ executeChannel: (channel, priorScore, channelSignal) => this.executeSingleChannel({
1017
+ channel,
1018
+ priorScore,
1019
+ queries: plannedQueries,
1020
+ contract,
1021
+ domain,
1022
+ recencyDays,
1023
+ maxScrapePerRound,
1024
+ scrapedUrls,
1025
+ ledger,
1026
+ signal: channelSignal
1027
+ })
1028
+ });
1029
+ allChannelTraces.push(...schedulerResult.traces);
1030
+ const afterReceiptCount = ledger.getReceipts().length;
1031
+ const newReceiptsAdded = afterReceiptCount - beforeReceiptCount;
1032
+ const evaluation = await this.evaluateRoundGaps({
1033
+ contract,
1034
+ mode: resolvedMode,
1035
+ ledger,
1036
+ minSources,
1037
+ minRelevanceScore,
1038
+ decision: resolvedMode === "search" ? void 0 : decision,
1039
+ llm: resolvedMode === "search" ? void 0 : llm
1040
+ });
1041
+ currentMissingGaps = evaluation.missingGaps;
1042
+ roundTraces.push({
1043
+ round,
1044
+ plannedQueries,
1045
+ newReceiptsAdded,
1046
+ satisfiedAttributes: evaluation.satisfiedAttributes,
1047
+ missingGaps: evaluation.missingGaps,
1048
+ channelTraces: schedulerResult.traces
1049
+ });
1050
+ if (evaluation.missingGaps.length === 0) {
1051
+ break;
1052
+ }
1053
+ }
1054
+ } finally {
1055
+ clearTimeout(harvestTimer);
1056
+ }
1057
+ const allItems = ledger.getItems();
1058
+ const approvedItems = ledger.getApprovedItems(minRelevanceScore);
1059
+ const provenanceSidecar = this.provenanceTracker.generateSidecar(
1060
+ contract.objective,
1061
+ ledger.toProvenanceRecords(domain)
1062
+ );
1063
+ if (allItems.length === 0) {
1064
+ const failMsg = `Research Sub-Agent failed to harvest any verified sources for objective: "${contract.objective}".`;
1065
+ return {
1066
+ status: "failed",
1067
+ objective: contract.objective,
1068
+ mode: resolvedMode,
1069
+ profile: resolvedProfile,
1070
+ roundsExecuted: roundTraces.length,
1071
+ data: null,
1072
+ markdownReport: `# \u274C Research Harvest Failed: ${contract.objective}
1073
+
1074
+ > ${failMsg}
1075
+
1076
+ ### Unresolved Gaps
1077
+ ${currentMissingGaps.length > 0 ? currentMissingGaps.map((g) => `- ${g}`).join("\n") : "- No reachable sources."}`,
1078
+ tier1Summary: failMsg,
1079
+ tier2TechnicalDigest: failMsg,
1080
+ ledgerItems: [],
1081
+ receipts: [],
1082
+ validCitationIds: [],
1083
+ invalidCitationIds: [],
1084
+ missingGaps: currentMissingGaps.length > 0 ? currentMissingGaps : ["minSources not met (0 harvested)"],
1085
+ roundTraces,
1086
+ modeClassificationTrace: modeTrace,
1087
+ channelTraces: allChannelTraces,
1088
+ provenanceMd: provenanceSidecar.provenanceMd
1089
+ };
1090
+ }
1091
+ if (resolvedMode === "search") {
1092
+ const receipts = ledger.getReceipts();
1093
+ const markdownReport = this.buildDeterministicMarkdownReport(
1094
+ contract.objective,
1095
+ resolvedProfile,
1096
+ allItems,
1097
+ contract.requiredSections
1098
+ );
1099
+ const tier1Summary = allItems.slice(0, 3).map((i) => `[${i.id}] ${i.title}: ${i.keyExcerpts[0] || ""}`).join(" ");
1100
+ const tier2TechnicalDigest = allItems.slice(0, 6).map((i) => `- **[${i.id}] ${i.title}** (${i.url}): ${i.keyExcerpts.slice(0, 2).join(" ")}`).join("\n");
1101
+ return {
1102
+ status: approvedItems.length >= minSources ? "success" : "partial",
1103
+ objective: contract.objective,
1104
+ mode: resolvedMode,
1105
+ profile: resolvedProfile,
1106
+ roundsExecuted: roundTraces.length,
1107
+ data: {
1108
+ objective: contract.objective,
1109
+ mode: resolvedMode,
1110
+ sources: receipts
1111
+ },
1112
+ markdownReport,
1113
+ tier1Summary,
1114
+ tier2TechnicalDigest,
1115
+ ledgerItems: allItems,
1116
+ receipts,
1117
+ validCitationIds: allItems.map((i) => i.id),
1118
+ invalidCitationIds: [],
1119
+ missingGaps: currentMissingGaps,
1120
+ roundTraces,
1121
+ modeClassificationTrace: modeTrace,
1122
+ channelTraces: allChannelTraces,
1123
+ provenanceMd: provenanceSidecar.provenanceMd
1124
+ };
1125
+ }
1126
+ return this.synthesizeAndVerify({
1127
+ contract,
1128
+ mode: resolvedMode,
1129
+ profile: resolvedProfile,
1130
+ domain,
1131
+ ledger,
1132
+ approvedCount: approvedItems.length,
1133
+ minSources,
1134
+ shouldVerifyClaims,
1135
+ missingGaps: currentMissingGaps,
1136
+ roundTraces,
1137
+ modeClassificationTrace: modeTrace,
1138
+ channelTraces: allChannelTraces,
1139
+ provenanceMd: provenanceSidecar.provenanceMd,
1140
+ llm,
1141
+ decision
1142
+ });
1143
+ }
1144
+ /**
1145
+ * Builds the Prior-sorted channel queue for a specific round.
1146
+ */
1147
+ buildRoundChannelQueue(round, channelPriors, profilePreset, contract) {
1148
+ if (contract.preferredChannels && contract.preferredChannels.length > 0) {
1149
+ const preferredSet = new Set(contract.preferredChannels);
1150
+ const preferred = channelPriors.filter((c) => preferredSet.has(c.channel));
1151
+ const others = channelPriors.filter((c) => !preferredSet.has(c.channel));
1152
+ if (this.config.allowEnvFallback === false) {
1153
+ return preferred;
1154
+ }
1155
+ return [...preferred, ...others];
1156
+ }
1157
+ if (contract.profile && contract.profile !== "auto") {
1158
+ const filtered = channelPriors.filter((c) => {
1159
+ if (c.channel === "web_docs") return profilePreset.enableWeb;
1160
+ if (c.channel === "academic") return profilePreset.enableAcademic;
1161
+ if (c.channel === "social_pulse") return profilePreset.enableSocialPulse;
1162
+ if (c.channel === "stem_oer") return profilePreset.enableStemOer;
1163
+ return false;
1164
+ });
1165
+ if (filtered.length > 0) {
1166
+ return filtered;
1167
+ }
1168
+ }
1169
+ if (this.config.allowEnvFallback === false) {
1170
+ const isolated = channelPriors.filter((c) => {
1171
+ if (c.channel === "web_docs") return Boolean(this.config.customSearchAdapter || this.config.apiKeys);
1172
+ if (c.channel === "academic") return Boolean(this.config.customAcademicSearchAdapter || this.config.apiKeys?.semanticScholar);
1173
+ return false;
1174
+ });
1175
+ if (isolated.length > 0) {
1176
+ return isolated;
1177
+ }
1178
+ }
1179
+ if (round > 1) {
1180
+ return [...channelPriors].sort((a, b) => {
1181
+ const boostA = a.channel === "web_docs" ? 0.3 : a.channel === "academic" ? 0.2 : 0;
1182
+ const boostB = b.channel === "web_docs" ? 0.3 : b.channel === "academic" ? 0.2 : 0;
1183
+ return b.score + boostB - (a.score + boostA);
1184
+ });
1185
+ }
1186
+ return [...channelPriors];
1187
+ }
1188
+ /**
1189
+ * Executes a single source channel and classifies its outcome (`'ok' | 'weak' | 'empty' | 'error'`)
1190
+ * using Non-Redundant Evidence Gating (ADR-0019).
1191
+ */
1192
+ async executeSingleChannel(params) {
1193
+ const {
1194
+ channel,
1195
+ priorScore,
1196
+ queries,
1197
+ contract,
1198
+ domain,
1199
+ recencyDays,
1200
+ maxScrapePerRound,
1201
+ scrapedUrls,
1202
+ ledger,
1203
+ signal
1204
+ } = params;
1205
+ const startMs = Date.now();
1206
+ const beforeItems = ledger.getItems().length;
1207
+ let substantiveBytes = 0;
1208
+ try {
1209
+ if (signal.aborted) {
1210
+ return {
1211
+ channel,
1212
+ status: "empty",
1213
+ priorScore,
1214
+ itemsAdded: 0,
1215
+ durationMs: 0
1216
+ };
1217
+ }
1218
+ if (channel === "web_docs") {
1219
+ const candidateHits = [];
1220
+ for (const q of queries) {
1221
+ if (signal.aborted) break;
1222
+ try {
1223
+ const hits = await this.searchEngine.search(q, { limit: 3 });
1224
+ for (const h of hits) {
1225
+ if (!isCommercialOrNoise({ url: h.url, title: h.title, snippet: h.content })) {
1226
+ if (!candidateHits.some((existing) => existing.url === h.url)) {
1227
+ candidateHits.push(h);
1228
+ }
1229
+ }
1230
+ }
1231
+ } catch {
1232
+ }
1233
+ }
1234
+ const urlsToScrape = maxScrapePerRound > 0 ? candidateHits.filter((h) => !scrapedUrls.has(h.url)).slice(0, maxScrapePerRound) : [];
1235
+ if (urlsToScrape.length > 0 && !signal.aborted) {
1236
+ await Promise.allSettled(
1237
+ urlsToScrape.map(async (hit) => {
1238
+ if (signal.aborted) return;
1239
+ scrapedUrls.add(hit.url);
1240
+ try {
1241
+ const doc = await this.webScraper.scrapeUrl(hit.url);
1242
+ const health = this.healthAuditor.auditDocument(doc);
1243
+ if (health.passed && doc.markdownContent.trim().length > 80) {
1244
+ if (isSemanticRankedHit(hit)) {
1245
+ const nativeScore = computeNativeHitScore(hit, 8, 7);
1246
+ const takeaways = extractTopSentences(doc.markdownContent, contract.objective, 3);
1247
+ const receipt = ledger.addScrapedDocument(doc, nativeScore, takeaways);
1248
+ const added = ledger.getById(receipt.id);
1249
+ substantiveBytes += added?.rawByteSize || doc.byteSize || 1e3;
1250
+ return;
1251
+ } else {
1252
+ const scored = this.evidenceScorer.scoreDocument(doc, domain, contract.objective);
1253
+ const receipt = ledger.addScrapedDocument(doc, scored.score, scored.keyTakeaways);
1254
+ const added = ledger.getById(receipt.id);
1255
+ substantiveBytes += added?.rawByteSize || doc.byteSize || 800;
1256
+ return;
1257
+ }
1258
+ }
1259
+ } catch {
1260
+ }
1261
+ if (hit.content && hit.content.trim().length > 30) {
1262
+ const hitScore = computeNativeHitScore(hit, 7, 6);
1263
+ ledger.addSearchHit(hit, hitScore);
1264
+ substantiveBytes += Buffer.byteLength(hit.content, "utf-8");
1265
+ }
1266
+ })
1267
+ );
1268
+ }
1269
+ const remainingHits = maxScrapePerRound > 0 ? candidateHits.slice(maxScrapePerRound, maxScrapePerRound + 3) : candidateHits.slice(0, 5);
1270
+ for (const hit of remainingHits) {
1271
+ if (hit.content && hit.content.trim().length > 35) {
1272
+ const hitScore = computeNativeHitScore(hit, 7, 6);
1273
+ ledger.addSearchHit(hit, hitScore);
1274
+ substantiveBytes += Math.max(
1275
+ maxScrapePerRound === 0 ? 500 : 100,
1276
+ Buffer.byteLength(hit.content, "utf-8")
1277
+ );
1278
+ }
1279
+ }
1280
+ } else if (channel === "academic") {
1281
+ const primaryQuery = queries[0] || contract.objective;
1282
+ const [s2Papers, oaPapers] = await Promise.all([
1283
+ this.academicEngine.searchPapers(primaryQuery, { limit: 3 }).catch(() => []),
1284
+ this.openAlexClient.searchWorks(primaryQuery, { limit: 3 }).catch(() => [])
1285
+ ]);
1286
+ for (const p of [...s2Papers, ...oaPapers].slice(0, 5)) {
1287
+ const receipt = ledger.addAcademicPaper(p);
1288
+ const item = ledger.getById(receipt.id);
1289
+ substantiveBytes += Math.max(850, item?.rawByteSize || 0);
1290
+ }
1291
+ } else if (channel === "social_pulse") {
1292
+ const pulseReport = await this.socialPulseHarvester.harvest(contract.objective, {
1293
+ recencyDays,
1294
+ limitPerPlatform: 3
1295
+ });
1296
+ for (const item of pulseReport.items.slice(0, 5)) {
1297
+ ledger.addSocialPulseItem(item);
1298
+ substantiveBytes += Math.max(450, Buffer.byteLength(item.snippet || "", "utf-8"));
1299
+ }
1300
+ } else if (channel === "stem_oer") {
1301
+ const oerCatalog = await this.stemResearcher.findResources(contract.objective, {
1302
+ limit: 4
1303
+ });
1304
+ for (const res of oerCatalog.resources.slice(0, 4)) {
1305
+ ledger.addStemResource({
1306
+ title: res.title,
1307
+ url: res.url,
1308
+ description: res.description,
1309
+ provider: res.provider,
1310
+ license: res.license?.type
1311
+ });
1312
+ substantiveBytes += Math.max(500, Buffer.byteLength(res.description || "", "utf-8"));
1313
+ }
1314
+ } else if (channel === "video_media") {
1315
+ const videoQuery = `${queries[0] || contract.objective} site:youtube.com tutorial lecture`;
1316
+ const hits = await this.searchEngine.search(videoQuery, { limit: 3 });
1317
+ for (const h of hits.slice(0, 3)) {
1318
+ if (signal.aborted) break;
1319
+ if (/youtube\.com\/watch|youtu\.be\//i.test(h.url)) {
1320
+ try {
1321
+ const transcript = await this.youtubeService.fetchTranscript(h.url, ["vi", "en"]);
1322
+ if (transcript && transcript.stitchedMarkdown && transcript.stitchedMarkdown.length > 60) {
1323
+ ledger.addScrapedDocument(
1324
+ {
1325
+ url: h.url,
1326
+ title: transcript.title || h.title || "YouTube Educational Video",
1327
+ markdownContent: transcript.stitchedMarkdown,
1328
+ byteSize: Buffer.byteLength(transcript.stitchedMarkdown, "utf-8"),
1329
+ extractedCodeSnippets: [],
1330
+ tablesCount: 0,
1331
+ fetchProvider: "youtube",
1332
+ keyExcerpts: [transcript.stitchedMarkdown.slice(0, 450)]
1333
+ },
1334
+ 8
1335
+ );
1336
+ substantiveBytes += Buffer.byteLength(transcript.stitchedMarkdown, "utf-8");
1337
+ continue;
1338
+ }
1339
+ } catch {
1340
+ }
1341
+ }
1342
+ if (h.content && h.content.trim().length > 30) {
1343
+ ledger.addSearchHit(h, 6);
1344
+ substantiveBytes += Buffer.byteLength(h.content, "utf-8");
1345
+ }
1346
+ }
1347
+ }
1348
+ const itemsAdded = Math.max(0, ledger.getItems().length - beforeItems);
1349
+ const status = classifyChannelStatus(itemsAdded, substantiveBytes);
1350
+ return {
1351
+ channel,
1352
+ status,
1353
+ priorScore,
1354
+ itemsAdded,
1355
+ durationMs: Date.now() - startMs
1356
+ };
1357
+ } catch (err) {
1358
+ const itemsAdded = Math.max(0, ledger.getItems().length - beforeItems);
1359
+ return {
1360
+ channel,
1361
+ status: itemsAdded > 0 ? classifyChannelStatus(itemsAdded, substantiveBytes) : "error",
1362
+ priorScore,
1363
+ itemsAdded,
1364
+ durationMs: Date.now() - startMs,
1365
+ errorMessage: err?.message || String(err)
1366
+ };
1367
+ }
1368
+ }
1369
+ /**
1370
+ * Plans targeted search queries for Round 1 (initial coverage) or Round > 1 (surgical gap filling).
1371
+ */
1372
+ async planQueriesForRound(params) {
1373
+ const { round, contract, mode, profile, missingGaps, receipts, executedQueries, maxQueries, llm } = params;
1374
+ const ctx = contract.context ?? this.config.defaultCourseContext;
1375
+ const toolAnchor = [ctx?.hardwarePlatform, ctx?.softwareEnv].filter(Boolean).join(" ").trim();
1376
+ const baseTopic = toolAnchor ? `${toolAnchor} ${contract.objective}` : contract.objective;
1377
+ if (mode === "search") {
1378
+ return [baseTopic.trim()].slice(0, maxQueries);
1379
+ }
1380
+ if (llm) {
1381
+ try {
1382
+ const promptLines = [
1383
+ `You are a Principal Research Planner for an autonomous Plan-and-Execute Research Sub-Agent.`,
1384
+ `Objective: "${contract.objective}"`,
1385
+ `Mode: ${mode} | Profile: ${profile} | Round: ${round}`,
1386
+ toolAnchor ? `Hardware/Software Context: ${toolAnchor}` : "",
1387
+ ctx?.ageBand ? `Target Learner Age Band: ${ctx.ageBand[0]}-${ctx.ageBand[1]}` : "",
1388
+ contract.requiredSections?.length ? `Required Sections: ${contract.requiredSections.join(", ")}` : "",
1389
+ contract.acceptanceCriteria?.requiredAttributes?.length ? `Required Attributes: ${contract.acceptanceCriteria.requiredAttributes.join(", ")}` : "",
1390
+ contract.acceptanceCriteria?.requireCodeExamples ? `Must find verified code examples.` : "",
1391
+ contract.acceptanceCriteria?.requireTables ? `Must find specification/pinout tables.` : ""
1392
+ ];
1393
+ if (round > 1 && receipts.length > 0) {
1394
+ promptLines.push(
1395
+ `
1396
+ Compact Receipts Collected So Far (${receipts.length} sources):`,
1397
+ ...receipts.slice(0, 8).map(
1398
+ (r) => `- [${r.id}] ${r.title} (score:${r.relevanceScore}, code:${r.codeBlockCount}, tables:${r.tableCount}): ${r.briefExcerpt.slice(0, 140)}`
1399
+ ),
1400
+ `
1401
+ Remaining Unresolved Gaps to Fill in Round ${round}:`,
1402
+ ...missingGaps.map((g) => `- ${g}`),
1403
+ `
1404
+ Previously Executed Queries (DO NOT REPEAT): ${Array.from(executedQueries).join(" | ")}`
1405
+ );
1406
+ }
1407
+ promptLines.push(
1408
+ `
1409
+ Generate ${maxQueries} high-precision search queries to fulfill ${round === 1 ? "the objective and required attributes" : "ONLY the remaining unresolved gaps"}.`,
1410
+ `Return ONLY a valid JSON array of query strings: ["query 1", "query 2"]`
1411
+ );
1412
+ const raw = await llm(promptLines.filter(Boolean).join("\n"), {
1413
+ system: "Return strictly a valid JSON array of search query strings.",
1414
+ temperature: 0.2,
1415
+ jsonMode: true
1416
+ });
1417
+ const match = raw.match(/\[[\s\S]*\]/);
1418
+ if (match) {
1419
+ const parsed = JSON.parse(match[0]);
1420
+ if (Array.isArray(parsed)) {
1421
+ const candidateQueries = parsed.map((q) => String(q).trim()).filter((q) => q.length > 3 && !executedQueries.has(q.toLowerCase())).slice(0, maxQueries);
1422
+ if (candidateQueries.length > 0) {
1423
+ return candidateQueries;
1424
+ }
1425
+ }
1426
+ }
1427
+ } catch (e) {
1428
+ console.warn(`[ResearchSubAgent] Round ${round} LLM query planning fallback:`, e?.message || e);
1429
+ }
1430
+ }
1431
+ const fallbackQueries = [];
1432
+ if (round === 1) {
1433
+ fallbackQueries.push(
1434
+ `${baseTopic} official documentation architecture specification`.trim(),
1435
+ `${baseTopic} practical examples tutorial implementation`.trim(),
1436
+ `${baseTopic} common pitfalls debugging troubleshooting bottlenecks`.trim()
1437
+ );
1438
+ if (contract.acceptanceCriteria?.requireTables) {
1439
+ fallbackQueries.push(`${baseTopic} pinout specification comparison table`.trim());
1440
+ }
1441
+ } else {
1442
+ for (const gap of missingGaps) {
1443
+ const candidate = `${baseTopic} ${gap}`.trim();
1444
+ if (!executedQueries.has(candidate.toLowerCase())) {
1445
+ fallbackQueries.push(candidate);
1446
+ }
1447
+ }
1448
+ if (fallbackQueries.length === 0) {
1449
+ fallbackQueries.push(`${baseTopic} advanced reference guide code examples`.trim());
1450
+ }
1451
+ }
1452
+ return fallbackQueries.filter((q) => !executedQueries.has(q.toLowerCase())).slice(0, maxQueries);
1453
+ }
1454
+ /**
1455
+ * Evaluates whether the current `EvidenceLedger` satisfies `acceptanceCriteria`,
1456
+ * `requiredAttributes`, and `requiredSections`.
1457
+ * Prioritizes Decision Model (`noul`) over Generative LLM when available (ADR-0019).
1458
+ */
1459
+ async evaluateRoundGaps(params) {
1460
+ const { contract, ledger, minSources, minRelevanceScore, decision, llm } = params;
1461
+ const missingGaps = [];
1462
+ const satisfiedAttributes = [];
1463
+ const approved = ledger.getApprovedItems(minRelevanceScore);
1464
+ if (approved.length < minSources) {
1465
+ missingGaps.push(`Need at least ${minSources} verified sources with score >= ${minRelevanceScore} (currently ${approved.length})`);
1466
+ } else {
1467
+ satisfiedAttributes.push(`minSources(${approved.length}/${minSources})`);
1468
+ }
1469
+ if (contract.acceptanceCriteria?.minPeerReviewedSources) {
1470
+ const academicCount = ledger.getItems().filter((i) => i.sourceType === "academic").length;
1471
+ if (academicCount < contract.acceptanceCriteria.minPeerReviewedSources) {
1472
+ missingGaps.push(
1473
+ `Need at least ${contract.acceptanceCriteria.minPeerReviewedSources} peer-reviewed academic sources (currently ${academicCount})`
1474
+ );
1475
+ } else {
1476
+ satisfiedAttributes.push(`peerReviewedSources(${academicCount}/${contract.acceptanceCriteria.minPeerReviewedSources})`);
1477
+ }
1478
+ }
1479
+ if (contract.acceptanceCriteria?.requireCodeExamples && ledger.getTotalCodeBlocks() === 0) {
1480
+ missingGaps.push("Missing verified code examples / syntax snippets");
1481
+ } else if (contract.acceptanceCriteria?.requireCodeExamples) {
1482
+ satisfiedAttributes.push(`codeExamples(${ledger.getTotalCodeBlocks()})`);
1483
+ }
1484
+ if (contract.acceptanceCriteria?.requireTables && ledger.getTotalTables() === 0) {
1485
+ missingGaps.push("Missing specification or pinout markdown tables");
1486
+ } else if (contract.acceptanceCriteria?.requireTables) {
1487
+ satisfiedAttributes.push(`tables(${ledger.getTotalTables()})`);
1488
+ }
1489
+ const targetCheckList = [
1490
+ ...contract.acceptanceCriteria?.requiredAttributes || [],
1491
+ ...contract.requiredSections || []
1492
+ ];
1493
+ if (targetCheckList.length > 0) {
1494
+ const receipts = ledger.getReceipts();
1495
+ if (receipts.length === 0) {
1496
+ missingGaps.push(...targetCheckList);
1497
+ } else {
1498
+ const receiptsText = receipts.map((r) => `- [${r.id}] ${r.title} (headings: ${r.headings.join(", ")}): ${r.briefExcerpt}`).join("\n");
1499
+ if (decision) {
1500
+ const decEval = await evaluateAttributeCoverageWithDecision({
1501
+ objective: contract.objective,
1502
+ targetCheckList,
1503
+ receiptsText,
1504
+ decision
1505
+ });
1506
+ if (decEval) {
1507
+ satisfiedAttributes.push(...decEval.satisfied);
1508
+ missingGaps.push(...decEval.missing);
1509
+ return { satisfiedAttributes, missingGaps };
1510
+ }
1511
+ }
1512
+ if (llm) {
1513
+ try {
1514
+ const prompt = [
1515
+ `Evaluate which of the required attributes/sections are covered by the collected Citation Receipts for "${contract.objective}".`,
1516
+ `Required Items: ${JSON.stringify(targetCheckList)}`,
1517
+ `Collected Citation Receipts:
1518
+ ${receiptsText}`,
1519
+ `Return ONLY a JSON object: {"satisfied": ["item1"], "missing": ["item2"]}`
1520
+ ].join("\n");
1521
+ const raw = await llm(prompt, {
1522
+ system: 'Output strictly valid JSON object with "satisfied" and "missing" string arrays.',
1523
+ temperature: 0.1,
1524
+ jsonMode: true
1525
+ });
1526
+ const match = raw.match(/\{[\s\S]*\}/);
1527
+ if (match) {
1528
+ const parsed = JSON.parse(match[0]);
1529
+ if (Array.isArray(parsed.satisfied)) {
1530
+ satisfiedAttributes.push(...parsed.satisfied.map(String));
1531
+ }
1532
+ if (Array.isArray(parsed.missing)) {
1533
+ missingGaps.push(...parsed.missing.map(String));
1534
+ }
1535
+ return { satisfiedAttributes, missingGaps };
1536
+ }
1537
+ } catch {
1538
+ }
1539
+ }
1540
+ const lowerCorpus = ledger.buildFullRawCorpus().toLowerCase();
1541
+ for (const reqItem of targetCheckList) {
1542
+ const tokens = reqItem.toLowerCase().replace(/[^a-z0-9\u00C0-\u1EF9]+/g, " ").split(/\s+/).filter((t) => t.length >= 3);
1543
+ const matched = tokens.filter((t) => lowerCorpus.includes(t)).length;
1544
+ if (tokens.length === 0 || matched / tokens.length >= 0.5) {
1545
+ satisfiedAttributes.push(reqItem);
1546
+ } else {
1547
+ missingGaps.push(reqItem);
1548
+ }
1549
+ }
1550
+ }
1551
+ }
1552
+ return { satisfiedAttributes, missingGaps };
1553
+ }
1554
+ /**
1555
+ * Verifies claims using Decision Model `choice` (`supported | refuted | not_enough_evidence`)
1556
+ * or Generative LLM NLI (`ClaimVerifier.verifyClaims`) when `shouldVerifyClaims` is enabled (e.g., `deep-research`).
1557
+ */
1558
+ async verifyClaimsWithDecisionOrLlm(claims, sourceCorpus, options) {
1559
+ if (claims.length === 0) {
1560
+ return this.claimVerifier.verifyClaimsDeterministic([], sourceCorpus);
1561
+ }
1562
+ if (options.decision) {
1563
+ try {
1564
+ const detBaseline = this.claimVerifier.verifyClaimsDeterministic(claims, sourceCorpus);
1565
+ const res = await options.decision({
1566
+ context: `Verified Evidence Corpus:
1567
+ ${sourceCorpus.slice(0, 6e3)}`,
1568
+ questions: claims.map((claim, idx) => ({
1569
+ id: `claim_${idx}`,
1570
+ type: "choice",
1571
+ criteria: `Evaluate whether the following claim is strictly supported, directly refuted, or has not_enough_evidence in the Verified Evidence Corpus: "${claim}"`,
1572
+ options: ["supported", "refuted", "not_enough_evidence"]
1573
+ }))
1574
+ });
1575
+ const verifiedClaims = claims.map((claim, idx) => {
1576
+ const ans = res.answers[`claim_${idx}`];
1577
+ const verdict = ans?.type === "choice" && ["supported", "refuted", "not_enough_evidence"].includes(ans.choice) ? ans.choice : detBaseline.claims[idx]?.isSupported ? "supported" : "not_enough_evidence";
1578
+ const prob = ans?.probabilities?.[verdict] ?? (verdict === "supported" ? 0.85 : 0.4);
1579
+ return {
1580
+ claimText: claim,
1581
+ verdict,
1582
+ isSupported: verdict === "supported",
1583
+ isLlmVerified: true,
1584
+ confidenceScore: Math.round(prob * 100),
1585
+ extractedQuote: detBaseline.claims[idx]?.extractedQuote,
1586
+ explanation: `Evaluated via Decision Model NLI choice (${verdict}).`
1587
+ };
1588
+ });
1589
+ const supportedCount = verifiedClaims.filter((c) => c.verdict === "supported").length;
1590
+ const refutedCount = verifiedClaims.filter((c) => c.verdict === "refuted").length;
1591
+ const supportPct = supportedCount / claims.length * 100;
1592
+ const hallucinationRisk = refutedCount > 0 ? "high" : supportPct >= 75 ? "low" : "medium";
1593
+ return {
1594
+ totalClaimsChecked: claims.length,
1595
+ supportedClaimsCount: supportedCount,
1596
+ refutedClaimsCount: refutedCount,
1597
+ unverifiedClaimsCount: claims.length - supportedCount,
1598
+ hallucinationRisk,
1599
+ isLlmVerified: true,
1600
+ claims: verifiedClaims,
1601
+ reportMd: detBaseline.reportMd
1602
+ };
1603
+ } catch {
1604
+ }
1605
+ }
1606
+ if (options.llm) {
1607
+ return this.claimVerifier.verifyClaims(claims, sourceCorpus, { llm: options.llm });
1608
+ }
1609
+ return this.claimVerifier.verifyClaimsDeterministic(claims, sourceCorpus);
1610
+ }
1611
+ /**
1612
+ * Stage B: Synthesizes `EvidenceLedger` excerpts into `outputSchema<T>` + `markdownReport`
1613
+ * and runs deterministic schema, citation, and claim verification gates.
1614
+ */
1615
+ async synthesizeAndVerify(params) {
1616
+ const {
1617
+ contract,
1618
+ mode,
1619
+ profile,
1620
+ ledger,
1621
+ approvedCount,
1622
+ minSources,
1623
+ shouldVerifyClaims,
1624
+ missingGaps,
1625
+ roundTraces,
1626
+ modeClassificationTrace,
1627
+ channelTraces,
1628
+ provenanceMd,
1629
+ llm,
1630
+ decision
1631
+ } = params;
1632
+ const synthesisCorpus = ledger.buildSynthesisCorpus(12);
1633
+ const items = ledger.getItems();
1634
+ const receipts = ledger.getReceipts();
1635
+ let synthesizedData = null;
1636
+ let markdownReport = "";
1637
+ let tier1Summary = "";
1638
+ let tier2TechnicalDigest = "";
1639
+ let keyClaims = [];
1640
+ let isLlmSynthesized = false;
1641
+ const schemaHint = contract.outputSchemaDescription || describeZodSchemaKeys(contract.outputSchema) || "JSON object capturing the key structured findings, technical constraints, exemplars, and citations";
1642
+ if (llm) {
1643
+ try {
1644
+ const requiredSectionsText = contract.requiredSections && contract.requiredSections.length > 0 ? contract.requiredSections.join(", ") : "Executive Summary, Key Technical & Empirical Findings, Practical Exemplars & Code/Specs, Common Pitfalls & Bottlenecks, Verified Sources";
1645
+ const prompt = [
1646
+ `You are a Principal Research Synthesizer. Synthesize the verified EvidenceLedger sources below to fulfill the Research Contract.`,
1647
+ `Objective: "${contract.objective}"`,
1648
+ `Mode: ${mode} | Profile: ${profile}`,
1649
+ contract.context?.ageBand ? `Learner Age Band: ${contract.context.ageBand[0]}-${contract.context.ageBand[1]}` : "",
1650
+ contract.context?.hardwarePlatform ? `Hardware Platform: ${contract.context.hardwarePlatform}` : "",
1651
+ contract.context?.softwareEnv ? `Software/Tools: ${contract.context.softwareEnv}` : "",
1652
+ `Required Markdown Sections: ${requiredSectionsText}`,
1653
+ `Required Structured "data" Payload Format: ${schemaHint}`,
1654
+ contract.acceptanceCriteria?.forbiddenTerms?.length ? `Forbidden Terms (MUST NOT APPEAR): ${contract.acceptanceCriteria.forbiddenTerms.join(", ")}` : "",
1655
+ `
1656
+ CRITICAL GROUNDING RULES:`,
1657
+ `1. Every claim, metric, pinout, or recommendation MUST cite its EvidenceLedger ID in brackets, e.g. [RES-01], [RES-02].`,
1658
+ `2. NEVER invent citation IDs outside [RES-01]..[RES-${String(items.length).padStart(2, "0")}].`,
1659
+ `3. If evidence for a specific attribute is missing from the ledger, state that explicitly rather than fabricating facts.`,
1660
+ `
1661
+ === VERIFIED EVIDENCE LEDGER ===
1662
+ ${synthesisCorpus}`,
1663
+ `
1664
+ Return ONLY a valid JSON object with the exact envelope:`,
1665
+ `{`,
1666
+ ` "data": { ...structured payload matching the Required Structured "data" Payload Format... },`,
1667
+ ` "markdownReport": "# Full Markdown Report with [RES-xx] citations and Required Markdown Sections...",`,
1668
+ ` "tier1Summary": "Concise <=200-word executive summary with [RES-xx] citations",`,
1669
+ ` "tier2TechnicalDigest": "Bulleted technical digest (<=600 words) preserving concrete APIs, specs, code/tables, and pitfalls with [RES-xx] tags",`,
1670
+ ` "keyClaims": ["Core factual claim 1 from report", "Core factual claim 2"]`,
1671
+ `}`
1672
+ ].filter(Boolean).join("\n");
1673
+ const raw = await llm(prompt, {
1674
+ system: "Output strictly valid JSON matching the requested synthesis envelope. Ground every claim in [RES-xx].",
1675
+ temperature: 0.2,
1676
+ jsonMode: true
1677
+ });
1678
+ const match = raw.match(/\{[\s\S]*\}/);
1679
+ if (match) {
1680
+ const parsed = JSON.parse(match[0]);
1681
+ markdownReport = typeof parsed.markdownReport === "string" ? parsed.markdownReport : "";
1682
+ tier1Summary = typeof parsed.tier1Summary === "string" ? parsed.tier1Summary : "";
1683
+ tier2TechnicalDigest = typeof parsed.tier2TechnicalDigest === "string" ? parsed.tier2TechnicalDigest : "";
1684
+ keyClaims = Array.isArray(parsed.keyClaims) ? parsed.keyClaims.map(String) : [];
1685
+ const candidateData = parsed.data !== void 0 ? parsed.data : parsed;
1686
+ if (contract.outputSchema) {
1687
+ const validation = contract.outputSchema.safeParse(candidateData);
1688
+ if (validation.success) {
1689
+ synthesizedData = validation.data;
1690
+ isLlmSynthesized = true;
1691
+ } else {
1692
+ const issuesText = validation.error.issues.map((iss) => `${iss.path.join(".") || "root"}: ${iss.message}`).join("; ");
1693
+ const repairPrompt = [
1694
+ `The synthesized "data" object failed Zod schema validation with issues: ${issuesText}`,
1695
+ `Schema requirement: ${schemaHint}`,
1696
+ `Original candidate data: ${JSON.stringify(candidateData)}`,
1697
+ `Repair and return ONLY the valid JSON object for "data" grounded strictly in the EvidenceLedger.`
1698
+ ].join("\n");
1699
+ const repairedRaw = await llm(repairPrompt, {
1700
+ system: "Return strictly valid JSON object matching the schema.",
1701
+ temperature: 0.1,
1702
+ jsonMode: true
1703
+ });
1704
+ const repMatch = repairedRaw.match(/\{[\s\S]*\}/);
1705
+ if (repMatch) {
1706
+ const repParsed = JSON.parse(repMatch[0]);
1707
+ const repCheck = contract.outputSchema.safeParse(repParsed);
1708
+ if (repCheck.success) {
1709
+ synthesizedData = repCheck.data;
1710
+ isLlmSynthesized = true;
1711
+ } else {
1712
+ missingGaps.push(`Output schema validation incomplete: ${issuesText}`);
1713
+ }
1714
+ }
1715
+ }
1716
+ } else {
1717
+ synthesizedData = candidateData;
1718
+ isLlmSynthesized = true;
1719
+ }
1720
+ }
1721
+ } catch (e) {
1722
+ console.warn("[ResearchSubAgent] Stage B LLM synthesis error, falling back to deterministic ledger compilation:", e?.message || e);
1723
+ }
1724
+ }
1725
+ if (!markdownReport) {
1726
+ markdownReport = this.buildDeterministicMarkdownReport(contract.objective, profile, items, contract.requiredSections);
1727
+ }
1728
+ if (!tier1Summary) {
1729
+ tier1Summary = items.slice(0, 3).map((i) => `[${i.id}] ${i.title}: ${i.keyExcerpts[0] || ""}`).join(" ");
1730
+ }
1731
+ if (!tier2TechnicalDigest) {
1732
+ tier2TechnicalDigest = items.slice(0, 6).map((i) => `- **[${i.id}] ${i.title}** (${i.url}): ${i.keyExcerpts.slice(0, 2).join(" ")}`).join("\n");
1733
+ }
1734
+ if (synthesizedData === null && !contract.outputSchema) {
1735
+ synthesizedData = {
1736
+ objective: contract.objective,
1737
+ mode,
1738
+ profile,
1739
+ sources: receipts,
1740
+ codeSnippets: items.flatMap((i) => i.codeBlocks).slice(0, 4),
1741
+ tables: items.flatMap((i) => i.tables).slice(0, 4)
1742
+ };
1743
+ }
1744
+ const combinedText = `${markdownReport}
1745
+ ${tier1Summary}
1746
+ ${tier2TechnicalDigest}
1747
+ ${JSON.stringify(synthesizedData || {})}`;
1748
+ const { validCitationIds, invalidCitationIds } = ledger.verifyCitationTags(combinedText);
1749
+ if (invalidCitationIds.length > 0) {
1750
+ for (const badId of invalidCitationIds) {
1751
+ const regex = new RegExp(`\\[?${badId}\\]?`, "gi");
1752
+ markdownReport = markdownReport.replace(regex, "[UNVERIFIED-CITATION-REMOVED]");
1753
+ tier1Summary = tier1Summary.replace(regex, "");
1754
+ tier2TechnicalDigest = tier2TechnicalDigest.replace(regex, "");
1755
+ }
1756
+ }
1757
+ if (contract.acceptanceCriteria?.forbiddenTerms?.length) {
1758
+ const lowerReport = markdownReport.toLowerCase();
1759
+ for (const forbidden of contract.acceptanceCriteria.forbiddenTerms) {
1760
+ if (lowerReport.includes(forbidden.toLowerCase())) {
1761
+ missingGaps.push(`Forbidden term detected in output: "${forbidden}"`);
1762
+ }
1763
+ }
1764
+ }
1765
+ const claimsToVerify = keyClaims.length > 0 ? keyClaims : items.slice(0, 4).map((i) => i.keyExcerpts[0]).filter((e) => Boolean(e && e.length > 25));
1766
+ const claimVerification = claimsToVerify.length > 0 ? shouldVerifyClaims ? await this.verifyClaimsWithDecisionOrLlm(claimsToVerify, ledger.buildFullRawCorpus(), {
1767
+ decision,
1768
+ llm
1769
+ }) : this.claimVerifier.verifyClaimsDeterministic(claimsToVerify, ledger.buildFullRawCorpus()) : void 0;
1770
+ let status = "success";
1771
+ if (!isLlmSynthesized && llm) {
1772
+ status = "degraded";
1773
+ } else if (missingGaps.length > 0 || approvedCount < minSources || contract.outputSchema && synthesizedData === null) {
1774
+ status = "partial";
1775
+ } else if (!llm) {
1776
+ status = contract.outputSchema && synthesizedData === null ? "degraded" : "success";
1777
+ }
1778
+ return {
1779
+ status,
1780
+ objective: contract.objective,
1781
+ mode,
1782
+ profile,
1783
+ roundsExecuted: roundTraces.length,
1784
+ data: synthesizedData,
1785
+ markdownReport,
1786
+ tier1Summary,
1787
+ tier2TechnicalDigest,
1788
+ ledgerItems: items,
1789
+ receipts,
1790
+ validCitationIds,
1791
+ invalidCitationIds,
1792
+ missingGaps,
1793
+ roundTraces,
1794
+ modeClassificationTrace,
1795
+ channelTraces,
1796
+ claimVerification,
1797
+ provenanceMd
1798
+ };
1799
+ }
1800
+ buildDeterministicMarkdownReport(objective, profile, items, requiredSections) {
1801
+ const sections = requiredSections && requiredSections.length > 0 ? requiredSections : [
1802
+ "Executive Summary",
1803
+ "Verified Technical & Domain Findings",
1804
+ "Code Exemplars & Specifications",
1805
+ "Verified Source Ledger"
1806
+ ];
1807
+ const lines = [
1808
+ `# Research Synthesis Report: ${objective}`,
1809
+ `> **Profile:** \`${profile}\` | **Verified Sources:** \`${items.length}\``,
1810
+ ""
1811
+ ];
1812
+ for (const sec of sections) {
1813
+ lines.push(`## ${sec}`);
1814
+ const lower = sec.toLowerCase();
1815
+ if (lower.includes("code") || lower.includes("spec") || lower.includes("table") || lower.includes("exemplar")) {
1816
+ const blocks = items.flatMap((i) => i.codeBlocks.map((cb) => ({ id: i.id, cb }))).slice(0, 3);
1817
+ const tables = items.flatMap((i) => i.tables.map((tb) => ({ id: i.id, tb }))).slice(0, 2);
1818
+ if (blocks.length === 0 && tables.length === 0) {
1819
+ lines.push(
1820
+ ...items.slice(0, 3).map((i) => `- **[${i.id}] ${i.title}**: ${i.keyExcerpts[0] || ""}`)
1821
+ );
1822
+ } else {
1823
+ for (const b of blocks) {
1824
+ lines.push(`From **[${b.id}]**:
1825
+ \`\`\`${b.cb.language || "text"}
1826
+ ${b.cb.code.slice(0, 500)}
1827
+ \`\`\``);
1828
+ }
1829
+ for (const t of tables) {
1830
+ lines.push(`From **[${t.id}]**:
1831
+
1832
+ ${t.tb}`);
1833
+ }
1834
+ }
1835
+ } else if (lower.includes("source") || lower.includes("reference") || lower.includes("ledger")) {
1836
+ for (const item of items) {
1837
+ lines.push(`- **[${item.id}]** [${item.title}](${item.url}) (${item.sourceType}, Score: ${item.relevanceScore}/10)`);
1838
+ }
1839
+ } else {
1840
+ for (const item of items.slice(0, 6)) {
1841
+ const excerpt = item.keyExcerpts[0] || item.title;
1842
+ lines.push(`- **[${item.id}] ${item.title}**: ${excerpt}`);
1843
+ }
1844
+ }
1845
+ lines.push("");
1846
+ }
1847
+ return lines.join("\n");
1848
+ }
1849
+ };
1850
+ var ResearchAgentToolInputSchema = z.object({
1851
+ objective: z.string().min(3).describe("Core research question or objective to investigate"),
1852
+ mode: z.enum(["auto", "search", "research", "deep-research"]).optional().describe("Execution mode: auto, search (<=8s), research (<=90s, 2 channels), or deep-research (<=300s, 5 channels)"),
1853
+ preferredChannels: z.array(z.enum(["web_docs", "academic", "social_pulse", "stem_oer", "video_media"])).optional().describe("Optional preferred source channels to prioritize"),
1854
+ profile: z.enum([
1855
+ "auto",
1856
+ "fast_grounded",
1857
+ "deep_autonomous",
1858
+ "technical",
1859
+ "academic",
1860
+ "social_pulse",
1861
+ "curriculum_oer",
1862
+ "general"
1863
+ ]).optional().describe("Legacy domain profile"),
1864
+ requiredAttributes: z.array(z.string()).optional().describe("Specific technical attributes, specs, or sub-questions that must be covered"),
1865
+ requiredSections: z.array(z.string()).optional().describe("Required Markdown sections in the synthesized report"),
1866
+ requireCodeExamples: z.boolean().optional().describe("Whether verified code snippets are required"),
1867
+ requireTables: z.boolean().optional().describe("Whether markdown specification/pinout tables are required"),
1868
+ verifyClaims: z.boolean().optional().describe("Whether to run semantic NLI claim verification"),
1869
+ minSources: z.number().int().min(1).max(10).optional().describe("Minimum number of verified sources (default: 2)"),
1870
+ maxChannels: z.number().int().min(1).max(5).optional().describe("Maximum number of ok channels to harvest"),
1871
+ maxRounds: z.number().int().min(1).max(4).optional().describe("Maximum Plan-Harvest-Evaluate rounds"),
1872
+ recencyDays: z.number().int().min(1).max(365).optional().describe("Recency window in days for social pulse signals"),
1873
+ hardwarePlatform: z.string().optional().describe("Optional hardware context (e.g., Arduino Uno, ESP32)"),
1874
+ softwareEnv: z.string().optional().describe("Optional software/IDE context (e.g., mBlock 5, Roblox Studio, Swift 6)")
1875
+ });
1876
+ async function runResearchSubAgent(contract, config = {}) {
1877
+ const agent = new ResearchSubAgent(config);
1878
+ return agent.run(contract);
1879
+ }
1880
+ function createResearchAgentTool(config = {}) {
1881
+ const agent = new ResearchSubAgent(config);
1882
+ return {
1883
+ name: "run_research_subagent",
1884
+ description: "Delegate a research objective to the autonomous Plan-and-Execute Research Sub-Agent (supports mode: auto | search | research | deep-research).",
1885
+ parameters: ResearchAgentToolInputSchema,
1886
+ execute: async (input) => {
1887
+ const result = await agent.run({
1888
+ objective: input.objective,
1889
+ mode: input.mode ?? "auto",
1890
+ preferredChannels: input.preferredChannels,
1891
+ profile: input.profile ?? "auto",
1892
+ requiredSections: input.requiredSections,
1893
+ acceptanceCriteria: {
1894
+ minSources: input.minSources ?? 2,
1895
+ requireCodeExamples: input.requireCodeExamples,
1896
+ requireTables: input.requireTables,
1897
+ verifyClaims: input.verifyClaims,
1898
+ recencyDays: input.recencyDays ?? 30,
1899
+ requiredAttributes: input.requiredAttributes
1900
+ },
1901
+ budget: {
1902
+ maxRounds: input.maxRounds,
1903
+ maxChannels: input.maxChannels
1904
+ },
1905
+ context: input.hardwarePlatform || input.softwareEnv ? {
1906
+ ...config.defaultCourseContext,
1907
+ hardwarePlatform: input.hardwarePlatform ?? config.defaultCourseContext?.hardwarePlatform,
1908
+ softwareEnv: input.softwareEnv ?? config.defaultCourseContext?.softwareEnv
1909
+ } : config.defaultCourseContext
1910
+ });
1911
+ return {
1912
+ status: result.status,
1913
+ mode: result.mode,
1914
+ profile: result.profile,
1915
+ roundsExecuted: result.roundsExecuted,
1916
+ tier1Summary: result.tier1Summary,
1917
+ tier2TechnicalDigest: result.tier2TechnicalDigest,
1918
+ markdownReport: result.markdownReport,
1919
+ citations: result.receipts,
1920
+ validCitationIds: result.validCitationIds,
1921
+ missingGaps: result.missingGaps,
1922
+ modeClassificationTrace: result.modeClassificationTrace,
1923
+ channelTraces: result.channelTraces
1924
+ };
1925
+ }
1926
+ };
1927
+ }
1928
+
1929
+ export { EvidenceLedger, PRIOR_MATRIX, QUESTION_FACETS, RESEARCH_MODE_PRESETS, RESEARCH_PROFILE_PRESETS, ResearchAgentToolInputSchema, ResearchSubAgent, SOURCE_CHANNELS, classifyChannelStatus, classifyModeAndPrior, computeContractComplexityScore, createResearchAgentTool, evaluateAttributeCoverageWithDecision, inferFallbackFacetProbabilities, isSemanticRankedHit, rankChannelsByExpectedPrior, resolveResearchProfile, runConcurrentRefillScheduler, runResearchSubAgent };
1930
+ //# sourceMappingURL=chunk-4S6UMYBA.js.map
1931
+ //# sourceMappingURL=chunk-4S6UMYBA.js.map