@thanh01.pmt/research-kit 1.2.3 → 1.3.0

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 (69) hide show
  1. package/dist/academic/index.cjs +122 -0
  2. package/dist/academic/index.cjs.map +1 -1
  3. package/dist/academic/index.d.cts +27 -4
  4. package/dist/academic/index.d.ts +27 -4
  5. package/dist/academic/index.js +2 -1
  6. package/dist/agent/index.cjs +3441 -0
  7. package/dist/agent/index.cjs.map +1 -0
  8. package/dist/agent/index.d.cts +10 -0
  9. package/dist/agent/index.d.ts +10 -0
  10. package/dist/agent/index.js +10 -0
  11. package/dist/agent/index.js.map +1 -0
  12. package/dist/{catalogBuilder-B4eiLS_S.d.cts → catalogBuilder-BBCa9jqI.d.cts} +2 -2
  13. package/dist/{catalogBuilder-BNB_gaWP.d.ts → catalogBuilder-D-UiM37y.d.ts} +2 -2
  14. package/dist/chunk-2GBXVPOQ.js +3 -0
  15. package/dist/{chunk-J3VCGH7Z.js.map → chunk-2GBXVPOQ.js.map} +1 -1
  16. package/dist/chunk-2RMBLKP5.js +581 -0
  17. package/dist/chunk-2RMBLKP5.js.map +1 -0
  18. package/dist/{chunk-2XIEWCUE.js → chunk-32B5PVTQ.js} +2 -2
  19. package/dist/{chunk-2XIEWCUE.js.map → chunk-32B5PVTQ.js.map} +1 -1
  20. package/dist/chunk-LDCZ33AC.js +3 -0
  21. package/dist/chunk-LDCZ33AC.js.map +1 -0
  22. package/dist/chunk-NSY6KU4G.js +125 -0
  23. package/dist/chunk-NSY6KU4G.js.map +1 -0
  24. package/dist/{chunk-SAHBBO3U.js → chunk-RYLZYZRF.js} +4 -580
  25. package/dist/chunk-RYLZYZRF.js.map +1 -0
  26. package/dist/{chunk-P6RHBJY2.js → chunk-S3JUCDKD.js} +62 -40
  27. package/dist/chunk-S3JUCDKD.js.map +1 -0
  28. package/dist/chunk-TYQEC24G.js +3 -0
  29. package/dist/chunk-TYQEC24G.js.map +1 -0
  30. package/dist/chunk-WWQ45RQK.js +1114 -0
  31. package/dist/chunk-WWQ45RQK.js.map +1 -0
  32. package/dist/{chunk-YICMTZS5.js → chunk-ZNGU4ZYX.js} +171 -3
  33. package/dist/chunk-ZNGU4ZYX.js.map +1 -0
  34. package/dist/config/index.d.cts +1 -1
  35. package/dist/config/index.d.ts +1 -1
  36. package/dist/evidence/index.d.cts +2 -2
  37. package/dist/evidence/index.d.ts +2 -2
  38. package/dist/evidence/index.js +2 -1
  39. package/dist/harvester/index.cjs +168 -1
  40. package/dist/harvester/index.cjs.map +1 -1
  41. package/dist/harvester/index.d.cts +5 -161
  42. package/dist/harvester/index.d.ts +5 -161
  43. package/dist/harvester/index.js +4 -2
  44. package/dist/index-CN8gei7k.d.ts +518 -0
  45. package/dist/{index-9rDiFuR4.d.ts → index-CxoD81QN.d.cts} +1 -1
  46. package/dist/{index-9rDiFuR4.d.cts → index-CxoD81QN.d.ts} +1 -1
  47. package/dist/index-onQDKDNo.d.cts +518 -0
  48. package/dist/index.cjs +1463 -36
  49. package/dist/index.cjs.map +1 -1
  50. package/dist/index.d.cts +11 -174
  51. package/dist/index.d.ts +11 -174
  52. package/dist/index.js +25 -10
  53. package/dist/index.js.map +1 -1
  54. package/dist/{literatureReview-DOzgm9Q2.d.ts → literatureReview-Bn2iEGRO.d.ts} +1 -1
  55. package/dist/{literatureReview-BwidpYJo.d.cts → literatureReview-Bvlqk4DB.d.cts} +1 -1
  56. package/dist/pipeline/index.cjs +59 -38
  57. package/dist/pipeline/index.cjs.map +1 -1
  58. package/dist/pipeline/index.d.cts +5 -4
  59. package/dist/pipeline/index.d.ts +5 -4
  60. package/dist/pipeline/index.js +3 -2
  61. package/dist/socialPulseHarvester-CN4MwrpY.d.cts +204 -0
  62. package/dist/socialPulseHarvester-IbdT3zD1.d.ts +204 -0
  63. package/dist/{webScraper-CAQjE46m.d.cts → webScraper-BVvNW4yj.d.cts} +1 -1
  64. package/dist/{webScraper-CXIpvyA6.d.ts → webScraper-C9pB5Rgd.d.ts} +1 -1
  65. package/package.json +6 -1
  66. package/dist/chunk-J3VCGH7Z.js +0 -3
  67. package/dist/chunk-P6RHBJY2.js.map +0 -1
  68. package/dist/chunk-SAHBBO3U.js.map +0 -1
  69. package/dist/chunk-YICMTZS5.js.map +0 -1
