@claritylabs/cl-sdk 3.0.33 → 3.1.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.
package/dist/index.js CHANGED
@@ -28,8 +28,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
33
  ADMITTED_STATUSES: () => ADMITTED_STATUSES,
34
34
  AGENT_TOOLS: () => AGENT_TOOLS,
35
35
  APPLICATION_CLASSIFY_PROMPT: () => APPLICATION_CLASSIFY_PROMPT,
@@ -40,13 +40,21 @@ __export(index_exports, {
40
40
  AgenticExecutionModeSchema: () => AgenticExecutionModeSchema,
41
41
  AnswerParsingResultSchema: () => AnswerParsingResultSchema,
42
42
  ApplicationClassifyResultSchema: () => ApplicationClassifyResultSchema,
43
+ ApplicationContextProposalSchema: () => ApplicationContextProposalSchema,
43
44
  ApplicationEmailReviewSchema: () => ApplicationEmailReviewSchema,
44
45
  ApplicationFieldSchema: () => ApplicationFieldSchema,
46
+ ApplicationPacketAnswerSchema: () => ApplicationPacketAnswerSchema,
47
+ ApplicationPacketSchema: () => ApplicationPacketSchema,
45
48
  ApplicationQualityArtifactSchema: () => ApplicationQualityArtifactSchema,
46
49
  ApplicationQualityIssueSchema: () => ApplicationQualityIssueSchema,
47
50
  ApplicationQualityReportSchema: () => ApplicationQualityReportSchema,
48
51
  ApplicationQualityRoundSchema: () => ApplicationQualityRoundSchema,
52
+ ApplicationQuestionConditionSchema: () => ApplicationQuestionConditionSchema,
53
+ ApplicationQuestionGraphSchema: () => ApplicationQuestionGraphSchema,
54
+ ApplicationQuestionNodeSchema: () => ApplicationQuestionNodeSchema,
55
+ ApplicationRepeatSchema: () => ApplicationRepeatSchema,
49
56
  ApplicationStateSchema: () => ApplicationStateSchema,
57
+ ApplicationTemplateSchema: () => ApplicationTemplateSchema,
50
58
  AttachmentInterpretationSchema: () => AttachmentInterpretationSchema,
51
59
  AuditTypeSchema: () => AuditTypeSchema,
52
60
  AutoFillMatchSchema: () => AutoFillMatchSchema,
@@ -261,9 +269,11 @@ __export(index_exports, {
261
269
  VerifyResultSchema: () => VerifyResultSchema,
262
270
  WatercraftDeclarationsSchema: () => WatercraftDeclarationsSchema,
263
271
  WorkersCompDeclarationsSchema: () => WorkersCompDeclarationsSchema,
272
+ applyApplicationAnswers: () => applyApplicationAnswers,
264
273
  buildAcroFormMappingPrompt: () => buildAcroFormMappingPrompt,
265
274
  buildAgentSystemPrompt: () => buildAgentSystemPrompt,
266
275
  buildAnswerParsingPrompt: () => buildAnswerParsingPrompt,
276
+ buildApplicationPacket: () => buildApplicationPacket,
267
277
  buildAutoFillPrompt: () => buildAutoFillPrompt,
268
278
  buildBatchEmailGenerationPrompt: () => buildBatchEmailGenerationPrompt,
269
279
  buildClassifyMessagePrompt: () => buildClassifyMessagePrompt,
@@ -290,6 +300,7 @@ __export(index_exports, {
290
300
  buildPdfProviderOptions: () => buildPdfProviderOptions,
291
301
  buildQueryClassifyPrompt: () => buildQueryClassifyPrompt,
292
302
  buildQuestionBatchPrompt: () => buildQuestionBatchPrompt,
303
+ buildQuestionGraphFromFields: () => buildQuestionGraphFromFields,
293
304
  buildQuotesPoliciesPrompt: () => buildQuotesPoliciesPrompt,
294
305
  buildReasonPrompt: () => buildReasonPrompt,
295
306
  buildReplyIntentClassificationPrompt: () => buildReplyIntentClassificationPrompt,
@@ -305,6 +316,7 @@ __export(index_exports, {
305
316
  collectPceEvidenceSources: () => collectPceEvidenceSources,
306
317
  compareSourceEvidence: () => compareSourceEvidence,
307
318
  createApplicationPipeline: () => createApplicationPipeline,
319
+ createApplicationRun: () => createApplicationRun,
308
320
  createExtractor: () => createExtractor,
309
321
  createPceAgent: () => createPceAgent,
310
322
  createPipelineContext: () => createPipelineContext,
@@ -312,12 +324,16 @@ __export(index_exports, {
312
324
  evaluateCaseProposals: () => evaluateCaseProposals,
313
325
  evidenceContainsQuote: () => evidenceContainsQuote,
314
326
  extractPageRange: () => extractPageRange,
327
+ extractQuestionGraphFromFields: () => extractQuestionGraphFromFields,
315
328
  fillAcroForm: () => fillAcroForm,
329
+ flattenQuestionGraph: () => flattenQuestionGraph,
316
330
  generateNextMessage: () => generateNextMessage,
317
331
  getAcroFormFields: () => getAcroFormFields,
332
+ getActiveApplicationFields: () => getActiveApplicationFields,
318
333
  getDoclingPageRangeText: () => getDoclingPageRangeText,
319
334
  getExtractor: () => getExtractor,
320
335
  getFileIdentifier: () => getFileIdentifier,
336
+ getNextApplicationQuestions: () => getNextApplicationQuestions,
321
337
  getPdfPageCount: () => getPdfPageCount,
322
338
  getTemplate: () => getTemplate,
323
339
  isDoclingExtractionInput: () => isDoclingExtractionInput,
@@ -325,6 +341,7 @@ __export(index_exports, {
325
341
  mergeOperationalProfile: () => mergeOperationalProfile,
326
342
  mergeQuestionAnswers: () => mergeQuestionAnswers,
327
343
  mergeSourceSpans: () => mergeSourceSpans,
344
+ normalizeApplicationQuestionGraph: () => normalizeApplicationQuestionGraph,
328
345
  normalizeDoclingDocument: () => normalizeDoclingDocument,
329
346
  normalizeDocumentSourceTreePaths: () => normalizeDocumentSourceTreePaths,
330
347
  normalizeForMatch: () => normalizeForMatch,
@@ -334,7 +351,9 @@ __export(index_exports, {
334
351
  pLimit: () => pLimit,
335
352
  pdfInputToBase64: () => pdfInputToBase64,
336
353
  pdfInputToBytes: () => pdfInputToBytes,
354
+ planNextApplicationQuestions: () => planNextApplicationQuestions,
337
355
  processReply: () => processReply,
356
+ proposeContextWrites: () => proposeContextWrites,
338
357
  resolveModelBudget: () => resolveModelBudget,
339
358
  safeGenerateObject: () => safeGenerateObject,
340
359
  sanitizeNulls: () => sanitizeNulls,
@@ -347,12 +366,13 @@ __export(index_exports, {
347
366
  stableStringify: () => stableStringify,
348
367
  stripFences: () => stripFences,
349
368
  toStrictSchema: () => toStrictSchema,
369
+ validateApplicationPacket: () => validateApplicationPacket,
350
370
  validateEvidence: () => validateEvidence,
351
371
  validatePceItems: () => validatePceItems,
352
372
  validateQuotedEvidence: () => validateQuotedEvidence,
353
373
  withRetry: () => withRetry
354
374
  });
355
- module.exports = __toCommonJS(index_exports);
375
+ module.exports = __toCommonJS(src_exports);
356
376
 
357
377
  // src/core/retry.ts
358
378
  var MAX_RETRIES = 5;
@@ -3591,6 +3611,12 @@ function moneyAmount(value) {
3591
3611
  function normalizeLabel(value) {
3592
3612
  return normalizeWhitespace3(value ?? "").toLowerCase();
3593
3613
  }
3614
+ function isGenericColumnLabel(value) {
3615
+ return /^column\s+\d+$/i.test(cleanValue(value) ?? "");
3616
+ }
3617
+ function isHeaderRow(row) {
3618
+ return row.metadata?.isHeader === true || row.metadata?.isHeader === "true";
3619
+ }
3594
3620
  var OPERATIONAL_COVERAGE_TERM_KINDS = /* @__PURE__ */ new Set([
3595
3621
  "each_claim_limit",
3596
3622
  "each_occurrence_limit",
@@ -3611,6 +3637,7 @@ function termKind(label, value) {
3611
3637
  if (/\bpremium\b/.test(text)) return "premium";
3612
3638
  if (/\bsub[-\s]?limit\b/.test(text)) return "sublimit";
3613
3639
  if (/\baggregate\b/.test(text)) return "aggregate_limit";
3640
+ if (/\beach\s+proceeding|per\s+proceeding\b/.test(text)) return "sublimit";
3614
3641
  if (/\beach\s+claim|per\s+claim\b/.test(text)) return "each_claim_limit";
3615
3642
  if (/\beach\s+occurrence|per\s+occurrence\b/.test(text)) return "each_occurrence_limit";
3616
3643
  if (/\beach\s+loss|per\s+loss\b/.test(text)) return "each_loss_limit";
@@ -3637,9 +3664,13 @@ function isNameCell(label, value) {
3637
3664
  const normalizedLabel = normalizeLabel(label);
3638
3665
  const normalizedValue = normalizeLabel(value);
3639
3666
  if (!value || moneyAmount(value) !== void 0) return false;
3667
+ if (/^item\s+\d+[.)]?\s*limits?\s+of\s+liability\b/.test(normalizedValue)) return false;
3640
3668
  if (/\b(coverage|coverage part|insuring agreement|description|item|name)\b/.test(normalizedLabel)) {
3641
3669
  return true;
3642
3670
  }
3671
+ if (/\b(sub[-\s]?limit|aggregate(?:\s+policy)?\s+limit|limit\s+of\s+liability)\b/.test(normalizedLabel) && /\b[a-z][a-z0-9&/ -]{2,}\b/.test(normalizedValue) && !/\bcoverage\s+part\s+[a-z]\)?$/.test(normalizedValue)) {
3672
+ return true;
3673
+ }
3643
3674
  if (/^column\s+1$/.test(normalizedLabel) && !/^(item\s+\d+|nwc-|iso-|cg |il |form\b|page\b)/i.test(normalizedValue)) {
3644
3675
  return true;
3645
3676
  }
@@ -3658,13 +3689,32 @@ function childMap(nodes) {
3658
3689
  for (const group of children.values()) group.sort((left, right) => left.order - right.order);
3659
3690
  return children;
3660
3691
  }
3661
- function cellRows(row, children) {
3692
+ function rawCellRows(row, children) {
3662
3693
  return (children.get(row.id) ?? []).filter((child) => child.kind === "table_cell").map((cell) => ({
3663
3694
  label: cleanValue(cell.title) ?? "Value",
3664
3695
  value: cleanValue(cell.textExcerpt ?? cell.description ?? cell.title) ?? "",
3665
3696
  node: cell
3666
3697
  })).filter((cell) => cell.value);
3667
3698
  }
3699
+ function headerLabelsForRow(row, children) {
3700
+ if (!row.parentId) return [];
3701
+ const labels = [];
3702
+ const siblingRows = (children.get(row.parentId) ?? []).filter((candidate) => candidate.kind === "table_row" && candidate.order < row.order).sort((left, right) => left.order - right.order);
3703
+ for (const sibling of siblingRows) {
3704
+ if (!isHeaderRow(sibling)) continue;
3705
+ for (const [index, cell] of rawCellRows(sibling, children).entries()) {
3706
+ const label = cleanValue(cell.value) ?? cleanValue(cell.label);
3707
+ if (label && !isGenericColumnLabel(label)) labels[index] = label;
3708
+ }
3709
+ }
3710
+ return labels;
3711
+ }
3712
+ function cellRows(row, children, headerLabels = []) {
3713
+ return rawCellRows(row, children).map((cell, index) => ({
3714
+ ...cell,
3715
+ label: isGenericColumnLabel(cell.label) && headerLabels[index] ? headerLabels[index] : cell.label
3716
+ }));
3717
+ }
3668
3718
  function directChildren(parent, children) {
3669
3719
  return children.get(parent.id) ?? [];
3670
3720
  }
@@ -3717,8 +3767,9 @@ function relabelGenericTerm(term, label) {
3717
3767
  };
3718
3768
  }
3719
3769
  function termFromCell(params) {
3720
- const value = cleanValue(params.value);
3770
+ const value = cleanCoverageTermValue(params.value);
3721
3771
  if (!value) return void 0;
3772
+ if (isRejectedCoverageTermValue(params.label, value)) return void 0;
3722
3773
  const nodes = [params.row, params.cell].filter((node) => Boolean(node));
3723
3774
  const kind = termKind(params.label, value);
3724
3775
  const amount = moneyAmount(value);
@@ -3731,20 +3782,38 @@ function termFromCell(params) {
3731
3782
  ...sourceIds(nodes)
3732
3783
  };
3733
3784
  }
3785
+ function cleanCoverageTermValue(value) {
3786
+ return cleanValue(value)?.replace(/\s+\/\s*$/, "").trim();
3787
+ }
3788
+ function isRejectedCoverageTermValue(label, value) {
3789
+ if (/\bshown\s+in\s+item\s*\d+\b/i.test(value) && moneyAmount(value) === void 0) return true;
3790
+ if (/\b(does not afford coverage|doesn't afford coverage|no coverage|remains excluded|is excluded|are excluded|shall not cover|will not cover)\b/i.test(value) && moneyAmount(value) === void 0) {
3791
+ return true;
3792
+ }
3793
+ if (/^for:\s*\(\d+\)/i.test(label) && moneyAmount(value) === void 0) return true;
3794
+ if (value.length > 80 && /\b(exclusion|excluded|shall not|will not|does not|failure to)\b/i.test(value) && moneyAmount(value) === void 0) return true;
3795
+ return false;
3796
+ }
3734
3797
  function termsFromRow(row, children) {
3735
- const cells = cellRows(row, children);
3798
+ const cells = cellRows(row, children, headerLabelsForRow(row, children));
3736
3799
  if (cells.length > 0) {
3737
3800
  const pairedTerms = [];
3801
+ const pairedIndexes = /* @__PURE__ */ new Set();
3738
3802
  for (const [index, cell] of cells.entries()) {
3739
3803
  const next = cells[index + 1];
3740
3804
  if (!next) continue;
3805
+ if (!isGenericColumnLabel(cell.label) && isNameCell(cell.label, cell.value)) continue;
3741
3806
  if (!isCoverageTermLabel(cell.value)) continue;
3742
3807
  if (isCoverageTermLabel(next.value) && moneyAmount(next.value) === void 0) continue;
3743
3808
  const term = termFromCell({ row, cell: next.node, label: cell.value, value: next.value });
3744
- if (term) pairedTerms.push(term);
3809
+ if (term) {
3810
+ pairedTerms.push(term);
3811
+ pairedIndexes.add(index);
3812
+ pairedIndexes.add(index + 1);
3813
+ }
3745
3814
  }
3746
- if (pairedTerms.length > 0) return pairedTerms;
3747
- return cells.filter((cell) => isValueCell(cell.label, cell.value)).map((cell) => termFromCell({ row, cell: cell.node, label: cell.label, value: cell.value })).filter((term) => Boolean(term));
3815
+ const valueTerms = cells.filter((_, index) => !pairedIndexes.has(index)).filter((cell) => isValueCell(cell.label, cell.value)).map((cell) => termFromCell({ row, cell: cell.node, label: cell.label, value: cell.value })).filter((term) => Boolean(term));
3816
+ return [...pairedTerms, ...valueTerms];
3748
3817
  }
3749
3818
  const text = normalizeWhitespace3(row.textExcerpt ?? row.description ?? nodeText(row));
3750
3819
  const terms = [];
@@ -3770,11 +3839,11 @@ function termsFromRow(row, children) {
3770
3839
  return terms;
3771
3840
  }
3772
3841
  function nameFromRow(row, children) {
3773
- const declarationName = declarationCoverageNameFromRow(row, children);
3774
- if (declarationName) return declarationName;
3775
- const cells = cellRows(row, children);
3842
+ const cells = cellRows(row, children, headerLabelsForRow(row, children));
3776
3843
  const named = cells.find((cell) => isNameCell(cell.label, cell.value));
3777
3844
  if (named) return cleanValue(named.value);
3845
+ const declarationName = declarationCoverageNameFromRow(row, children);
3846
+ if (declarationName) return declarationName;
3778
3847
  return coverageNameFromRow(row.textExcerpt ?? row.description ?? nodeText(row));
3779
3848
  }
3780
3849
  function legacyLimit(terms) {
@@ -3807,7 +3876,7 @@ function isOperationalCoverageRow(coverage) {
3807
3876
  if (coverage.name.split(/\s+/).length > 16 && !/\b(coverage|liability|sub[-\s]?limit|aggregate|each\s+(claim|loss|occurrence)|limit)\b/i.test(coverage.name)) {
3808
3877
  return false;
3809
3878
  }
3810
- return /\b(coverage|coverage part|liability|sub[-\s]?limit|aggregate|each\s+(claim|loss|occurrence)|bricking|cyber|privacy|media|regulatory|defense|ai\/ml|errors?\s*&?\s*omissions|technology)\b/i.test(coverage.name);
3879
+ return /\b(coverage|coverage part|liability|sub[-\s]?limit|aggregate|each\s+(claim|loss|occurrence|proceeding)|bricking|cyber|privacy|media|regulatory|defense|fraud|social engineering|ai\/ml|errors?\s*&?\s*omissions|technology)\b/i.test(coverage.name);
3811
3880
  }
3812
3881
  function uniqueTerms(terms) {
3813
3882
  const seen = /* @__PURE__ */ new Set();
@@ -3821,7 +3890,7 @@ function uniqueTerms(terms) {
3821
3890
  return result;
3822
3891
  }
3823
3892
  function coverageFromTableRow(row, children, byId) {
3824
- if (row.metadata?.isHeader === true || row.metadata?.isHeader === "true") return void 0;
3893
+ if (isHeaderRow(row)) return void 0;
3825
3894
  const name = nameFromRow(row, children);
3826
3895
  const terms = uniqueTerms(termsFromRow(row, children));
3827
3896
  if (!name || terms.length === 0) return void 0;
@@ -13012,6 +13081,55 @@ var ApplicationFieldSchema = import_zod42.z.object({
13012
13081
  acroFormName: import_zod42.z.string().optional().describe("Native PDF AcroForm field name when available"),
13013
13082
  validationStatus: import_zod42.z.enum(["valid", "needs_review", "unsupported", "missing"]).optional()
13014
13083
  });
13084
+ var ApplicationQuestionConditionSchema = import_zod42.z.object({
13085
+ dependsOn: import_zod42.z.string(),
13086
+ operator: import_zod42.z.enum(["equals", "not_equals", "in", "not_in", "exists"]).optional(),
13087
+ value: import_zod42.z.string().optional(),
13088
+ whenValue: import_zod42.z.string().optional(),
13089
+ values: import_zod42.z.array(import_zod42.z.string()).optional()
13090
+ });
13091
+ var ApplicationRepeatSchema = import_zod42.z.object({
13092
+ min: import_zod42.z.number().int().nonnegative().optional(),
13093
+ max: import_zod42.z.number().int().positive().optional(),
13094
+ label: import_zod42.z.string().optional()
13095
+ });
13096
+ var ApplicationQuestionNodeSchema = import_zod42.z.lazy(
13097
+ () => import_zod42.z.object({
13098
+ id: import_zod42.z.string(),
13099
+ nodeType: import_zod42.z.enum(["group", "question", "repeat_group", "table"]),
13100
+ fieldId: import_zod42.z.string().optional(),
13101
+ fieldPath: import_zod42.z.string().optional(),
13102
+ parentId: import_zod42.z.string().optional(),
13103
+ order: import_zod42.z.number().int().nonnegative().optional(),
13104
+ label: import_zod42.z.string(),
13105
+ section: import_zod42.z.string().optional(),
13106
+ fieldType: FieldTypeSchema.optional(),
13107
+ required: import_zod42.z.boolean().optional(),
13108
+ prompt: import_zod42.z.string().optional(),
13109
+ options: import_zod42.z.array(import_zod42.z.string()).optional(),
13110
+ columns: import_zod42.z.array(import_zod42.z.string()).optional(),
13111
+ condition: ApplicationQuestionConditionSchema.optional(),
13112
+ repeat: ApplicationRepeatSchema.optional(),
13113
+ children: import_zod42.z.array(ApplicationQuestionNodeSchema).optional()
13114
+ })
13115
+ );
13116
+ var ApplicationQuestionGraphSchema = import_zod42.z.object({
13117
+ id: import_zod42.z.string(),
13118
+ version: import_zod42.z.string(),
13119
+ title: import_zod42.z.string().optional(),
13120
+ applicationType: import_zod42.z.string().nullable().optional(),
13121
+ source: import_zod42.z.enum(["pdf", "manual", "imported", "generated"]).default("generated"),
13122
+ rootNodeIds: import_zod42.z.array(import_zod42.z.string()).optional(),
13123
+ nodes: import_zod42.z.array(ApplicationQuestionNodeSchema)
13124
+ });
13125
+ var ApplicationTemplateSchema = import_zod42.z.object({
13126
+ id: import_zod42.z.string(),
13127
+ version: import_zod42.z.string(),
13128
+ title: import_zod42.z.string(),
13129
+ applicationType: import_zod42.z.string().nullable().optional(),
13130
+ questionGraph: ApplicationQuestionGraphSchema,
13131
+ fields: import_zod42.z.array(ApplicationFieldSchema).optional()
13132
+ });
13015
13133
  var ApplicationClassifyResultSchema = import_zod42.z.object({
13016
13134
  isApplication: import_zod42.z.boolean(),
13017
13135
  confidence: import_zod42.z.number().min(0).max(1),
@@ -13109,16 +13227,67 @@ var ApplicationQualityReportSchema = import_zod42.z.object({
13109
13227
  emailReview: ApplicationEmailReviewSchema.optional(),
13110
13228
  qualityGateStatus: QualityGateStatusSchema
13111
13229
  });
13230
+ var ApplicationContextProposalSchema = import_zod42.z.object({
13231
+ id: import_zod42.z.string(),
13232
+ fieldId: import_zod42.z.string().optional(),
13233
+ key: import_zod42.z.string(),
13234
+ value: import_zod42.z.string(),
13235
+ category: import_zod42.z.string(),
13236
+ source: import_zod42.z.enum(["application", "user", "lookup", "policy", "email", "chat", "imessage", "mcp"]),
13237
+ confidence: import_zod42.z.enum(["confirmed", "high", "medium", "low"]),
13238
+ sourceSpanIds: import_zod42.z.array(import_zod42.z.string()).optional(),
13239
+ userSourceSpanIds: import_zod42.z.array(import_zod42.z.string()).optional()
13240
+ });
13241
+ var ApplicationPacketAnswerSchema = import_zod42.z.object({
13242
+ fieldId: import_zod42.z.string(),
13243
+ label: import_zod42.z.string(),
13244
+ section: import_zod42.z.string(),
13245
+ value: import_zod42.z.string(),
13246
+ source: import_zod42.z.string(),
13247
+ confidence: import_zod42.z.enum(["confirmed", "high", "medium", "low"]).optional(),
13248
+ sourceSpanIds: import_zod42.z.array(import_zod42.z.string()).optional(),
13249
+ userSourceSpanIds: import_zod42.z.array(import_zod42.z.string()).optional()
13250
+ });
13251
+ var ApplicationPacketSchema = import_zod42.z.object({
13252
+ id: import_zod42.z.string(),
13253
+ applicationId: import_zod42.z.string(),
13254
+ title: import_zod42.z.string(),
13255
+ status: import_zod42.z.enum(["draft", "broker_ready", "submitted"]),
13256
+ answers: import_zod42.z.array(ApplicationPacketAnswerSchema),
13257
+ missingFieldIds: import_zod42.z.array(import_zod42.z.string()),
13258
+ qualityReport: ApplicationQualityReportSchema,
13259
+ submissionNotes: import_zod42.z.string().optional(),
13260
+ createdAt: import_zod42.z.number()
13261
+ });
13112
13262
  var ApplicationStateSchema = import_zod42.z.object({
13113
13263
  id: import_zod42.z.string(),
13114
13264
  pdfBase64: import_zod42.z.string().optional().describe("Original PDF, omitted after extraction"),
13265
+ templateId: import_zod42.z.string().optional(),
13266
+ templateVersion: import_zod42.z.string().optional(),
13267
+ templateSnapshot: ApplicationTemplateSchema.optional(),
13115
13268
  title: import_zod42.z.string().optional(),
13116
13269
  applicationType: import_zod42.z.string().nullable().optional(),
13270
+ questionGraph: ApplicationQuestionGraphSchema.optional(),
13117
13271
  fields: import_zod42.z.array(ApplicationFieldSchema),
13118
13272
  batches: import_zod42.z.array(import_zod42.z.array(import_zod42.z.string())).optional(),
13119
13273
  currentBatchIndex: import_zod42.z.number().default(0),
13274
+ contextProposals: import_zod42.z.array(ApplicationContextProposalSchema).optional(),
13275
+ packet: ApplicationPacketSchema.optional(),
13120
13276
  qualityReport: ApplicationQualityReportSchema.optional(),
13121
- status: import_zod42.z.enum(["classifying", "extracting", "auto_filling", "batching", "collecting", "confirming", "mapping", "complete"]),
13277
+ status: import_zod42.z.enum([
13278
+ "classifying",
13279
+ "extracting",
13280
+ "auto_filling",
13281
+ "batching",
13282
+ "collecting",
13283
+ "confirming",
13284
+ "mapping",
13285
+ "broker_review",
13286
+ "packet_ready",
13287
+ "submitted",
13288
+ "cancelled",
13289
+ "complete"
13290
+ ]),
13122
13291
  createdAt: import_zod42.z.number(),
13123
13292
  updatedAt: import_zod42.z.number()
13124
13293
  });
@@ -13817,7 +13986,7 @@ function planReplyActions(input) {
13817
13986
  parseAnswers: input.intent.hasAnswers && hasCurrentFields,
13818
13987
  runLookup: hasLookupRequests && input.hasDocumentStore,
13819
13988
  answerQuestion: Boolean(input.intent.questionText) && (input.intent.primaryIntent === "question" || input.intent.primaryIntent === "mixed"),
13820
- advanceBatch: hasCurrentFields && input.currentBatchFields.every((field) => !isUnfilled(field)),
13989
+ advanceBatch: hasCurrentFields && input.currentBatchFields.every((field) => !isUnfilled(field)) || !hasCurrentFields && nextBatchNeedsAnswers,
13821
13990
  generateNextEmail: nextBatchNeedsAnswers
13822
13991
  };
13823
13992
  }
@@ -13856,12 +14025,287 @@ function isHighValueLookupField(field) {
13856
14025
  ].some((term) => text.includes(term));
13857
14026
  }
13858
14027
 
14028
+ // src/application/question-graph.ts
14029
+ function buildQuestionGraphFromFields(fields, options) {
14030
+ const sectionNodes = /* @__PURE__ */ new Map();
14031
+ const nodes = [];
14032
+ for (const [index, field] of fields.entries()) {
14033
+ const sectionId = stableNodeId(["section", field.section]);
14034
+ let sectionNode = sectionNodes.get(sectionId);
14035
+ if (!sectionNode) {
14036
+ sectionNode = {
14037
+ id: sectionId,
14038
+ nodeType: "group",
14039
+ label: field.section,
14040
+ order: sectionNodes.size,
14041
+ children: []
14042
+ };
14043
+ sectionNodes.set(sectionId, sectionNode);
14044
+ nodes.push(sectionNode);
14045
+ }
14046
+ const child = {
14047
+ id: field.fieldAnchorId ?? stableNodeId(["field", field.section, field.id || field.label]),
14048
+ nodeType: field.fieldType === "table" ? "table" : "question",
14049
+ fieldId: field.id,
14050
+ fieldPath: `${field.section}.${field.id}`,
14051
+ parentId: sectionId,
14052
+ order: index,
14053
+ label: field.label,
14054
+ section: field.section,
14055
+ fieldType: field.fieldType,
14056
+ required: field.required,
14057
+ options: field.options,
14058
+ columns: field.columns,
14059
+ condition: field.condition ? {
14060
+ dependsOn: field.condition.dependsOn,
14061
+ operator: "equals",
14062
+ value: field.condition.whenValue,
14063
+ whenValue: field.condition.whenValue
14064
+ } : void 0
14065
+ };
14066
+ sectionNode.children = [...sectionNode.children ?? [], child];
14067
+ }
14068
+ return normalizeApplicationQuestionGraph({
14069
+ id: options.id,
14070
+ version: options.version ?? "v1",
14071
+ title: options.title,
14072
+ applicationType: options.applicationType,
14073
+ source: options.source ?? "generated",
14074
+ rootNodeIds: nodes.map((node) => node.id),
14075
+ nodes
14076
+ });
14077
+ }
14078
+ function normalizeApplicationQuestionGraph(graph) {
14079
+ const normalizedNodes = graph.nodes.map((node, index) => normalizeNode(node, void 0, index)).sort(compareNodes);
14080
+ return {
14081
+ ...graph,
14082
+ rootNodeIds: graph.rootNodeIds?.length ? graph.rootNodeIds : normalizedNodes.map((node) => node.id),
14083
+ nodes: normalizedNodes
14084
+ };
14085
+ }
14086
+ function flattenQuestionGraph(graph) {
14087
+ const fields = [];
14088
+ for (const node of graph.nodes.sort(compareNodes)) {
14089
+ collectFields(node, fields);
14090
+ }
14091
+ return fields;
14092
+ }
14093
+ function getActiveApplicationFields(state) {
14094
+ const valueByFieldId = new Map(
14095
+ state.fields.filter((field) => field.value !== void 0 && field.value.trim() !== "").map((field) => [field.id, field.value ?? ""])
14096
+ );
14097
+ const graphConditions = /* @__PURE__ */ new Map();
14098
+ for (const node of state.questionGraph?.nodes ?? []) {
14099
+ collectNodeConditions(node, graphConditions);
14100
+ }
14101
+ return state.fields.filter((field) => {
14102
+ const graphCondition = graphConditions.get(field.id);
14103
+ return isConditionSatisfied(field.condition, valueByFieldId) && isQuestionConditionSatisfied(graphCondition, valueByFieldId);
14104
+ });
14105
+ }
14106
+ function getNextApplicationQuestions(state, limit = 8) {
14107
+ const activeUnfilled = getActiveApplicationFields(state).filter((field) => !field.value);
14108
+ if (activeUnfilled.length === 0) return [];
14109
+ const currentBatchIds = state.batches?.[state.currentBatchIndex] ?? [];
14110
+ const currentBatchFields = activeUnfilled.filter((field) => currentBatchIds.includes(field.id));
14111
+ return (currentBatchFields.length > 0 ? currentBatchFields : activeUnfilled).slice(0, limit);
14112
+ }
14113
+ function normalizeNode(node, parentId, index) {
14114
+ const children = node.children?.map((child, childIndex) => normalizeNode(child, node.id, childIndex));
14115
+ return {
14116
+ ...node,
14117
+ parentId: node.parentId ?? parentId,
14118
+ order: node.order ?? index,
14119
+ fieldPath: node.fieldPath ?? (node.fieldId ? [node.section, node.fieldId].filter(Boolean).join(".") : void 0),
14120
+ children
14121
+ };
14122
+ }
14123
+ function collectFields(node, fields) {
14124
+ if ((node.nodeType === "question" || node.nodeType === "table") && node.fieldId) {
14125
+ fields.push({
14126
+ id: node.fieldId,
14127
+ label: node.label,
14128
+ section: node.section ?? "General",
14129
+ fieldType: node.fieldType ?? (node.nodeType === "table" ? "table" : "text"),
14130
+ required: node.required ?? false,
14131
+ options: node.options,
14132
+ columns: node.columns,
14133
+ condition: node.condition ? {
14134
+ dependsOn: node.condition.dependsOn,
14135
+ whenValue: node.condition.value ?? node.condition.whenValue ?? ""
14136
+ } : void 0,
14137
+ fieldAnchorId: node.id
14138
+ });
14139
+ }
14140
+ for (const child of node.children ?? []) {
14141
+ collectFields(child, fields);
14142
+ }
14143
+ }
14144
+ function collectNodeConditions(node, conditions) {
14145
+ if (node.fieldId && node.condition) {
14146
+ conditions.set(node.fieldId, node.condition);
14147
+ }
14148
+ for (const child of node.children ?? []) {
14149
+ collectNodeConditions(child, conditions);
14150
+ }
14151
+ }
14152
+ function isConditionSatisfied(condition, valueByFieldId) {
14153
+ if (!condition) return true;
14154
+ const current = valueByFieldId.get(condition.dependsOn);
14155
+ return normalizeValue(current) === normalizeValue(condition.whenValue);
14156
+ }
14157
+ function isQuestionConditionSatisfied(condition, valueByFieldId) {
14158
+ if (!condition) return true;
14159
+ const current = valueByFieldId.get(condition.dependsOn);
14160
+ const expected = condition.value ?? condition.whenValue;
14161
+ const values = condition.values ?? (expected !== void 0 ? [expected] : []);
14162
+ switch (condition.operator) {
14163
+ case "exists":
14164
+ return current !== void 0 && current.trim() !== "";
14165
+ case "not_equals":
14166
+ return normalizeValue(current) !== normalizeValue(expected);
14167
+ case "in":
14168
+ return values.map(normalizeValue).includes(normalizeValue(current));
14169
+ case "not_in":
14170
+ return !values.map(normalizeValue).includes(normalizeValue(current));
14171
+ case "equals":
14172
+ default:
14173
+ return normalizeValue(current) === normalizeValue(expected);
14174
+ }
14175
+ }
14176
+ function compareNodes(a, b) {
14177
+ return (a.order ?? 0) - (b.order ?? 0) || a.id.localeCompare(b.id);
14178
+ }
14179
+ function normalizeValue(value) {
14180
+ return (value ?? "").trim().toLowerCase();
14181
+ }
14182
+ function stableNodeId(parts) {
14183
+ return parts.join(":").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "node";
14184
+ }
14185
+
14186
+ // src/application/intake.ts
14187
+ function extractQuestionGraphFromFields(fields, options) {
14188
+ return buildQuestionGraphFromFields(fields, options);
14189
+ }
14190
+ function createApplicationRun(params) {
14191
+ const now = params.now ?? Date.now();
14192
+ const graph = normalizeApplicationQuestionGraph(params.template.questionGraph);
14193
+ const fields = params.template.fields?.length ? params.template.fields : flattenQuestionGraph(graph);
14194
+ return {
14195
+ id: params.applicationId,
14196
+ templateId: params.template.id,
14197
+ templateVersion: params.template.version,
14198
+ templateSnapshot: params.template,
14199
+ title: params.template.title,
14200
+ applicationType: params.template.applicationType,
14201
+ questionGraph: graph,
14202
+ fields,
14203
+ currentBatchIndex: 0,
14204
+ status: "collecting",
14205
+ createdAt: now,
14206
+ updatedAt: now
14207
+ };
14208
+ }
14209
+ function planNextApplicationQuestions(state, limit) {
14210
+ const fields = getNextApplicationQuestions(state, limit);
14211
+ return {
14212
+ status: fields.length === 0 ? "complete" : "needs_answers",
14213
+ fieldIds: fields.map((field) => field.id),
14214
+ fields
14215
+ };
14216
+ }
14217
+ function applyApplicationAnswers(state, answers, now = Date.now()) {
14218
+ const answerByFieldId = new Map(answers.map((answer) => [answer.fieldId, answer]));
14219
+ const fields = state.fields.map((field) => {
14220
+ const answer = answerByFieldId.get(field.id);
14221
+ if (!answer) return field;
14222
+ return {
14223
+ ...field,
14224
+ value: answer.value,
14225
+ source: answer.source ?? "user",
14226
+ confidence: answer.confidence ?? "confirmed",
14227
+ sourceSpanIds: answer.sourceSpanIds ?? field.sourceSpanIds,
14228
+ userSourceSpanIds: answer.userSourceSpanIds ?? field.userSourceSpanIds,
14229
+ validationStatus: "valid"
14230
+ };
14231
+ });
14232
+ const nextState = {
14233
+ ...state,
14234
+ fields,
14235
+ updatedAt: now
14236
+ };
14237
+ const nextQuestions = planNextApplicationQuestions(nextState);
14238
+ return {
14239
+ ...nextState,
14240
+ status: nextQuestions.status === "complete" ? "confirming" : nextState.status,
14241
+ qualityReport: buildApplicationQualityReport(nextState)
14242
+ };
14243
+ }
14244
+ function proposeContextWrites(state) {
14245
+ return getActiveApplicationFields(state).filter((field) => field.value && field.confidence && field.confidence !== "low").map((field) => ({
14246
+ id: `${state.id}:${field.id}:context`,
14247
+ fieldId: field.id,
14248
+ key: stableContextKey(field),
14249
+ value: field.value ?? "",
14250
+ category: field.section,
14251
+ source: field.source?.startsWith("lookup:") ? "lookup" : "application",
14252
+ confidence: field.confidence ?? "medium",
14253
+ sourceSpanIds: field.sourceSpanIds,
14254
+ userSourceSpanIds: field.userSourceSpanIds
14255
+ }));
14256
+ }
14257
+ function buildApplicationPacket(state, options = {}) {
14258
+ const qualityReport = buildApplicationQualityReport(state);
14259
+ const activeFields = getActiveApplicationFields(state);
14260
+ const answers = activeFields.filter((field) => field.value).map((field) => ({
14261
+ fieldId: field.id,
14262
+ label: field.label,
14263
+ section: field.section,
14264
+ value: field.value ?? "",
14265
+ source: field.source ?? "unknown",
14266
+ confidence: field.confidence,
14267
+ sourceSpanIds: field.sourceSpanIds,
14268
+ userSourceSpanIds: field.userSourceSpanIds
14269
+ }));
14270
+ const missingFieldIds = activeFields.filter((field) => field.required && !field.value).map((field) => field.id);
14271
+ return {
14272
+ id: `${state.id}:packet`,
14273
+ applicationId: state.id,
14274
+ title: state.title ?? state.applicationType ?? "Insurance Application",
14275
+ status: qualityReport.qualityGateStatus === "failed" || missingFieldIds.length > 0 ? "draft" : "broker_ready",
14276
+ answers,
14277
+ missingFieldIds,
14278
+ qualityReport,
14279
+ submissionNotes: options.submissionNotes,
14280
+ createdAt: options.now ?? Date.now()
14281
+ };
14282
+ }
14283
+ function validateApplicationPacket(packet) {
14284
+ const issues = [...packet.qualityReport.issues];
14285
+ if (packet.missingFieldIds.length > 0) {
14286
+ issues.push({
14287
+ code: "packet_missing_required_answers",
14288
+ severity: "blocking",
14289
+ message: "Packet still has required unanswered application fields."
14290
+ });
14291
+ }
14292
+ return {
14293
+ ...packet.qualityReport,
14294
+ issues,
14295
+ qualityGateStatus: issues.some((issue) => issue.severity === "blocking") ? "failed" : packet.qualityReport.qualityGateStatus
14296
+ };
14297
+ }
14298
+ function stableContextKey(field) {
14299
+ return `${field.section}.${field.label}`.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
14300
+ }
14301
+
13859
14302
  // src/application/coordinator.ts
13860
14303
  function createApplicationPipeline(config) {
13861
14304
  const {
13862
14305
  generateText,
13863
14306
  generateObject,
13864
14307
  applicationStore,
14308
+ templateStore,
13865
14309
  documentStore,
13866
14310
  memoryStore,
13867
14311
  backfillProvider,
@@ -13898,11 +14342,18 @@ function createApplicationPipeline(config) {
13898
14342
  const applicationProviderOptions = input.sourceSpans?.length ? { ...providerOptions, sourceSpans: input.sourceSpans } : providerOptions;
13899
14343
  const id = input.applicationId ?? `app-${Date.now()}`;
13900
14344
  const now = Date.now();
14345
+ if (input.template) {
14346
+ await templateStore?.saveTemplate(input.template);
14347
+ }
13901
14348
  let state = {
13902
14349
  id,
14350
+ templateId: input.template?.id,
14351
+ templateVersion: input.template?.version,
14352
+ templateSnapshot: input.template,
13903
14353
  pdfBase64: void 0,
13904
14354
  title: void 0,
13905
14355
  applicationType: null,
14356
+ questionGraph: input.questionGraph ?? input.template?.questionGraph,
13906
14357
  fields: [],
13907
14358
  qualityReport: void 0,
13908
14359
  batches: void 0,
@@ -13962,6 +14413,12 @@ function createApplicationPipeline(config) {
13962
14413
  return { state, tokenUsage: totalUsage, reviewReport: state.qualityReport };
13963
14414
  }
13964
14415
  state.fields = fields;
14416
+ state.questionGraph = input.questionGraph ?? input.template?.questionGraph ?? buildQuestionGraphFromFields(fields, {
14417
+ id: `${id}:graph`,
14418
+ title: classifyResult.applicationType ?? void 0,
14419
+ applicationType: classifyResult.applicationType,
14420
+ source: "pdf"
14421
+ });
13965
14422
  state.title = classifyResult.applicationType ?? void 0;
13966
14423
  state.status = "auto_filling";
13967
14424
  state.updatedAt = Date.now();
@@ -13982,8 +14439,10 @@ function createApplicationPipeline(config) {
13982
14439
  if (field && !field.value && pa.relevance > 0.8) {
13983
14440
  field.value = pa.value;
13984
14441
  field.source = `backfill: ${pa.source}`;
13985
- field.confidence = "high";
13986
- field.validationStatus = "needs_review";
14442
+ field.confidence = pa.confidence ?? "high";
14443
+ field.validationStatus = pa.sourceSpanIds?.length ? "valid" : "needs_review";
14444
+ field.sourceSpanIds = pa.sourceSpanIds;
14445
+ field.userSourceSpanIds = pa.userSourceSpanIds;
13987
14446
  }
13988
14447
  }
13989
14448
  } catch (e) {
@@ -14033,7 +14492,18 @@ function createApplicationPipeline(config) {
14033
14492
  try {
14034
14493
  const searchPromises = workflowPlan.documentSearchFields.map(
14035
14494
  (f) => limit(async () => {
14036
- await memoryStore.search(f.label, { limit: 3 });
14495
+ const chunks = await memoryStore.search(`${f.section} ${f.label}`, { limit: 3 });
14496
+ const match = selectMemoryBackfillMatch(f, chunks);
14497
+ if (match) {
14498
+ const field = state.fields.find((candidate) => candidate.id === f.id);
14499
+ if (field && !field.value) {
14500
+ field.value = match.value;
14501
+ field.source = match.source;
14502
+ field.confidence = match.confidence;
14503
+ field.validationStatus = match.sourceSpanIds.length > 0 ? "valid" : "needs_review";
14504
+ field.sourceSpanIds = match.sourceSpanIds.length > 0 ? match.sourceSpanIds : void 0;
14505
+ }
14506
+ }
14037
14507
  })
14038
14508
  );
14039
14509
  await Promise.all(searchPromises);
@@ -14053,7 +14523,7 @@ function createApplicationPipeline(config) {
14053
14523
  hasDocumentStore: false,
14054
14524
  hasMemoryStore: false
14055
14525
  });
14056
- const unfilledFields = workflowPlan.unfilledFields;
14526
+ const unfilledFields = getActiveApplicationFields(state).filter((field) => !field.value);
14057
14527
  if (workflowPlan.runBatching) {
14058
14528
  onProgress?.(`Batching ${unfilledFields.length} remaining questions...`);
14059
14529
  state.status = "batching";
@@ -14075,6 +14545,7 @@ function createApplicationPipeline(config) {
14075
14545
  } else {
14076
14546
  state.status = "confirming";
14077
14547
  }
14548
+ state.contextProposals = proposeContextWrites(state);
14078
14549
  state.qualityReport = buildApplicationQualityReport(state);
14079
14550
  state.updatedAt = Date.now();
14080
14551
  await applicationStore?.save(state);
@@ -14102,7 +14573,8 @@ function createApplicationPipeline(config) {
14102
14573
  throw new Error(`Application ${applicationId} not found`);
14103
14574
  }
14104
14575
  const currentBatchFieldIds = state.batches?.[state.currentBatchIndex] ?? [];
14105
- const currentBatchFields = state.fields.filter(
14576
+ const activeFields = getActiveApplicationFields(state);
14577
+ const currentBatchFields = activeFields.filter(
14106
14578
  (f) => currentBatchFieldIds.includes(f.id)
14107
14579
  );
14108
14580
  onProgress?.("Classifying reply...");
@@ -14225,14 +14697,16 @@ Provide a brief, helpful explanation (2-3 sentences). End with "Just reply with
14225
14697
  responseText = `I wasn't able to generate an explanation for your question. Could you rephrase it, or just provide the answer directly?`;
14226
14698
  }
14227
14699
  }
14228
- const currentBatchComplete = currentBatchFieldIds.every(
14700
+ const activeCurrentBatchFieldIds = currentBatchFields.map((field) => field.id);
14701
+ const currentBatchComplete = activeCurrentBatchFieldIds.every(
14229
14702
  (fid) => state.fields.find((f) => f.id === fid)?.value
14230
14703
  );
14231
14704
  let nextBatchIndex;
14232
14705
  let nextBatchFields;
14233
14706
  if (state.batches) {
14234
14707
  for (let index = state.currentBatchIndex + 1; index < state.batches.length; index++) {
14235
- const candidateFields = state.fields.filter((f) => state.batches[index].includes(f.id));
14708
+ const activeCandidateFields = getActiveApplicationFields(state);
14709
+ const candidateFields = activeCandidateFields.filter((f) => state.batches[index].includes(f.id));
14236
14710
  if (candidateFields.some((f) => !f.value)) {
14237
14711
  nextBatchIndex = index;
14238
14712
  nextBatchFields = candidateFields;
@@ -14288,7 +14762,8 @@ ${emailText}`;
14288
14762
  }
14289
14763
  }
14290
14764
  state.updatedAt = Date.now();
14291
- state.qualityReport = state.qualityReport ?? buildApplicationQualityReport(state);
14765
+ state.contextProposals = proposeContextWrites(state);
14766
+ state.qualityReport = buildApplicationQualityReport(state);
14292
14767
  await applicationStore?.save(state);
14293
14768
  if (shouldFailQualityGate(qualityGate, state.qualityReport.qualityGateStatus)) {
14294
14769
  throw new Error("Application quality gate failed. See state.qualityReport for blocking issues.");
@@ -14308,7 +14783,7 @@ ${emailText}`;
14308
14783
  if (!state) throw new Error(`Application ${applicationId} not found`);
14309
14784
  if (!state.batches?.length) throw new Error("No batches available");
14310
14785
  const batchFieldIds = state.batches[state.currentBatchIndex];
14311
- const batchFields = state.fields.filter((f) => batchFieldIds.includes(f.id));
14786
+ const batchFields = getActiveApplicationFields(state).filter((f) => batchFieldIds.includes(f.id));
14312
14787
  const filledCount = state.fields.filter((f) => f.value).length;
14313
14788
  const { text, usage } = await generateBatchEmail(
14314
14789
  batchFields,
@@ -14356,13 +14831,86 @@ ${fieldSummary}`,
14356
14831
  trackUsage(usage);
14357
14832
  return { text, tokenUsage: totalUsage };
14358
14833
  }
14834
+ async function createApplicationRun2(input) {
14835
+ const state = createApplicationRun(input);
14836
+ await applicationStore?.save(state);
14837
+ return state;
14838
+ }
14839
+ async function planNextQuestions(applicationId, limit2) {
14840
+ const state = await applicationStore?.get(applicationId);
14841
+ if (!state) throw new Error(`Application ${applicationId} not found`);
14842
+ return planNextApplicationQuestions(state, limit2);
14843
+ }
14844
+ async function proposeContextWrites2(applicationId) {
14845
+ const state = await applicationStore?.get(applicationId);
14846
+ if (!state) throw new Error(`Application ${applicationId} not found`);
14847
+ const proposals = proposeContextWrites(state);
14848
+ await applicationStore?.save({
14849
+ ...state,
14850
+ contextProposals: proposals,
14851
+ updatedAt: Date.now()
14852
+ });
14853
+ return { proposals };
14854
+ }
14855
+ async function buildApplicationPacket2(input) {
14856
+ const state = await applicationStore?.get(input.applicationId);
14857
+ if (!state) throw new Error(`Application ${input.applicationId} not found`);
14858
+ const packet = buildApplicationPacket(state, {
14859
+ submissionNotes: input.submissionNotes,
14860
+ now: input.now
14861
+ });
14862
+ const reviewReport = validateApplicationPacket(packet);
14863
+ await applicationStore?.save({
14864
+ ...state,
14865
+ packet: { ...packet, qualityReport: reviewReport },
14866
+ status: reviewReport.qualityGateStatus === "failed" ? "broker_review" : "packet_ready",
14867
+ qualityReport: reviewReport,
14868
+ updatedAt: Date.now()
14869
+ });
14870
+ return { packet: { ...packet, qualityReport: reviewReport }, reviewReport };
14871
+ }
14359
14872
  return {
14360
14873
  processApplication,
14361
14874
  processReply: processReply2,
14362
14875
  generateCurrentBatchEmail,
14363
- getConfirmationSummary
14876
+ getConfirmationSummary,
14877
+ createApplicationRun: createApplicationRun2,
14878
+ planNextQuestions,
14879
+ proposeContextWrites: proposeContextWrites2,
14880
+ buildApplicationPacket: buildApplicationPacket2
14364
14881
  };
14365
14882
  }
14883
+ function selectMemoryBackfillMatch(field, chunks) {
14884
+ for (const chunk of chunks) {
14885
+ const value = chunk.metadata.value ?? chunk.metadata.answer ?? chunk.metadata.fieldValue;
14886
+ if (!value) continue;
14887
+ const metadataFieldId = chunk.metadata.fieldId ?? chunk.metadata.applicationFieldId;
14888
+ const metadataLabel = chunk.metadata.fieldLabel?.toLowerCase();
14889
+ const labelMatches = metadataLabel === field.label.toLowerCase();
14890
+ if (metadataFieldId && metadataFieldId !== field.id && !labelMatches) continue;
14891
+ return {
14892
+ value,
14893
+ source: chunk.metadata.source ?? `memory: ${chunk.documentId}`,
14894
+ confidence: metadataFieldId === field.id || labelMatches ? "high" : "medium",
14895
+ sourceSpanIds: parseSourceSpanIds(chunk.metadata.sourceSpanIds)
14896
+ };
14897
+ }
14898
+ return null;
14899
+ }
14900
+ function parseSourceSpanIds(value) {
14901
+ if (!value) return [];
14902
+ const trimmed = value.trim();
14903
+ if (!trimmed) return [];
14904
+ if (trimmed.startsWith("[")) {
14905
+ try {
14906
+ const parsed = JSON.parse(trimmed);
14907
+ return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
14908
+ } catch {
14909
+ return [];
14910
+ }
14911
+ }
14912
+ return trimmed.split(",").map((item) => item.trim()).filter(Boolean);
14913
+ }
14366
14914
 
14367
14915
  // src/prompts/application/confirmation.ts
14368
14916
  function buildConfirmationSummaryPrompt(fields, applicationTitle) {
@@ -16443,13 +16991,21 @@ var AGENT_TOOLS = [
16443
16991
  AgenticExecutionModeSchema,
16444
16992
  AnswerParsingResultSchema,
16445
16993
  ApplicationClassifyResultSchema,
16994
+ ApplicationContextProposalSchema,
16446
16995
  ApplicationEmailReviewSchema,
16447
16996
  ApplicationFieldSchema,
16997
+ ApplicationPacketAnswerSchema,
16998
+ ApplicationPacketSchema,
16448
16999
  ApplicationQualityArtifactSchema,
16449
17000
  ApplicationQualityIssueSchema,
16450
17001
  ApplicationQualityReportSchema,
16451
17002
  ApplicationQualityRoundSchema,
17003
+ ApplicationQuestionConditionSchema,
17004
+ ApplicationQuestionGraphSchema,
17005
+ ApplicationQuestionNodeSchema,
17006
+ ApplicationRepeatSchema,
16452
17007
  ApplicationStateSchema,
17008
+ ApplicationTemplateSchema,
16453
17009
  AttachmentInterpretationSchema,
16454
17010
  AuditTypeSchema,
16455
17011
  AutoFillMatchSchema,
@@ -16664,9 +17220,11 @@ var AGENT_TOOLS = [
16664
17220
  VerifyResultSchema,
16665
17221
  WatercraftDeclarationsSchema,
16666
17222
  WorkersCompDeclarationsSchema,
17223
+ applyApplicationAnswers,
16667
17224
  buildAcroFormMappingPrompt,
16668
17225
  buildAgentSystemPrompt,
16669
17226
  buildAnswerParsingPrompt,
17227
+ buildApplicationPacket,
16670
17228
  buildAutoFillPrompt,
16671
17229
  buildBatchEmailGenerationPrompt,
16672
17230
  buildClassifyMessagePrompt,
@@ -16693,6 +17251,7 @@ var AGENT_TOOLS = [
16693
17251
  buildPdfProviderOptions,
16694
17252
  buildQueryClassifyPrompt,
16695
17253
  buildQuestionBatchPrompt,
17254
+ buildQuestionGraphFromFields,
16696
17255
  buildQuotesPoliciesPrompt,
16697
17256
  buildReasonPrompt,
16698
17257
  buildReplyIntentClassificationPrompt,
@@ -16708,6 +17267,7 @@ var AGENT_TOOLS = [
16708
17267
  collectPceEvidenceSources,
16709
17268
  compareSourceEvidence,
16710
17269
  createApplicationPipeline,
17270
+ createApplicationRun,
16711
17271
  createExtractor,
16712
17272
  createPceAgent,
16713
17273
  createPipelineContext,
@@ -16715,12 +17275,16 @@ var AGENT_TOOLS = [
16715
17275
  evaluateCaseProposals,
16716
17276
  evidenceContainsQuote,
16717
17277
  extractPageRange,
17278
+ extractQuestionGraphFromFields,
16718
17279
  fillAcroForm,
17280
+ flattenQuestionGraph,
16719
17281
  generateNextMessage,
16720
17282
  getAcroFormFields,
17283
+ getActiveApplicationFields,
16721
17284
  getDoclingPageRangeText,
16722
17285
  getExtractor,
16723
17286
  getFileIdentifier,
17287
+ getNextApplicationQuestions,
16724
17288
  getPdfPageCount,
16725
17289
  getTemplate,
16726
17290
  isDoclingExtractionInput,
@@ -16728,6 +17292,7 @@ var AGENT_TOOLS = [
16728
17292
  mergeOperationalProfile,
16729
17293
  mergeQuestionAnswers,
16730
17294
  mergeSourceSpans,
17295
+ normalizeApplicationQuestionGraph,
16731
17296
  normalizeDoclingDocument,
16732
17297
  normalizeDocumentSourceTreePaths,
16733
17298
  normalizeForMatch,
@@ -16737,7 +17302,9 @@ var AGENT_TOOLS = [
16737
17302
  pLimit,
16738
17303
  pdfInputToBase64,
16739
17304
  pdfInputToBytes,
17305
+ planNextApplicationQuestions,
16740
17306
  processReply,
17307
+ proposeContextWrites,
16741
17308
  resolveModelBudget,
16742
17309
  safeGenerateObject,
16743
17310
  sanitizeNulls,
@@ -16750,6 +17317,7 @@ var AGENT_TOOLS = [
16750
17317
  stableStringify,
16751
17318
  stripFences,
16752
17319
  toStrictSchema,
17320
+ validateApplicationPacket,
16753
17321
  validateEvidence,
16754
17322
  validatePceItems,
16755
17323
  validateQuotedEvidence,