@thanh01.pmt/research-kit 1.4.0 → 1.4.2

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 (62) hide show
  1. package/dist/academic/index.cjs +17 -16
  2. package/dist/academic/index.cjs.map +1 -1
  3. package/dist/academic/index.d.cts +1 -1
  4. package/dist/academic/index.d.ts +1 -1
  5. package/dist/academic/index.js +3 -3
  6. package/dist/agent/index.cjs +287 -126
  7. package/dist/agent/index.cjs.map +1 -1
  8. package/dist/agent/index.d.cts +4 -4
  9. package/dist/agent/index.d.ts +4 -4
  10. package/dist/agent/index.js +7 -7
  11. package/dist/{catalogBuilder-D-UiM37y.d.ts → catalogBuilder-BN3VwEsE.d.ts} +15 -2
  12. package/dist/{catalogBuilder-BBCa9jqI.d.cts → catalogBuilder-mba5BIHD.d.cts} +15 -2
  13. package/dist/{chunk-RYLZYZRF.js → chunk-5HSLUAM6.js} +11 -3
  14. package/dist/chunk-5HSLUAM6.js.map +1 -0
  15. package/dist/{chunk-RAMDHDRJ.js → chunk-6QW5TFDJ.js} +70 -342
  16. package/dist/chunk-6QW5TFDJ.js.map +1 -0
  17. package/dist/chunk-BPZLZKVJ.js +1012 -0
  18. package/dist/chunk-BPZLZKVJ.js.map +1 -0
  19. package/dist/{chunk-AKEI7H2C.js → chunk-EWIAA2CC.js} +4 -4
  20. package/dist/{chunk-AKEI7H2C.js.map → chunk-EWIAA2CC.js.map} +1 -1
  21. package/dist/{chunk-QQZQNBJC.js → chunk-JV6Z6WUQ.js} +4 -4
  22. package/dist/{chunk-QQZQNBJC.js.map → chunk-JV6Z6WUQ.js.map} +1 -1
  23. package/dist/{chunk-4O3FXMXO.js → chunk-LTXXARCA.js} +5 -5
  24. package/dist/{chunk-4O3FXMXO.js.map → chunk-LTXXARCA.js.map} +1 -1
  25. package/dist/{chunk-UHKDJZNL.js → chunk-PFECHAAR.js} +3 -3
  26. package/dist/{chunk-UHKDJZNL.js.map → chunk-PFECHAAR.js.map} +1 -1
  27. package/dist/{chunk-MFRQ2VJZ.js → chunk-QLBHTCV6.js} +98 -38
  28. package/dist/chunk-QLBHTCV6.js.map +1 -0
  29. package/dist/{chunk-SDDZFFL6.js → chunk-SB7WYK7A.js} +15 -14
  30. package/dist/chunk-SB7WYK7A.js.map +1 -0
  31. package/dist/{chunk-SHBDLP64.js → chunk-SEHHDO7X.js} +5 -5
  32. package/dist/{chunk-SHBDLP64.js.map → chunk-SEHHDO7X.js.map} +1 -1
  33. package/dist/evidence/index.cjs.map +1 -1
  34. package/dist/evidence/index.js +2 -2
  35. package/dist/harvester/index.cjs +225 -92
  36. package/dist/harvester/index.cjs.map +1 -1
  37. package/dist/harvester/index.d.cts +2 -2
  38. package/dist/harvester/index.d.ts +2 -2
  39. package/dist/harvester/index.js +5 -5
  40. package/dist/{index-CGa7lf3L.d.ts → index-9Z-uMwdI.d.ts} +13 -5
  41. package/dist/{index-DrjfrbGw.d.cts → index-eTcF4XVo.d.cts} +13 -5
  42. package/dist/index.cjs +2578 -2348
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.d.cts +5 -5
  45. package/dist/index.d.ts +5 -5
  46. package/dist/index.js +19 -19
  47. package/dist/{literatureReview-Bvlqk4DB.d.cts → literatureReview-BUtPL7bj.d.cts} +1 -0
  48. package/dist/{literatureReview-Bn2iEGRO.d.ts → literatureReview-CHz-JfSR.d.ts} +1 -0
  49. package/dist/pipeline/index.cjs +326 -132
  50. package/dist/pipeline/index.cjs.map +1 -1
  51. package/dist/pipeline/index.d.cts +15 -3
  52. package/dist/pipeline/index.d.ts +15 -3
  53. package/dist/pipeline/index.js +7 -7
  54. package/dist/{socialPulseHarvester-CN4MwrpY.d.cts → socialPulseHarvester-BCFxGwx2.d.cts} +4 -1
  55. package/dist/{socialPulseHarvester-IbdT3zD1.d.ts → socialPulseHarvester-DjMvBufT.d.ts} +4 -1
  56. package/package.json +1 -1
  57. package/dist/chunk-2RMBLKP5.js +0 -581
  58. package/dist/chunk-2RMBLKP5.js.map +0 -1
  59. package/dist/chunk-MFRQ2VJZ.js.map +0 -1
  60. package/dist/chunk-RAMDHDRJ.js.map +0 -1
  61. package/dist/chunk-RYLZYZRF.js.map +0 -1
  62. package/dist/chunk-SDDZFFL6.js.map +0 -1