@@ -0,0 +1,1114 @@
1
+ import { OpenAlexClient } from './chunk-NSY6KU4G.js';
2
+ import { SocialPulseHarvester, StemResourceResearcher } from './chunk-ZNGU4ZYX.js';
3
+ import { ClaimVerifier } from './chunk-32B5PVTQ.js';
4
+ import { MultiSourceSearchEngine, HealthAuditor, classifyTechnicalDomain, isCommercialOrNoise } from './chunk-2RMBLKP5.js';
5
+ import { AcademicSearchEngine } from './chunk-AKEI7H2C.js';
6
+ import { EvidenceScorer, ProvenanceTracker } from './chunk-KXJDQBSJ.js';
7
+ import { WebScraper } from './chunk-QQZQNBJC.js';
8
+ import { z } from 'zod';
9
+
10
+ // src/agent/types.ts
11
+ var RESEARCH_PROFILE_PRESETS = {
12
+ fast_grounded: {
13
+ maxRounds: 2,
14
+ maxQueriesPerRound: 3,
15
+ maxScrapePerRound: 3,
16
+ timeoutMs: 35e3,
17
+ enableWeb: true,
18
+ enableAcademic: false,
19
+ enableSocialPulse: false,
20
+ enableStemOer: false
21
+ },
22
+ deep_autonomous: {
23
+ maxRounds: 3,
24
+ maxQueriesPerRound: 4,
25
+ maxScrapePerRound: 4,
26
+ timeoutMs: 12e4,
27
+ enableWeb: true,
28
+ enableAcademic: true,
29
+ enableSocialPulse: true,
30
+ enableStemOer: true
31
+ },
32
+ technical: {
33
+ maxRounds: 2,
34
+ maxQueriesPerRound: 3,
35
+ maxScrapePerRound: 4,
36
+ timeoutMs: 45e3,
37
+ enableWeb: true,
38
+ enableAcademic: false,
39
+ enableSocialPulse: true,
40
+ enableStemOer: false
41
+ },
42
+ academic: {
43
+ maxRounds: 2,
44
+ maxQueriesPerRound: 3,
45
+ maxScrapePerRound: 2,
46
+ timeoutMs: 45e3,
47
+ enableWeb: true,
48
+ enableAcademic: true,
49
+ enableSocialPulse: false,
50
+ enableStemOer: false
51
+ },
52
+ social_pulse: {
53
+ maxRounds: 2,
54
+ maxQueriesPerRound: 3,
55
+ maxScrapePerRound: 2,
56
+ timeoutMs: 35e3,
57
+ enableWeb: true,
58
+ enableAcademic: false,
59
+ enableSocialPulse: true,
60
+ enableStemOer: false
61
+ },
62
+ curriculum_oer: {
63
+ maxRounds: 2,
64
+ maxQueriesPerRound: 3,
65
+ maxScrapePerRound: 3,
66
+ timeoutMs: 45e3,
67
+ enableWeb: true,
68
+ enableAcademic: false,
69
+ enableSocialPulse: false,
70
+ enableStemOer: true
71
+ },
72
+ general: {
73
+ maxRounds: 2,
74
+ maxQueriesPerRound: 3,
75
+ maxScrapePerRound: 3,
76
+ timeoutMs: 45e3,
77
+ enableWeb: true,
78
+ enableAcademic: false,
79
+ enableSocialPulse: false,
80
+ enableStemOer: false
81
+ }
82
+ };
83
+
84
+ // src/agent/evidenceLedger.ts
85
+ function normalizeUrlKey(rawUrl) {
86
+ try {
87
+ const u = new URL(rawUrl.trim());
88
+ u.hash = "";
89
+ for (const param of ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "ref"]) {
90
+ u.searchParams.delete(param);
91
+ }
92
+ return u.toString().replace(/\/$/, "").toLowerCase();
93
+ } catch {
94
+ return rawUrl.trim().replace(/\/$/, "").toLowerCase();
95
+ }
96
+ }
97
+ var EvidenceLedger = class {
98
+ items = [];
99
+ urlIndex = /* @__PURE__ */ new Map();
100
+ idIndex = /* @__PURE__ */ new Map();
101
+ allocateId() {
102
+ const nextNum = this.items.length + 1;
103
+ return `RES-${String(nextNum).padStart(2, "0")}`;
104
+ }
105
+ /**
106
+ * Records or upgrades a ledger entry from a full `ScrapedDocument`.
107
+ */
108
+ addScrapedDocument(doc, relevanceScore, extraTakeaways = []) {
109
+ const key = normalizeUrlKey(doc.url);
110
+ const existing = this.urlIndex.get(key);
111
+ const mergedExcerpts = Array.from(
112
+ new Set([
113
+ ...extraTakeaways,
114
+ ...doc.keyExcerpts || [],
115
+ doc.markdownContent.replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, 450)
116
+ ].filter((e) => e && e.trim().length > 20))
117
+ ).slice(0, 6);
118
+ const sourceType = doc.fetchProvider === "youtube" ? "youtube" : "web";
119
+ if (existing) {
120
+ existing.title = doc.title || existing.title;
121
+ existing.relevanceScore = Math.max(existing.relevanceScore, relevanceScore);
122
+ existing.headings = doc.extractedHeadings?.slice(0, 8) || existing.headings;
123
+ existing.keyExcerpts = mergedExcerpts.length > 0 ? mergedExcerpts : existing.keyExcerpts;
124
+ existing.codeBlocks = (doc.extractedCodeBlocks || []).slice(0, 4);
125
+ existing.tables = (doc.extractedTables || []).slice(0, 4);
126
+ existing.rawByteSize = Math.max(existing.rawByteSize, doc.byteSize || 0);
127
+ return this.toCompactReceipt(existing);
128
+ }
129
+ const item = {
130
+ id: this.allocateId(),
131
+ sourceType,
132
+ title: doc.title || "Untitled Document",
133
+ url: doc.url,
134
+ relevanceScore: Math.max(1, Math.min(10, Math.round(relevanceScore))),
135
+ headings: (doc.extractedHeadings || []).slice(0, 8),
136
+ keyExcerpts: mergedExcerpts,
137
+ codeBlocks: (doc.extractedCodeBlocks || []).slice(0, 4),
138
+ tables: (doc.extractedTables || []).slice(0, 4),
139
+ rawByteSize: doc.byteSize || Buffer.byteLength(doc.markdownContent || "", "utf-8"),
140
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
141
+ };
142
+ this.items.push(item);
143
+ this.urlIndex.set(key, item);
144
+ this.idIndex.set(item.id, item);
145
+ return this.toCompactReceipt(item);
146
+ }
147
+ /**
148
+ * Records a lightweight search hit when full scraping is skipped or pending.
149
+ */
150
+ addSearchHit(hit, relevanceScore = 6) {
151
+ const key = normalizeUrlKey(hit.url);
152
+ const existing = this.urlIndex.get(key);
153
+ if (existing) {
154
+ return this.toCompactReceipt(existing);
155
+ }
156
+ const snippet = (hit.content || "").replace(/\s+/g, " ").trim();
157
+ const item = {
158
+ id: this.allocateId(),
159
+ sourceType: hit.engine === "academic" ? "academic" : "web",
160
+ title: hit.title || "Search Result",
161
+ url: hit.url,
162
+ relevanceScore: Math.max(1, Math.min(10, Math.round(relevanceScore))),
163
+ headings: [],
164
+ keyExcerpts: snippet ? [snippet.slice(0, 450)] : [],
165
+ codeBlocks: [],
166
+ tables: [],
167
+ rawByteSize: Buffer.byteLength(snippet, "utf-8"),
168
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
169
+ };
170
+ this.items.push(item);
171
+ this.urlIndex.set(key, item);
172
+ this.idIndex.set(item.id, item);
173
+ return this.toCompactReceipt(item);
174
+ }
175
+ /**
176
+ * Records a peer-reviewed or preprint paper from Semantic Scholar, OpenAlex, Crossref, or arXiv.
177
+ */
178
+ addAcademicPaper(paper) {
179
+ const url = paper.url || paper.pdfUrl || (paper.doi ? `https://doi.org/${paper.doi}` : `https://openalex.org/${paper.id}`);
180
+ const key = normalizeUrlKey(url);
181
+ const existing = this.urlIndex.get(key);
182
+ if (existing) {
183
+ return this.toCompactReceipt(existing);
184
+ }
185
+ const abstractOrTldr = [paper.tldr, paper.abstract].filter(Boolean).join(" \u2014 ").trim();
186
+ const citationBonus = paper.citationCount >= 50 ? 9 : paper.citationCount >= 10 ? 8 : 7;
187
+ const item = {
188
+ id: this.allocateId(),
189
+ sourceType: "academic",
190
+ title: paper.title,
191
+ url,
192
+ authorOrVenue: [paper.authors?.slice(0, 3).join(", "), paper.venue, paper.year].filter(Boolean).join(" \xB7 "),
193
+ publishedDate: paper.year ? String(paper.year) : void 0,
194
+ relevanceScore: citationBonus,
195
+ headings: paper.fieldsOfStudy || [],
196
+ keyExcerpts: abstractOrTldr ? [abstractOrTldr.slice(0, 600)] : [`Academic paper: ${paper.title}`],
197
+ codeBlocks: [],
198
+ tables: [],
199
+ rawByteSize: Buffer.byteLength(abstractOrTldr || paper.title, "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 30-day social/developer pulse signal (HackerNews, GitHub, Reddit).
209
+ */
210
+ addSocialPulseItem(pulse) {
211
+ const key = normalizeUrlKey(pulse.url);
212
+ const existing = this.urlIndex.get(key);
213
+ if (existing) {
214
+ return this.toCompactReceipt(existing);
215
+ }
216
+ const item = {
217
+ id: this.allocateId(),
218
+ sourceType: "social_pulse",
219
+ title: pulse.title,
220
+ url: pulse.url,
221
+ authorOrVenue: `${pulse.platform.toUpperCase()}${pulse.author ? ` (@${pulse.author})` : ""}`,
222
+ publishedDate: pulse.createdAt,
223
+ relevanceScore: Math.max(1, Math.min(10, pulse.engagementScore)),
224
+ headings: [pulse.platform.toUpperCase()],
225
+ keyExcerpts: [pulse.snippet.slice(0, 450)],
226
+ codeBlocks: [],
227
+ tables: [],
228
+ rawByteSize: Buffer.byteLength(pulse.snippet, "utf-8"),
229
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
230
+ };
231
+ this.items.push(item);
232
+ this.urlIndex.set(key, item);
233
+ this.idIndex.set(item.id, item);
234
+ return this.toCompactReceipt(item);
235
+ }
236
+ /**
237
+ * Records a verified STEM OER simulation/resource (PhET, OpenStax, NASA, CS Unplugged).
238
+ */
239
+ addStemResource(resource) {
240
+ const key = normalizeUrlKey(resource.url);
241
+ const existing = this.urlIndex.get(key);
242
+ if (existing) {
243
+ return this.toCompactReceipt(existing);
244
+ }
245
+ const excerpt = `${resource.description} [Provider: ${resource.provider}${resource.license ? `, License: ${resource.license}` : ""}]`;
246
+ const item = {
247
+ id: this.allocateId(),
248
+ sourceType: "stem_oer",
249
+ title: resource.title,
250
+ url: resource.url,
251
+ authorOrVenue: resource.provider,
252
+ relevanceScore: 8,
253
+ headings: [resource.provider],
254
+ keyExcerpts: [excerpt.slice(0, 450)],
255
+ codeBlocks: [],
256
+ tables: [],
257
+ rawByteSize: Buffer.byteLength(excerpt, "utf-8"),
258
+ accessedAt: (/* @__PURE__ */ new Date()).toISOString()
259
+ };
260
+ this.items.push(item);
261
+ this.urlIndex.set(key, item);
262
+ this.idIndex.set(item.id, item);
263
+ return this.toCompactReceipt(item);
264
+ }
265
+ /**
266
+ * Projects a full `LedgerItem` into a compact receipt (<= 150 tokens) for Stage A planning & gap analysis.
267
+ */
268
+ toCompactReceipt(item) {
269
+ const rawExcerpt = item.keyExcerpts[0] || item.title;
270
+ return {
271
+ id: item.id,
272
+ sourceType: item.sourceType,
273
+ title: item.title.slice(0, 140),
274
+ url: item.url,
275
+ relevanceScore: item.relevanceScore,
276
+ headings: item.headings.slice(0, 5),
277
+ codeBlockCount: item.codeBlocks.length,
278
+ tableCount: item.tables.length,
279
+ briefExcerpt: rawExcerpt.slice(0, 300)
280
+ };
281
+ }
282
+ getItems() {
283
+ return [...this.items];
284
+ }
285
+ getApprovedItems(minScore = 6) {
286
+ return this.items.filter((i) => i.relevanceScore >= minScore);
287
+ }
288
+ getReceipts() {
289
+ return this.items.map((i) => this.toCompactReceipt(i));
290
+ }
291
+ getById(id) {
292
+ return this.idIndex.get(id.toUpperCase());
293
+ }
294
+ getTotalCodeBlocks() {
295
+ return this.items.reduce((sum, i) => sum + i.codeBlocks.length, 0);
296
+ }
297
+ getTotalTables() {
298
+ return this.items.reduce((sum, i) => sum + i.tables.length, 0);
299
+ }
300
+ /**
301
+ * Formats the top verified items with `[RES-xx]` tags, substantive excerpts, code blocks,
302
+ * and tables for Stage B Contract Synthesis.
303
+ */
304
+ buildSynthesisCorpus(maxItems = 12) {
305
+ const sorted = [...this.items].sort((a, b) => b.relevanceScore - a.relevanceScore).slice(0, maxItems);
306
+ if (sorted.length === 0) {
307
+ return "No verified sources recorded in EvidenceLedger.";
308
+ }
309
+ return sorted.map((item) => {
310
+ const parts = [
311
+ `[${item.id}] (${item.sourceType.toUpperCase()} \xB7 Score ${item.relevanceScore}/10) Title: ${item.title}`,
312
+ `URL: ${item.url}`
313
+ ];
314
+ if (item.authorOrVenue) {
315
+ parts.push(`Source/Author: ${item.authorOrVenue}`);
316
+ }
317
+ if (item.headings.length > 0) {
318
+ parts.push(`Sections: ${item.headings.join(" | ")}`);
319
+ }
320
+ if (item.keyExcerpts.length > 0) {
321
+ parts.push(`Verified Excerpts:
322
+ ${item.keyExcerpts.map((e) => `- ${e}`).join("\n")}`);
323
+ }
324
+ if (item.codeBlocks.length > 0) {
325
+ parts.push(
326
+ `Extracted Code Blocks:
327
+ ` + item.codeBlocks.slice(0, 2).map((cb) => `\`\`\`${cb.language || "text"}
328
+ ${cb.code.slice(0, 600)}
329
+ \`\`\``).join("\n")
330
+ );
331
+ }
332
+ if (item.tables.length > 0) {
333
+ parts.push(`Extracted Tables:
334
+ ${item.tables.slice(0, 2).join("\n\n")}`);
335
+ }
336
+ return parts.join("\n");
337
+ }).join("\n\n---\n\n");
338
+ }
339
+ /**
340
+ * Returns concatenated plain text of all ledger items for deterministic/LLM `ClaimVerifier` checks.
341
+ */
342
+ buildFullRawCorpus() {
343
+ return this.items.map(
344
+ (i) => `${i.title}
345
+ ${i.keyExcerpts.join("\n")}
346
+ ${i.codeBlocks.map((c) => c.code).join("\n")}
347
+ ${i.tables.join("\n")}`
348
+ ).join("\n\n");
349
+ }
350
+ /**
351
+ * Scans any synthesized report or JSON string for `[RES-xx]` citation markers
352
+ * and verifies every marker against the ledger.
353
+ */
354
+ verifyCitationTags(synthesizedText) {
355
+ const matches = [...synthesizedText.matchAll(/\[?(RES-\d{2,3})\]?/gi)];
356
+ const validSet = /* @__PURE__ */ new Set();
357
+ const invalidSet = /* @__PURE__ */ new Set();
358
+ for (const m of matches) {
359
+ const tag = m[1].toUpperCase();
360
+ if (this.idIndex.has(tag)) {
361
+ validSet.add(tag);
362
+ } else {
363
+ invalidSet.add(tag);
364
+ }
365
+ }
366
+ return {
367
+ validCitationIds: Array.from(validSet),
368
+ invalidCitationIds: Array.from(invalidSet)
369
+ };
370
+ }
371
+ /**
372
+ * Maps ledger items into `ProvenanceRecord[]` for `ProvenanceTracker`.
373
+ */
374
+ toProvenanceRecords(defaultDomain = "general") {
375
+ return this.items.map((item) => ({
376
+ resourceId: item.id,
377
+ sourceUrl: item.url,
378
+ accessedAt: item.accessedAt,
379
+ domain: item.sourceType || defaultDomain,
380
+ relevanceScore: item.relevanceScore,
381
+ byteSize: item.rawByteSize
382
+ }));
383
+ }
384
+ };
385
+ function describeZodSchemaKeys(schema) {
386
+ if (!schema) return void 0;
387
+ const def = schema?._def;
388
+ if (def?.typeName === "ZodObject" && typeof def.shape === "function") {
389
+ const shapeObj = def.shape();
390
+ const keys = Object.keys(shapeObj);
391
+ if (keys.length > 0) {
392
+ return `JSON object with required top-level keys: ${keys.map((k) => `"${k}"`).join(", ")}`;
393
+ }
394
+ }
395
+ return void 0;
396
+ }
397
+ function resolveResearchProfile(contract) {
398
+ if (contract.profile && contract.profile !== "auto") {
399
+ return contract.profile;
400
+ }
401
+ const text = `${contract.objective} ${contract.context?.positioning || ""}`.toLowerCase();
402
+ if (/\b(hackernews|reddit|social|pulse|trend|last 30 days|community sentiment|github stars)\b/.test(text)) {
403
+ return "social_pulse";
404
+ }
405
+ if (/\b(literature review|academic|peer-reviewed|openalex|arxiv|citation|paper|cs2023)\b/.test(text)) {
406
+ return "academic";
407
+ }
408
+ if (/\b(phet|oer|openstax|simulation|worksheet|unplugged)\b/.test(text)) {
409
+ return "curriculum_oer";
410
+ }
411
+ 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)) {
412
+ return "technical";
413
+ }
414
+ return "general";
415
+ }
416
+ var ResearchSubAgent = class {
417
+ constructor(config = {}) {
418
+ this.config = config;
419
+ this.searchEngine = new MultiSourceSearchEngine({
420
+ apiKeys: config.apiKeys,
421
+ allowEnvFallback: config.allowEnvFallback,
422
+ customAdapter: config.customSearchAdapter
423
+ });
424
+ this.webScraper = new WebScraper({
425
+ crawl4aiHost: config.crawl4aiHost,
426
+ jinaKey: config.apiKeys?.jina,
427
+ brightDataKey: config.apiKeys?.brightdata || config.apiKeys?.brightData,
428
+ allowEnvFallback: config.allowEnvFallback,
429
+ customAdapter: config.customCrawlerAdapter
430
+ });
431
+ this.academicEngine = new AcademicSearchEngine({
432
+ apiKey: config.apiKeys?.semanticScholar,
433
+ allowEnvFallback: config.allowEnvFallback,
434
+ customAdapter: config.customAcademicSearchAdapter
435
+ });
436
+ this.openAlexClient = new OpenAlexClient();
437
+ this.socialPulseHarvester = new SocialPulseHarvester(this.searchEngine);
438
+ this.stemResearcher = new StemResourceResearcher();
439
+ this.healthAuditor = new HealthAuditor();
440
+ this.evidenceScorer = new EvidenceScorer();
441
+ this.claimVerifier = new ClaimVerifier();
442
+ this.provenanceTracker = new ProvenanceTracker();
443
+ }
444
+ searchEngine;
445
+ webScraper;
446
+ academicEngine;
447
+ openAlexClient;
448
+ socialPulseHarvester;
449
+ stemResearcher;
450
+ healthAuditor;
451
+ evidenceScorer;
452
+ claimVerifier;
453
+ provenanceTracker;
454
+ /**
455
+ * Executes a complete Plan-and-Execute research campaign governed by `contract`.
456
+ */
457
+ async run(contract, options) {
458
+ const llm = options?.llm ?? this.config.llm;
459
+ const resolvedProfile = resolveResearchProfile(contract);
460
+ const preset = RESEARCH_PROFILE_PRESETS[resolvedProfile];
461
+ const ctx = contract.context ?? this.config.defaultCourseContext;
462
+ const domain = classifyTechnicalDomain(contract.objective, void 0, ctx).domain;
463
+ const maxRounds = Math.max(1, Math.min(5, contract.budget?.maxRounds ?? preset.maxRounds));
464
+ const maxQueriesPerRound = Math.max(1, Math.min(6, contract.budget?.maxQueriesPerRound ?? preset.maxQueriesPerRound));
465
+ const maxScrapePerRound = Math.max(1, Math.min(6, contract.budget?.maxScrapePerRound ?? preset.maxScrapePerRound));
466
+ const minSources = contract.acceptanceCriteria?.minSources ?? 2;
467
+ const minRelevanceScore = contract.acceptanceCriteria?.minRelevanceScore ?? 6;
468
+ const recencyDays = contract.acceptanceCriteria?.recencyDays ?? 30;
469
+ const ledger = new EvidenceLedger();
470
+ const executedQueries = /* @__PURE__ */ new Set();
471
+ const scrapedUrls = /* @__PURE__ */ new Set();
472
+ const roundTraces = [];
473
+ let currentMissingGaps = [
474
+ ...contract.acceptanceCriteria?.requiredAttributes || [],
475
+ ...contract.requiredSections || []
476
+ ];
477
+ for (let round = 1; round <= maxRounds; round++) {
478
+ const beforeReceiptCount = ledger.getReceipts().length;
479
+ const plannedQueries = await this.planQueriesForRound({
480
+ round,
481
+ contract,
482
+ profile: resolvedProfile,
483
+ missingGaps: currentMissingGaps,
484
+ receipts: ledger.getReceipts(),
485
+ executedQueries,
486
+ maxQueries: maxQueriesPerRound,
487
+ llm
488
+ });
489
+ for (const q of plannedQueries) {
490
+ executedQueries.add(q.toLowerCase());
491
+ }
492
+ await this.executeHarvestRound({
493
+ round,
494
+ queries: plannedQueries,
495
+ contract,
496
+ preset,
497
+ domain,
498
+ recencyDays,
499
+ maxScrapePerRound,
500
+ scrapedUrls,
501
+ ledger
502
+ });
503
+ const afterReceiptCount = ledger.getReceipts().length;
504
+ const newReceiptsAdded = afterReceiptCount - beforeReceiptCount;
505
+ const evaluation = await this.evaluateRoundGaps({
506
+ contract,
507
+ ledger,
508
+ minSources,
509
+ minRelevanceScore,
510
+ llm
511
+ });
512
+ currentMissingGaps = evaluation.missingGaps;
513
+ roundTraces.push({
514
+ round,
515
+ plannedQueries,
516
+ newReceiptsAdded,
517
+ satisfiedAttributes: evaluation.satisfiedAttributes,
518
+ missingGaps: evaluation.missingGaps
519
+ });
520
+ if (evaluation.missingGaps.length === 0) {
521
+ break;
522
+ }
523
+ }
524
+ const allItems = ledger.getItems();
525
+ const approvedItems = ledger.getApprovedItems(minRelevanceScore);
526
+ const provenanceSidecar = this.provenanceTracker.generateSidecar(
527
+ contract.objective,
528
+ ledger.toProvenanceRecords(domain)
529
+ );
530
+ if (allItems.length === 0) {
531
+ const failMsg = `Research Sub-Agent failed to harvest any verified sources for objective: "${contract.objective}".`;
532
+ return {
533
+ status: "failed",
534
+ objective: contract.objective,
535
+ profile: resolvedProfile,
536
+ roundsExecuted: roundTraces.length,
537
+ data: null,
538
+ markdownReport: `# \u274C Research Harvest Failed: ${contract.objective}
539
+
540
+ > ${failMsg}
541
+
542
+ ### Unresolved Gaps
543
+ ${currentMissingGaps.length > 0 ? currentMissingGaps.map((g) => `- ${g}`).join("\n") : "- No reachable sources."}`,
544
+ tier1Summary: failMsg,
545
+ tier2TechnicalDigest: failMsg,
546
+ ledgerItems: [],
547
+ receipts: [],
548
+ validCitationIds: [],
549
+ invalidCitationIds: [],
550
+ missingGaps: currentMissingGaps.length > 0 ? currentMissingGaps : ["minSources not met (0 harvested)"],
551
+ roundTraces,
552
+ provenanceMd: provenanceSidecar.provenanceMd
553
+ };
554
+ }
555
+ return this.synthesizeAndVerify({
556
+ contract,
557
+ profile: resolvedProfile,
558
+ domain,
559
+ ledger,
560
+ approvedCount: approvedItems.length,
561
+ minSources,
562
+ missingGaps: currentMissingGaps,
563
+ roundTraces,
564
+ provenanceMd: provenanceSidecar.provenanceMd,
565
+ llm
566
+ });
567
+ }
568
+ /**
569
+ * Plans targeted search queries for Round 1 (initial coverage) or Round > 1 (surgical gap filling).
570
+ */
571
+ async planQueriesForRound(params) {
572
+ const { round, contract, profile, missingGaps, receipts, executedQueries, maxQueries, llm } = params;
573
+ const ctx = contract.context ?? this.config.defaultCourseContext;
574
+ const toolAnchor = [ctx?.hardwarePlatform, ctx?.softwareEnv].filter(Boolean).join(" ").trim();
575
+ const baseTopic = toolAnchor ? `${toolAnchor} ${contract.objective}` : contract.objective;
576
+ if (llm) {
577
+ try {
578
+ const promptLines = [
579
+ `You are a Principal Research Planner for an autonomous Plan-and-Execute Research Sub-Agent.`,
580
+ `Objective: "${contract.objective}"`,
581
+ `Profile: ${profile} | Round: ${round}`,
582
+ toolAnchor ? `Hardware/Software Context: ${toolAnchor}` : "",
583
+ ctx?.ageBand ? `Target Learner Age Band: ${ctx.ageBand[0]}-${ctx.ageBand[1]}` : "",
584
+ contract.requiredSections?.length ? `Required Sections: ${contract.requiredSections.join(", ")}` : "",
585
+ contract.acceptanceCriteria?.requiredAttributes?.length ? `Required Attributes: ${contract.acceptanceCriteria.requiredAttributes.join(", ")}` : "",
586
+ contract.acceptanceCriteria?.requireCodeExamples ? `Must find verified code examples.` : "",
587
+ contract.acceptanceCriteria?.requireTables ? `Must find specification/pinout tables.` : ""
588
+ ];
589
+ if (round > 1 && receipts.length > 0) {
590
+ promptLines.push(
591
+ `
592
+ Compact Receipts Collected So Far (${receipts.length} sources):`,
593
+ ...receipts.slice(0, 8).map(
594
+ (r) => `- [${r.id}] ${r.title} (score:${r.relevanceScore}, code:${r.codeBlockCount}, tables:${r.tableCount}): ${r.briefExcerpt.slice(0, 140)}`
595
+ ),
596
+ `
597
+ Remaining Unresolved Gaps to Fill in Round ${round}:`,
598
+ ...missingGaps.map((g) => `- ${g}`),
599
+ `
600
+ Previously Executed Queries (DO NOT REPEAT): ${Array.from(executedQueries).join(" | ")}`
601
+ );
602
+ }
603
+ promptLines.push(
604
+ `
605
+ Generate ${maxQueries} high-precision search queries to fulfill ${round === 1 ? "the objective and required attributes" : "ONLY the remaining unresolved gaps"}.`,
606
+ `Return ONLY a valid JSON array of query strings: ["query 1", "query 2"]`
607
+ );
608
+ const raw = await llm(promptLines.filter(Boolean).join("\n"), {
609
+ system: "Return strictly a valid JSON array of search query strings.",
610
+ temperature: 0.2,
611
+ jsonMode: true
612
+ });
613
+ const match = raw.match(/\[[\s\S]*\]/);
614
+ if (match) {
615
+ const parsed = JSON.parse(match[0]);
616
+ if (Array.isArray(parsed)) {
617
+ const candidateQueries = parsed.map((q) => String(q).trim()).filter((q) => q.length > 3 && !executedQueries.has(q.toLowerCase())).slice(0, maxQueries);
618
+ if (candidateQueries.length > 0) {
619
+ return candidateQueries;
620
+ }
621
+ }
622
+ }
623
+ } catch (e) {
624
+ console.warn(`[ResearchSubAgent] Round ${round} LLM query planning fallback:`, e?.message || e);
625
+ }
626
+ }
627
+ const fallbackQueries = [];
628
+ if (round === 1) {
629
+ fallbackQueries.push(
630
+ `${baseTopic} official documentation architecture specification`.trim(),
631
+ `${baseTopic} practical examples tutorial implementation`.trim(),
632
+ `${baseTopic} common pitfalls debugging troubleshooting bottlenecks`.trim()
633
+ );
634
+ if (contract.acceptanceCriteria?.requireTables) {
635
+ fallbackQueries.push(`${baseTopic} pinout specification comparison table`.trim());
636
+ }
637
+ } else {
638
+ for (const gap of missingGaps) {
639
+ const candidate = `${baseTopic} ${gap}`.trim();
640
+ if (!executedQueries.has(candidate.toLowerCase())) {
641
+ fallbackQueries.push(candidate);
642
+ }
643
+ }
644
+ if (fallbackQueries.length === 0) {
645
+ fallbackQueries.push(`${baseTopic} advanced reference guide code examples`.trim());
646
+ }
647
+ }
648
+ return fallbackQueries.filter((q) => !executedQueries.has(q.toLowerCase())).slice(0, maxQueries);
649
+ }
650
+ /**
651
+ * Executes active harvesters in parallel and stores results in the Out-of-Band `EvidenceLedger`.
652
+ */
653
+ async executeHarvestRound(params) {
654
+ const { round, queries, contract, preset, domain, recencyDays, maxScrapePerRound, scrapedUrls, ledger } = params;
655
+ if (queries.length === 0) return;
656
+ const tasks = [];
657
+ if (preset.enableWeb) {
658
+ tasks.push(
659
+ (async () => {
660
+ const candidateHits = [];
661
+ for (const q of queries) {
662
+ try {
663
+ const hits = await this.searchEngine.search(q, { limit: 3 });
664
+ for (const h of hits) {
665
+ if (!isCommercialOrNoise({ url: h.url, title: h.title, snippet: h.content })) {
666
+ if (!candidateHits.some((existing) => existing.url === h.url)) {
667
+ candidateHits.push(h);
668
+ }
669
+ }
670
+ }
671
+ } catch {
672
+ }
673
+ }
674
+ const urlsToScrape = candidateHits.filter((h) => !scrapedUrls.has(h.url)).slice(0, maxScrapePerRound);
675
+ await Promise.allSettled(
676
+ urlsToScrape.map(async (hit) => {
677
+ scrapedUrls.add(hit.url);
678
+ try {
679
+ const doc = await this.webScraper.scrapeUrl(hit.url);
680
+ const health = this.healthAuditor.auditDocument(doc);
681
+ if (health.passed && doc.markdownContent.trim().length > 80) {
682
+ const scored = this.evidenceScorer.scoreDocument(doc, domain, contract.objective);
683
+ ledger.addScrapedDocument(doc, scored.score, scored.keyTakeaways);
684
+ return;
685
+ }
686
+ } catch {
687
+ }
688
+ if (hit.content && hit.content.trim().length > 30) {
689
+ ledger.addSearchHit(hit, 6);
690
+ }
691
+ })
692
+ );
693
+ for (const hit of candidateHits.slice(maxScrapePerRound, maxScrapePerRound + 2)) {
694
+ if (hit.content && hit.content.trim().length > 40) {
695
+ ledger.addSearchHit(hit, 6);
696
+ }
697
+ }
698
+ })()
699
+ );
700
+ }
701
+ if (preset.enableAcademic && round === 1) {
702
+ tasks.push(
703
+ (async () => {
704
+ try {
705
+ const primaryQuery = queries[0] || contract.objective;
706
+ const [s2Papers, oaPapers] = await Promise.all([
707
+ this.academicEngine.searchPapers(primaryQuery, { limit: 3 }),
708
+ this.openAlexClient.searchWorks(primaryQuery, { limit: 3 })
709
+ ]);
710
+ for (const p of [...s2Papers, ...oaPapers].slice(0, 5)) {
711
+ ledger.addAcademicPaper(p);
712
+ }
713
+ } catch (e) {
714
+ console.warn("[ResearchSubAgent] Academic harvest error:", e?.message || e);
715
+ }
716
+ })()
717
+ );
718
+ }
719
+ if (preset.enableSocialPulse && round === 1) {
720
+ tasks.push(
721
+ (async () => {
722
+ try {
723
+ const pulseReport = await this.socialPulseHarvester.harvest(contract.objective, {
724
+ recencyDays,
725
+ limitPerPlatform: 3
726
+ });
727
+ for (const item of pulseReport.items.slice(0, 5)) {
728
+ ledger.addSocialPulseItem(item);
729
+ }
730
+ } catch (e) {
731
+ console.warn("[ResearchSubAgent] Social pulse harvest error:", e?.message || e);
732
+ }
733
+ })()
734
+ );
735
+ }
736
+ if (preset.enableStemOer && round === 1) {
737
+ tasks.push(
738
+ (async () => {
739
+ try {
740
+ const oerCatalog = await this.stemResearcher.findResources(contract.objective, {
741
+ limit: 4
742
+ });
743
+ for (const res of oerCatalog.resources.slice(0, 4)) {
744
+ ledger.addStemResource({
745
+ title: res.title,
746
+ url: res.url,
747
+ description: res.description,
748
+ provider: res.provider,
749
+ license: res.license?.type
750
+ });
751
+ }
752
+ } catch (e) {
753
+ console.warn("[ResearchSubAgent] STEM OER harvest error:", e?.message || e);
754
+ }
755
+ })()
756
+ );
757
+ }
758
+ await Promise.allSettled(tasks);
759
+ }
760
+ /**
761
+ * Evaluates whether the current `EvidenceLedger` satisfies `acceptanceCriteria`,
762
+ * `requiredAttributes`, and `requiredSections`.
763
+ */
764
+ async evaluateRoundGaps(params) {
765
+ const { contract, ledger, minSources, minRelevanceScore, llm } = params;
766
+ const missingGaps = [];
767
+ const satisfiedAttributes = [];
768
+ const approved = ledger.getApprovedItems(minRelevanceScore);
769
+ if (approved.length < minSources) {
770
+ missingGaps.push(`Need at least ${minSources} verified sources with score >= ${minRelevanceScore} (currently ${approved.length})`);
771
+ } else {
772
+ satisfiedAttributes.push(`minSources(${approved.length}/${minSources})`);
773
+ }
774
+ if (contract.acceptanceCriteria?.requireCodeExamples && ledger.getTotalCodeBlocks() === 0) {
775
+ missingGaps.push("Missing verified code examples / syntax snippets");
776
+ } else if (contract.acceptanceCriteria?.requireCodeExamples) {
777
+ satisfiedAttributes.push(`codeExamples(${ledger.getTotalCodeBlocks()})`);
778
+ }
779
+ if (contract.acceptanceCriteria?.requireTables && ledger.getTotalTables() === 0) {
780
+ missingGaps.push("Missing specification or pinout markdown tables");
781
+ } else if (contract.acceptanceCriteria?.requireTables) {
782
+ satisfiedAttributes.push(`tables(${ledger.getTotalTables()})`);
783
+ }
784
+ const targetCheckList = [
785
+ ...contract.acceptanceCriteria?.requiredAttributes || [],
786
+ ...contract.requiredSections || []
787
+ ];
788
+ if (targetCheckList.length > 0) {
789
+ const receipts = ledger.getReceipts();
790
+ if (receipts.length === 0) {
791
+ missingGaps.push(...targetCheckList);
792
+ } else if (llm) {
793
+ try {
794
+ const prompt = [
795
+ `Evaluate which of the required attributes/sections are covered by the collected Citation Receipts for "${contract.objective}".`,
796
+ `Required Items: ${JSON.stringify(targetCheckList)}`,
797
+ `Collected Citation Receipts:
798
+ ${receipts.map((r) => `- [${r.id}] ${r.title} (headings: ${r.headings.join(", ")}): ${r.briefExcerpt}`).join("\n")}`,
799
+ `Return ONLY a JSON object: {"satisfied": ["item1"], "missing": ["item2"]}`
800
+ ].join("\n");
801
+ const raw = await llm(prompt, {
802
+ system: 'Output strictly valid JSON object with "satisfied" and "missing" string arrays.',
803
+ temperature: 0.1,
804
+ jsonMode: true
805
+ });
806
+ const match = raw.match(/\{[\s\S]*\}/);
807
+ if (match) {
808
+ const parsed = JSON.parse(match[0]);
809
+ if (Array.isArray(parsed.satisfied)) {
810
+ satisfiedAttributes.push(...parsed.satisfied.map(String));
811
+ }
812
+ if (Array.isArray(parsed.missing)) {
813
+ missingGaps.push(...parsed.missing.map(String));
814
+ }
815
+ return { satisfiedAttributes, missingGaps };
816
+ }
817
+ } catch {
818
+ }
819
+ }
820
+ const lowerCorpus = ledger.buildFullRawCorpus().toLowerCase();
821
+ for (const reqItem of targetCheckList) {
822
+ const tokens = reqItem.toLowerCase().replace(/[^a-z0-9\u00C0-\u1EF9]+/g, " ").split(/\s+/).filter((t) => t.length >= 3);
823
+ const matched = tokens.filter((t) => lowerCorpus.includes(t)).length;
824
+ if (tokens.length === 0 || matched / tokens.length >= 0.5) {
825
+ satisfiedAttributes.push(reqItem);
826
+ } else {
827
+ missingGaps.push(reqItem);
828
+ }
829
+ }
830
+ }
831
+ return { satisfiedAttributes, missingGaps };
832
+ }
833
+ /**
834
+ * Stage B: Synthesizes `EvidenceLedger` excerpts into `outputSchema<T>` + `markdownReport`
835
+ * and runs deterministic schema, citation, and claim verification gates.
836
+ */
837
+ async synthesizeAndVerify(params) {
838
+ const { contract, profile, ledger, approvedCount, minSources, missingGaps, roundTraces, provenanceMd, llm } = params;
839
+ const synthesisCorpus = ledger.buildSynthesisCorpus(12);
840
+ const items = ledger.getItems();
841
+ const receipts = ledger.getReceipts();
842
+ let synthesizedData = null;
843
+ let markdownReport = "";
844
+ let tier1Summary = "";
845
+ let tier2TechnicalDigest = "";
846
+ let keyClaims = [];
847
+ let isLlmSynthesized = false;
848
+ const schemaHint = contract.outputSchemaDescription || describeZodSchemaKeys(contract.outputSchema) || "JSON object capturing the key structured findings, technical constraints, exemplars, and citations";
849
+ if (llm) {
850
+ try {
851
+ 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";
852
+ const prompt = [
853
+ `You are a Principal Research Synthesizer. Synthesize the verified EvidenceLedger sources below to fulfill the Research Contract.`,
854
+ `Objective: "${contract.objective}"`,
855
+ `Profile: ${profile}`,
856
+ contract.context?.ageBand ? `Learner Age Band: ${contract.context.ageBand[0]}-${contract.context.ageBand[1]}` : "",
857
+ contract.context?.hardwarePlatform ? `Hardware Platform: ${contract.context.hardwarePlatform}` : "",
858
+ contract.context?.softwareEnv ? `Software/Tools: ${contract.context.softwareEnv}` : "",
859
+ `Required Markdown Sections: ${requiredSectionsText}`,
860
+ `Required Structured "data" Payload Format: ${schemaHint}`,
861
+ contract.acceptanceCriteria?.forbiddenTerms?.length ? `Forbidden Terms (MUST NOT APPEAR): ${contract.acceptanceCriteria.forbiddenTerms.join(", ")}` : "",
862
+ `
863
+ CRITICAL GROUNDING RULES:`,
864
+ `1. Every claim, metric, pinout, or recommendation MUST cite its EvidenceLedger ID in brackets, e.g. [RES-01], [RES-02].`,
865
+ `2. NEVER invent citation IDs outside [RES-01]..[RES-${String(items.length).padStart(2, "0")}].`,
866
+ `3. If evidence for a specific attribute is missing from the ledger, state that explicitly rather than fabricating facts.`,
867
+ `
868
+ === VERIFIED EVIDENCE LEDGER ===
869
+ ${synthesisCorpus}`,
870
+ `
871
+ Return ONLY a valid JSON object with the exact envelope:`,
872
+ `{`,
873
+ ` "data": { ...structured payload matching the Required Structured "data" Payload Format... },`,
874
+ ` "markdownReport": "# Full Markdown Report with [RES-xx] citations and Required Markdown Sections...",`,
875
+ ` "tier1Summary": "Concise <=200-word executive summary with [RES-xx] citations",`,
876
+ ` "tier2TechnicalDigest": "Bulleted technical digest (<=600 words) preserving concrete APIs, specs, code/tables, and pitfalls with [RES-xx] tags",`,
877
+ ` "keyClaims": ["Core factual claim 1 from report", "Core factual claim 2"]`,
878
+ `}`
879
+ ].filter(Boolean).join("\n");
880
+ const raw = await llm(prompt, {
881
+ system: "Output strictly valid JSON matching the requested synthesis envelope. Ground every claim in [RES-xx].",
882
+ temperature: 0.2,
883
+ jsonMode: true
884
+ });
885
+ const match = raw.match(/\{[\s\S]*\}/);
886
+ if (match) {
887
+ const parsed = JSON.parse(match[0]);
888
+ markdownReport = typeof parsed.markdownReport === "string" ? parsed.markdownReport : "";
889
+ tier1Summary = typeof parsed.tier1Summary === "string" ? parsed.tier1Summary : "";
890
+ tier2TechnicalDigest = typeof parsed.tier2TechnicalDigest === "string" ? parsed.tier2TechnicalDigest : "";
891
+ keyClaims = Array.isArray(parsed.keyClaims) ? parsed.keyClaims.map(String) : [];
892
+ const candidateData = parsed.data !== void 0 ? parsed.data : parsed;
893
+ if (contract.outputSchema) {
894
+ const validation = contract.outputSchema.safeParse(candidateData);
895
+ if (validation.success) {
896
+ synthesizedData = validation.data;
897
+ isLlmSynthesized = true;
898
+ } else {
899
+ const issuesText = validation.error.issues.map((iss) => `${iss.path.join(".") || "root"}: ${iss.message}`).join("; ");
900
+ const repairPrompt = [
901
+ `The synthesized "data" object failed Zod schema validation with issues: ${issuesText}`,
902
+ `Schema requirement: ${schemaHint}`,
903
+ `Original candidate data: ${JSON.stringify(candidateData)}`,
904
+ `Repair and return ONLY the valid JSON object for "data" grounded strictly in the EvidenceLedger.`
905
+ ].join("\n");
906
+ const repairedRaw = await llm(repairPrompt, {
907
+ system: "Return strictly valid JSON object matching the schema.",
908
+ temperature: 0.1,
909
+ jsonMode: true
910
+ });
911
+ const repMatch = repairedRaw.match(/\{[\s\S]*\}/);
912
+ if (repMatch) {
913
+ const repParsed = JSON.parse(repMatch[0]);
914
+ const repCheck = contract.outputSchema.safeParse(repParsed);
915
+ if (repCheck.success) {
916
+ synthesizedData = repCheck.data;
917
+ isLlmSynthesized = true;
918
+ } else {
919
+ missingGaps.push(`Output schema validation incomplete: ${issuesText}`);
920
+ }
921
+ }
922
+ }
923
+ } else {
924
+ synthesizedData = candidateData;
925
+ isLlmSynthesized = true;
926
+ }
927
+ }
928
+ } catch (e) {
929
+ console.warn("[ResearchSubAgent] Stage B LLM synthesis error, falling back to deterministic ledger compilation:", e?.message || e);
930
+ }
931
+ }
932
+ if (!markdownReport) {
933
+ markdownReport = this.buildDeterministicMarkdownReport(contract.objective, profile, items, contract.requiredSections);
934
+ }
935
+ if (!tier1Summary) {
936
+ tier1Summary = items.slice(0, 3).map((i) => `[${i.id}] ${i.title}: ${i.keyExcerpts[0] || ""}`).join(" ");
937
+ }
938
+ if (!tier2TechnicalDigest) {
939
+ tier2TechnicalDigest = items.slice(0, 6).map((i) => `- **[${i.id}] ${i.title}** (${i.url}): ${i.keyExcerpts.slice(0, 2).join(" ")}`).join("\n");
940
+ }
941
+ if (synthesizedData === null && !contract.outputSchema) {
942
+ synthesizedData = {
943
+ objective: contract.objective,
944
+ profile,
945
+ sources: receipts,
946
+ codeSnippets: items.flatMap((i) => i.codeBlocks).slice(0, 4),
947
+ tables: items.flatMap((i) => i.tables).slice(0, 4)
948
+ };
949
+ }
950
+ const combinedText = `${markdownReport}
951
+ ${tier1Summary}
952
+ ${tier2TechnicalDigest}
953
+ ${JSON.stringify(synthesizedData || {})}`;
954
+ const { validCitationIds, invalidCitationIds } = ledger.verifyCitationTags(combinedText);
955
+ if (invalidCitationIds.length > 0) {
956
+ for (const badId of invalidCitationIds) {
957
+ const regex = new RegExp(`\\[?${badId}\\]?`, "gi");
958
+ markdownReport = markdownReport.replace(regex, "[UNVERIFIED-CITATION-REMOVED]");
959
+ tier1Summary = tier1Summary.replace(regex, "");
960
+ tier2TechnicalDigest = tier2TechnicalDigest.replace(regex, "");
961
+ }
962
+ }
963
+ if (contract.acceptanceCriteria?.forbiddenTerms?.length) {
964
+ const lowerReport = markdownReport.toLowerCase();
965
+ for (const forbidden of contract.acceptanceCriteria.forbiddenTerms) {
966
+ if (lowerReport.includes(forbidden.toLowerCase())) {
967
+ missingGaps.push(`Forbidden term detected in output: "${forbidden}"`);
968
+ }
969
+ }
970
+ }
971
+ const claimsToVerify = keyClaims.length > 0 ? keyClaims : items.slice(0, 4).map((i) => i.keyExcerpts[0]).filter((e) => Boolean(e && e.length > 25));
972
+ const claimVerification = claimsToVerify.length > 0 ? this.claimVerifier.verifyClaimsDeterministic(claimsToVerify, ledger.buildFullRawCorpus()) : void 0;
973
+ let status = "success";
974
+ if (!isLlmSynthesized && llm) {
975
+ status = "degraded";
976
+ } else if (missingGaps.length > 0 || approvedCount < minSources || contract.outputSchema && synthesizedData === null) {
977
+ status = "partial";
978
+ } else if (!llm) {
979
+ status = contract.outputSchema && synthesizedData === null ? "degraded" : "success";
980
+ }
981
+ return {
982
+ status,
983
+ objective: contract.objective,
984
+ profile,
985
+ roundsExecuted: roundTraces.length,
986
+ data: synthesizedData,
987
+ markdownReport,
988
+ tier1Summary: tier1Summary.slice(0, 1800),
989
+ tier2TechnicalDigest: tier2TechnicalDigest.slice(0, 4e3),
990
+ ledgerItems: items,
991
+ receipts,
992
+ validCitationIds,
993
+ invalidCitationIds,
994
+ missingGaps: Array.from(new Set(missingGaps)),
995
+ roundTraces,
996
+ claimVerification,
997
+ provenanceMd
998
+ };
999
+ }
1000
+ buildDeterministicMarkdownReport(objective, profile, items, requiredSections) {
1001
+ const lines = [
1002
+ `# \u{1F52C} Autonomous Research Dossier: ${objective}`,
1003
+ `> **Profile:** \`${profile.toUpperCase()}\` | **Verified Ledger Sources:** \`${items.length}\``
1004
+ ];
1005
+ if (requiredSections && requiredSections.length > 0) {
1006
+ for (const section of requiredSections) {
1007
+ lines.push(`
1008
+ ## ${section}`);
1009
+ for (const item of items.slice(0, 4)) {
1010
+ if (item.keyExcerpts[0]) {
1011
+ lines.push(`- **[${item.id}] ${item.title}**: ${item.keyExcerpts[0]}`);
1012
+ }
1013
+ }
1014
+ }
1015
+ } else {
1016
+ lines.push(`
1017
+ ## 1. Executive Summary & Verified Findings`);
1018
+ for (const item of items) {
1019
+ lines.push(
1020
+ `### [${item.id}] ${item.title} (${item.sourceType.toUpperCase()} \xB7 Score \`${item.relevanceScore}/10\`)`,
1021
+ `- **URL:** ${item.url}`,
1022
+ ...item.keyExcerpts.slice(0, 3).map((ex) => `- ${ex}`)
1023
+ );
1024
+ }
1025
+ }
1026
+ const allCode = items.flatMap((i) => i.codeBlocks.map((cb) => ({ id: i.id, ...cb }))).slice(0, 4);
1027
+ if (allCode.length > 0) {
1028
+ lines.push(
1029
+ `
1030
+ ## Extracted Code Examples`,
1031
+ ...allCode.map((c) => `From **[${c.id}]**:
1032
+ \`\`\`${c.language || "text"}
1033
+ ${c.code}
1034
+ \`\`\``)
1035
+ );
1036
+ }
1037
+ const allTables = items.flatMap((i) => i.tables.map((t) => ({ id: i.id, table: t }))).slice(0, 4);
1038
+ if (allTables.length > 0) {
1039
+ lines.push(
1040
+ `
1041
+ ## Extracted Specification Tables`,
1042
+ ...allTables.map((t) => `From **[${t.id}]**:
1043
+
1044
+ ${t.table}`)
1045
+ );
1046
+ }
1047
+ lines.push(
1048
+ `
1049
+ ## Evidence Ledger Citations`,
1050
+ ...items.map((i) => `- **[${i.id}]** [${i.title}](${i.url}) \u2014 *${i.sourceType}, score ${i.relevanceScore}/10*`)
1051
+ );
1052
+ return lines.join("\n");
1053
+ }
1054
+ };
1055
+ async function runResearchSubAgent(contract, config = {}) {
1056
+ const agent = new ResearchSubAgent(config);
1057
+ return agent.run(contract, { llm: config.llm });
1058
+ }
1059
+ var ResearchAgentToolInputSchema = z.object({
1060
+ objective: z.string().min(3).describe("The specific research question, topic, or technical requirement to investigate."),
1061
+ profile: 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."),
1062
+ requiredSections: z.array(z.string()).optional().describe("Optional list of required Markdown sections in the synthesized report."),
1063
+ requiredAttributes: z.array(z.string()).optional().describe("Optional list of specific technical attributes, specs, or sub-questions that must be verified."),
1064
+ requireCodeExamples: z.boolean().optional().describe("Set true if verified code examples are mandatory."),
1065
+ requireTables: z.boolean().optional().describe("Set true if pinout or specification tables are mandatory."),
1066
+ recencyDays: z.number().int().min(1).max(365).optional().describe("Recency window in days for social/community pulse."),
1067
+ maxRounds: z.number().int().min(1).max(4).optional().describe("Maximum Plan-Harvest-Evaluate rounds (1-4).")
1068
+ });
1069
+ function createResearchAgentTool(config = {}) {
1070
+ const subAgent = new ResearchSubAgent(config);
1071
+ return {
1072
+ name: "research_subagent",
1073
+ 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.",
1074
+ parameters: ResearchAgentToolInputSchema,
1075
+ inputSchema: ResearchAgentToolInputSchema,
1076
+ execute: async (input) => {
1077
+ const result = await subAgent.run({
1078
+ objective: input.objective,
1079
+ profile: input.profile,
1080
+ requiredSections: input.requiredSections,
1081
+ acceptanceCriteria: {
1082
+ requiredAttributes: input.requiredAttributes,
1083
+ requireCodeExamples: input.requireCodeExamples,
1084
+ requireTables: input.requireTables,
1085
+ recencyDays: input.recencyDays
1086
+ },
1087
+ budget: {
1088
+ maxRounds: input.maxRounds
1089
+ }
1090
+ });
1091
+ return {
1092
+ status: result.status,
1093
+ objective: result.objective,
1094
+ profile: result.profile,
1095
+ roundsExecuted: result.roundsExecuted,
1096
+ tier1Summary: result.tier1Summary,
1097
+ tier2TechnicalDigest: result.tier2TechnicalDigest,
1098
+ citations: result.receipts.map((r) => ({
1099
+ id: r.id,
1100
+ title: r.title,
1101
+ url: r.url,
1102
+ sourceType: r.sourceType,
1103
+ score: r.relevanceScore
1104
+ })),
1105
+ missingGaps: result.missingGaps,
1106
+ fullResult: result
1107
+ };
1108
+ }
1109
+ };
1110
+ }
1111
+
1112
+ export { EvidenceLedger, RESEARCH_PROFILE_PRESETS, ResearchAgentToolInputSchema, ResearchSubAgent, createResearchAgentTool, resolveResearchProfile, runResearchSubAgent };
1113
+ //# sourceMappingURL=chunk-WWQ45RQK.js.map
1114
+ //# sourceMappingURL=chunk-WWQ45RQK.js.map