@@ -1,17 +1,17 @@
1
- import { OpenAlexClient } from './chunk-SHBDLP64.js';
2
- import { SocialPulseHarvester, StemResourceResearcher } from './chunk-4O3FXMXO.js';
1
+ import { OpenAlexClient } from './chunk-SEHHDO7X.js';
2
+ import { SocialPulseHarvester, StemResourceResearcher } from './chunk-LTXXARCA.js';
3
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, extractTopSentences } from './chunk-UHKDJZNL.js';
7
- import { WebScraper, YouTubeIngestionService } from './chunk-QQZQNBJC.js';
4
+ import { MultiSourceSearchEngine, HealthAuditor, classifyTechnicalDomain, EvidenceLedger, isCommercialOrNoise } from './chunk-BPZLZKVJ.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
8
  import { z } from 'zod';
9
9
 
10
10
  // src/agent/types.ts
11
11
  var RESEARCH_MODE_PRESETS = {
12
12
  search: {
13
13
  mode: "search",
14
- timeoutMs: 8e3,
14
+ timeoutMs: 15e3,
15
15
  maxChannels: 1,
16
16
  channelConcurrency: 1,
17
17
  maxRounds: 1,
@@ -21,7 +21,7 @@ var RESEARCH_MODE_PRESETS = {
21
21
  },
22
22
  research: {
23
23
  mode: "research",
24
- timeoutMs: 9e4,
24
+ timeoutMs: 18e4,
25
25
  maxChannels: 2,
26
26
  channelConcurrency: 2,
27
27
  maxRounds: 1,
@@ -31,7 +31,7 @@ var RESEARCH_MODE_PRESETS = {
31
31
  },
32
32
  "deep-research": {
33
33
  mode: "deep-research",
34
- timeoutMs: 3e5,
34
+ timeoutMs: 6e5,
35
35
  maxChannels: 5,
36
36
  channelConcurrency: 2,
37
37
  maxRounds: 3,
@@ -45,7 +45,7 @@ var RESEARCH_PROFILE_PRESETS = {
45
45
  maxRounds: 1,
46
46
  maxQueriesPerRound: 3,
47
47
  maxScrapePerRound: 3,
48
- timeoutMs: 9e4,
48
+ timeoutMs: 18e4,
49
49
  enableWeb: true,
50
50
  enableAcademic: false,
51
51
  enableSocialPulse: false,
@@ -55,7 +55,7 @@ var RESEARCH_PROFILE_PRESETS = {
55
55
  maxRounds: 3,
56
56
  maxQueriesPerRound: 4,
57
57
  maxScrapePerRound: 4,
58
- timeoutMs: 3e5,
58
+ timeoutMs: 6e5,
59
59
  enableWeb: true,
60
60
  enableAcademic: true,
61
61
  enableSocialPulse: true,
@@ -65,7 +65,7 @@ var RESEARCH_PROFILE_PRESETS = {
65
65
  maxRounds: 1,
66
66
  maxQueriesPerRound: 3,
67
67
  maxScrapePerRound: 3,
68
- timeoutMs: 9e4,
68
+ timeoutMs: 18e4,
69
69
  enableWeb: true,
70
70
  enableAcademic: false,
71
71
  enableSocialPulse: true,
@@ -75,7 +75,7 @@ var RESEARCH_PROFILE_PRESETS = {
75
75
  maxRounds: 1,
76
76
  maxQueriesPerRound: 3,
77
77
  maxScrapePerRound: 2,
78
- timeoutMs: 9e4,
78
+ timeoutMs: 18e4,
79
79
  enableWeb: true,
80
80
  enableAcademic: true,
81
81
  enableSocialPulse: false,
@@ -85,7 +85,7 @@ var RESEARCH_PROFILE_PRESETS = {
85
85
  maxRounds: 1,
86
86
  maxQueriesPerRound: 3,
87
87
  maxScrapePerRound: 2,
88
- timeoutMs: 9e4,
88
+ timeoutMs: 18e4,
89
89
  enableWeb: true,
90
90
  enableAcademic: false,
91
91
  enableSocialPulse: true,
@@ -95,7 +95,7 @@ var RESEARCH_PROFILE_PRESETS = {
95
95
  maxRounds: 1,
96
96
  maxQueriesPerRound: 3,
97
97
  maxScrapePerRound: 3,
98
- timeoutMs: 9e4,
98
+ timeoutMs: 18e4,
99
99
  enableWeb: true,
100
100
  enableAcademic: false,
101
101
  enableSocialPulse: false,
@@ -105,7 +105,7 @@ var RESEARCH_PROFILE_PRESETS = {
105
105
  maxRounds: 1,
106
106
  maxQueriesPerRound: 3,
107
107
  maxScrapePerRound: 3,
108
- timeoutMs: 9e4,
108
+ timeoutMs: 18e4,
109
109
  enableWeb: true,
110
110
  enableAcademic: false,
111
111
  enableSocialPulse: false,
@@ -113,308 +113,6 @@ var RESEARCH_PROFILE_PRESETS = {
113
113
  }
114
114
  };
115
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
116
  // src/agent/decisionRouter.ts
419
117
  var QUESTION_FACETS = [
420
118
  "official_spec",
@@ -738,7 +436,7 @@ ${receiptsText}`,
738
436
  const missing = [];
739
437
  targetCheckList.forEach((attr, idx) => {
740
438
  const ans = res.answers[`attr_${idx}`];
741
- if (ans && ans.type === "noul" && ans.probability >= 0.55) {
439
+ if (ans && (ans.type === "noul" && ans.probability >= 0.55 || ans.passed === true || ans.choice === "yes")) {
742
440
  satisfied.push(attr);
743
441
  } else {
744
442
  missing.push(attr);
@@ -863,6 +561,28 @@ function describeZodSchemaKeys(schema) {
863
561
  }
864
562
  return void 0;
865
563
  }
564
+ function extractJsonEnvelope(raw) {
565
+ if (!raw || typeof raw !== "string") return null;
566
+ const trimmed = raw.trim();
567
+ const unFenced = trimmed.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
568
+ try {
569
+ JSON.parse(unFenced);
570
+ return unFenced;
571
+ } catch {
572
+ }
573
+ const start = unFenced.indexOf("{");
574
+ const end = unFenced.lastIndexOf("}");
575
+ if (start !== -1 && end > start) {
576
+ const slice = unFenced.slice(start, end + 1);
577
+ try {
578
+ JSON.parse(slice);
579
+ return slice;
580
+ } catch {
581
+ return slice;
582
+ }
583
+ }
584
+ return null;
585
+ }
866
586
  function resolveResearchProfile(contract) {
867
587
  if (contract.profile && contract.profile !== "auto") {
868
588
  return contract.profile;
@@ -1271,25 +991,23 @@ ${currentMissingGaps.length > 0 ? currentMissingGaps.map((g) => `- ${g}`).join("
1271
991
  if (hit.content && hit.content.trim().length > 35) {
1272
992
  const hitScore = computeNativeHitScore(hit, 7, 6);
1273
993
  ledger.addSearchHit(hit, hitScore);
1274
- substantiveBytes += Math.max(
1275
- maxScrapePerRound === 0 ? 500 : 100,
1276
- Buffer.byteLength(hit.content, "utf-8")
1277
- );
994
+ substantiveBytes += Buffer.byteLength(hit.content, "utf-8");
1278
995
  }
1279
996
  }
1280
997
  } 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)) {
998
+ const targetQueries = queries.length > 0 ? queries.slice(0, 2) : [contract.objective];
999
+ const paperLists = await Promise.all(
1000
+ targetQueries.map((q) => this.academicEngine.searchPapers(q, { limit: 3 }).catch(() => []))
1001
+ );
1002
+ const collectedPapers = paperLists.flat();
1003
+ for (const p of collectedPapers.slice(0, 5)) {
1287
1004
  const receipt = ledger.addAcademicPaper(p);
1288
1005
  const item = ledger.getById(receipt.id);
1289
1006
  substantiveBytes += Math.max(850, item?.rawByteSize || 0);
1290
1007
  }
1291
1008
  } else if (channel === "social_pulse") {
1292
- const pulseReport = await this.socialPulseHarvester.harvest(contract.objective, {
1009
+ const pulseQuery = queries[0] || contract.objective;
1010
+ const pulseReport = await this.socialPulseHarvester.harvest(pulseQuery, {
1293
1011
  recencyDays,
1294
1012
  limitPerPlatform: 3
1295
1013
  });
@@ -1298,7 +1016,8 @@ ${currentMissingGaps.length > 0 ? currentMissingGaps.map((g) => `- ${g}`).join("
1298
1016
  substantiveBytes += Math.max(450, Buffer.byteLength(item.snippet || "", "utf-8"));
1299
1017
  }
1300
1018
  } else if (channel === "stem_oer") {
1301
- const oerCatalog = await this.stemResearcher.findResources(contract.objective, {
1019
+ const oerQuery = queries[0] || contract.objective;
1020
+ const oerCatalog = await this.stemResearcher.findResources(oerQuery, {
1302
1021
  limit: 4
1303
1022
  });
1304
1023
  for (const res of oerCatalog.resources.slice(0, 4)) {
@@ -1495,7 +1214,9 @@ Generate ${maxQueries} high-precision search queries to fulfill ${round === 1 ?
1495
1214
  if (receipts.length === 0) {
1496
1215
  missingGaps.push(...targetCheckList);
1497
1216
  } else {
1498
- const receiptsText = receipts.map((r) => `- [${r.id}] ${r.title} (headings: ${r.headings.join(", ")}): ${r.briefExcerpt}`).join("\n");
1217
+ const receiptsText = receipts.map(
1218
+ (r) => `- [${r.id}] ${r.title} (headings: ${r.headings.join(", ") || "N/A"}, codeBlocks: ${r.codeBlockCount}, tables: ${r.tableCount}): ${r.briefExcerpt}`
1219
+ ).join("\n");
1499
1220
  if (decision) {
1500
1221
  const decEval = await evaluateAttributeCoverageWithDecision({
1501
1222
  objective: contract.objective,
@@ -1564,7 +1285,7 @@ ${receiptsText}`,
1564
1285
  const detBaseline = this.claimVerifier.verifyClaimsDeterministic(claims, sourceCorpus);
1565
1286
  const res = await options.decision({
1566
1287
  context: `Verified Evidence Corpus:
1567
- ${sourceCorpus.slice(0, 6e3)}`,
1288
+ ${sourceCorpus.slice(0, 24e3)}`,
1568
1289
  questions: claims.map((claim, idx) => ({
1569
1290
  id: `claim_${idx}`,
1570
1291
  type: "choice",
@@ -1675,9 +1396,9 @@ Return ONLY a valid JSON object with the exact envelope:`,
1675
1396
  temperature: 0.2,
1676
1397
  jsonMode: true
1677
1398
  });
1678
- const match = raw.match(/\{[\s\S]*\}/);
1679
- if (match) {
1680
- const parsed = JSON.parse(match[0]);
1399
+ const jsonCandidate = extractJsonEnvelope(raw);
1400
+ if (jsonCandidate) {
1401
+ const parsed = JSON.parse(jsonCandidate);
1681
1402
  markdownReport = typeof parsed.markdownReport === "string" ? parsed.markdownReport : "";
1682
1403
  tier1Summary = typeof parsed.tier1Summary === "string" ? parsed.tier1Summary : "";
1683
1404
  tier2TechnicalDigest = typeof parsed.tier2TechnicalDigest === "string" ? parsed.tier2TechnicalDigest : "";
@@ -1701,9 +1422,9 @@ Return ONLY a valid JSON object with the exact envelope:`,
1701
1422
  temperature: 0.1,
1702
1423
  jsonMode: true
1703
1424
  });
1704
- const repMatch = repairedRaw.match(/\{[\s\S]*\}/);
1705
- if (repMatch) {
1706
- const repParsed = JSON.parse(repMatch[0]);
1425
+ const repCandidate = extractJsonEnvelope(repairedRaw);
1426
+ if (repCandidate) {
1427
+ const repParsed = JSON.parse(repCandidate);
1707
1428
  const repCheck = contract.outputSchema.safeParse(repParsed);
1708
1429
  if (repCheck.success) {
1709
1430
  synthesizedData = repCheck.data;
@@ -1752,6 +1473,13 @@ ${JSON.stringify(synthesizedData || {})}`;
1752
1473
  markdownReport = markdownReport.replace(regex, "[UNVERIFIED-CITATION-REMOVED]");
1753
1474
  tier1Summary = tier1Summary.replace(regex, "");
1754
1475
  tier2TechnicalDigest = tier2TechnicalDigest.replace(regex, "");
1476
+ if (synthesizedData) {
1477
+ try {
1478
+ const rawJson = JSON.stringify(synthesizedData);
1479
+ synthesizedData = JSON.parse(rawJson.replace(regex, ""));
1480
+ } catch {
1481
+ }
1482
+ }
1755
1483
  }
1756
1484
  }
1757
1485
  if (contract.acceptanceCriteria?.forbiddenTerms?.length) {
@@ -1926,6 +1654,6 @@ function createResearchAgentTool(config = {}) {
1926
1654
  };
1927
1655
  }
1928
1656
 
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-RAMDHDRJ.js.map
1931
- //# sourceMappingURL=chunk-RAMDHDRJ.js.map
1657
+ export { PRIOR_MATRIX, QUESTION_FACETS, RESEARCH_MODE_PRESETS, RESEARCH_PROFILE_PRESETS, ResearchAgentToolInputSchema, ResearchSubAgent, SOURCE_CHANNELS, classifyChannelStatus, classifyModeAndPrior, computeContractComplexityScore, createResearchAgentTool, evaluateAttributeCoverageWithDecision, extractJsonEnvelope, inferFallbackFacetProbabilities, isSemanticRankedHit, rankChannelsByExpectedPrior, resolveResearchProfile, runConcurrentRefillScheduler, runResearchSubAgent };
1658
+ //# sourceMappingURL=chunk-6QW5TFDJ.js.map
1659
+ //# sourceMappingURL=chunk-6QW5TFDJ.js.map