@claritylabs/cl-sdk 3.1.20 → 3.1.21

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
@@ -2478,7 +2478,6 @@ var OperationalCoverageLineSchema = import_zod20.z.object({
2478
2478
  retroactiveDate: import_zod20.z.string().optional(),
2479
2479
  formNumber: import_zod20.z.string().optional(),
2480
2480
  sectionRef: import_zod20.z.string().optional(),
2481
- coverageOrigin: import_zod20.z.enum(["core", "endorsement"]).optional(),
2482
2481
  endorsementNumber: import_zod20.z.string().optional(),
2483
2482
  limits: import_zod20.z.array(OperationalCoverageTermSchema).default([]),
2484
2483
  sourceNodeIds: import_zod20.z.array(import_zod20.z.string().min(1)).default([]),
@@ -2508,7 +2507,6 @@ var PolicyOperationalProfileSchema = import_zod20.z.object({
2508
2507
  expirationDate: SourceBackedValueSchema.optional(),
2509
2508
  retroactiveDate: SourceBackedValueSchema.optional(),
2510
2509
  premium: SourceBackedValueSchema.optional(),
2511
- coverageTypes: import_zod20.z.array(import_zod20.z.string()).default([]),
2512
2510
  coverages: import_zod20.z.array(OperationalCoverageLineSchema).default([]),
2513
2511
  parties: import_zod20.z.array(OperationalPartySchema).default([]),
2514
2512
  endorsementSupport: import_zod20.z.array(OperationalEndorsementSupportSchema).default([]),
@@ -3625,9 +3623,9 @@ function normalizeDoclingDocument(document, options) {
3625
3623
  pageTexts.set(page, appendText(pageTexts.get(page), unit.text));
3626
3624
  }
3627
3625
  const fullText = Array.from({ length: pageCount }, (_, index) => {
3628
- const pageNumber2 = index + 1;
3629
- const text = pageTexts.get(pageNumber2)?.trim();
3630
- return text ? `Page ${pageNumber2}
3626
+ const pageNumber = index + 1;
3627
+ const text = pageTexts.get(pageNumber)?.trim();
3628
+ return text ? `Page ${pageNumber}
3631
3629
  ${text}` : "";
3632
3630
  }).filter(Boolean).join("\n\n");
3633
3631
  const sourceKind = options.sourceKind ?? "policy_pdf";
@@ -5956,7 +5954,7 @@ function mergeCoverageLimits(existing, incoming) {
5956
5954
  const merged = mergeShallowPreferPresent(existing, incoming);
5957
5955
  const existingCoverages = Array.isArray(existing.coverages) ? existing.coverages : [];
5958
5956
  const incomingCoverages = Array.isArray(incoming.coverages) ? incoming.coverages : [];
5959
- const coverageKey2 = (coverage) => keyFromParts(
5957
+ const coverageKey = (coverage) => keyFromParts(
5960
5958
  coverage.name,
5961
5959
  coverage.limitType,
5962
5960
  coverage.limit,
@@ -5965,7 +5963,7 @@ function mergeCoverageLimits(existing, incoming) {
5965
5963
  );
5966
5964
  const byKey = /* @__PURE__ */ new Map();
5967
5965
  for (const coverage of [...existingCoverages, ...incomingCoverages]) {
5968
- const key = coverageKey2(coverage);
5966
+ const key = coverageKey(coverage);
5969
5967
  const current = byKey.get(key);
5970
5968
  byKey.set(key, current ? mergeShallowPreferPresent(current, coverage) : coverage);
5971
5969
  }
@@ -6938,8 +6936,11 @@ For EACH form, extract:
6938
6936
 
6939
6937
  Critical rules:
6940
6938
  - Include declarations page sets even if they do not show a standard form number.
6941
- - Do not classify policy jackets, claim-reporting notices, privacy notices, OFAC notices, terrorism/TRIA notices, sanctions notices, signatures, countersignatures, or marketing/admin pages as declarations.
6939
+ - Do not classify policy jackets, claim-reporting notices, privacy notices, OFAC notices, terrorism/TRIA notices, sanctions notices, signatures, countersignatures, or marketing/admin pages as declarations when they are only administrative content.
6942
6940
  - Declarations pages contain policy-specific schedules such as named insured, policy number, policy period, premium, limits, retentions, coverage parts, or forms-and-endorsements schedules.
6941
+ - Declarations pages may be internally itemized as "Item 1.", "Item 2.", etc. Keep the whole itemized declarations set together, including continuation pages for coverage schedules, premium, ERP options, producer information, and forms or endorsements attached at inception.
6942
+ - A page that lists declaration items or form/endorsement schedules remains part of the declarations set even if the bottom of that page also contains countersignature, authorized-representative, or policy-execution language.
6943
+ - When "Forms and Endorsements Attached at Inception" or similar form schedules continue onto the next page, extend the declarations pageEnd through that continuation instead of treating the continuation as a standalone signature page.
6943
6944
  - Use original document page numbers, not local chunk page numbers.
6944
6945
  - Do not emit duplicate entries for repeated headers/footers.
6945
6946
  - Multi-page forms should be represented once with pageStart/pageEnd covering the full span when visible.
@@ -7416,7 +7417,7 @@ var ExclusionsSchema = import_zod30.z.object({
7416
7417
  exceptions: import_zod30.z.array(import_zod30.z.string()).optional().describe("Exceptions to the exclusion, if any"),
7417
7418
  buybackAvailable: import_zod30.z.boolean().optional().describe("Whether coverage can be bought back via endorsement"),
7418
7419
  buybackEndorsement: import_zod30.z.string().optional().describe("Form number of the buyback endorsement if available"),
7419
- appliesTo: import_zod30.z.array(import_zod30.z.string()).optional().describe("Coverage types this exclusion applies to"),
7420
+ appliesTo: import_zod30.z.array(import_zod30.z.string()).optional().describe("Policy types this exclusion applies to"),
7420
7421
  content: import_zod30.z.string().describe("Full verbatim exclusion text"),
7421
7422
  pageNumber: import_zod30.z.number().optional().describe("Page number where exclusion appears")
7422
7423
  })
@@ -7433,7 +7434,7 @@ For EACH exclusion, extract:
7433
7434
  - exceptions: any exceptions to the exclusion (things still covered despite the exclusion)
7434
7435
  - buybackAvailable: whether coverage can be purchased back via endorsement
7435
7436
  - buybackEndorsement: the form number of the buyback endorsement if known
7436
- - appliesTo: which coverage types or lines this exclusion applies to (as an array)
7437
+ - appliesTo: which policy types or lines this exclusion applies to (as an array)
7437
7438
  - content: full verbatim exclusion text \u2014 REQUIRED
7438
7439
  - pageNumber: page number where the exclusion appears
7439
7440
 
@@ -8297,190 +8298,6 @@ async function resolveReferentialCoverages(params) {
8297
8298
  };
8298
8299
  }
8299
8300
 
8300
- // src/extraction/coverage-schedule-recovery.ts
8301
- function textValue(value) {
8302
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
8303
- }
8304
- function numberValue2(value) {
8305
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
8306
- }
8307
- function normalize(value) {
8308
- return value.toLowerCase().replace(/&/g, "and").replace(/[^a-z0-9]+/g, " ").trim();
8309
- }
8310
- function sourceUnit5(span) {
8311
- return span.sourceUnit ?? span.metadata?.sourceUnit;
8312
- }
8313
- function pageNumber(span) {
8314
- return span.pageStart ?? span.location?.page ?? span.location?.startPage;
8315
- }
8316
- function coveragePages(pageAssignments) {
8317
- const pages = /* @__PURE__ */ new Set();
8318
- for (const assignment of pageAssignments) {
8319
- if (assignment.extractorNames.includes("coverage_limits") || assignment.hasScheduleValues) {
8320
- pages.add(assignment.localPageNumber);
8321
- }
8322
- }
8323
- return pages;
8324
- }
8325
- function parseCurrencyAmount(value) {
8326
- const match = value.match(/(?:CAD|USD|US)?\s*\$?\s*([0-9][0-9,]*(?:\.\d+)?)/i);
8327
- if (!match) return void 0;
8328
- const amount = Number(match[1].replace(/,/g, ""));
8329
- return Number.isFinite(amount) ? amount : void 0;
8330
- }
8331
- function limitTypeFrom(value) {
8332
- const normalized = normalize(value);
8333
- if (normalized.includes("/") || normalized.includes("each claim") && normalized.includes("aggregate")) return "scheduled";
8334
- if (normalized.includes("each claim") || normalized.includes("per claim")) return "per_claim";
8335
- if (normalized.includes("each occurrence") || normalized.includes("per occurrence")) return "per_occurrence";
8336
- if (normalized.includes("aggregate")) return "aggregate";
8337
- if (normalized.includes("shared within") || normalized.includes("within coverage")) return "scheduled";
8338
- if (normalized.includes("/")) return "scheduled";
8339
- return void 0;
8340
- }
8341
- function limitValueTypeFrom(value) {
8342
- const normalized = normalize(value);
8343
- if (parseCurrencyAmount(value) !== void 0) return "numeric";
8344
- if (normalized.includes("shared within") || normalized.includes("within coverage") || normalized.includes("shown above")) {
8345
- return "referential";
8346
- }
8347
- if (normalized.includes("included")) return "included";
8348
- if (normalized.includes("not included") || normalized === "nil" || normalized === "none") return "not_included";
8349
- if (normalized.includes("as stated")) return "as_stated";
8350
- return "other";
8351
- }
8352
- function cleanName(value) {
8353
- return value.replace(/\s*\([^)]*part of and not in addition to[^)]*\)\s*/gi, " ").replace(/\s+/g, " ").trim().replace(/[.:;-]+$/, "").trim();
8354
- }
8355
- function isDeductibleOnly(name, rowText) {
8356
- const normalizedName = normalize(name);
8357
- const normalizedRow = normalize(rowText);
8358
- if (!/\b(deductible|retention|sir)\b/.test(`${normalizedName} ${normalizedRow}`)) return false;
8359
- if (/\b(coverage|sub limit|sublimit|limit)\b/.test(normalizedName) && !/\b(enhanced|standard)\s+deductible\b/.test(normalizedName)) {
8360
- return false;
8361
- }
8362
- return /\b(enhanced|standard)?\s*(deductible|retention|sir)\b/.test(normalizedName) || /^\s*(deductible|retention|sir)\b/.test(normalizedRow);
8363
- }
8364
- function splitRowFields(rowText) {
8365
- return rowText.split(/\s+\|\s+/).map((part) => part.trim()).filter(Boolean).map((part) => {
8366
- const match = part.match(/^([^:]{1,100}):\s*(.*)$/);
8367
- if (!match) return { value: part };
8368
- return { key: match[1].trim(), value: match[2].trim() };
8369
- });
8370
- }
8371
- function firstField(fields, patterns) {
8372
- for (const field of fields) {
8373
- const target = `${field.key ?? ""} ${field.value}`;
8374
- if (patterns.some((pattern) => pattern.test(target))) return field.value || field.key;
8375
- }
8376
- return void 0;
8377
- }
8378
- function coverageFromRow(span) {
8379
- const rowText = span.text.trim();
8380
- if (!rowText || sourceUnit5(span) !== "table_row") return void 0;
8381
- if (span.table?.isHeader || span.metadata?.isHeader === "true") return void 0;
8382
- const fields = splitRowFields(rowText);
8383
- let name;
8384
- let limit;
8385
- for (const field of fields) {
8386
- const key = field.key?.trim();
8387
- const value = field.value.trim();
8388
- if (!key || !value) continue;
8389
- if (!name && /^coverage$/i.test(key)) name = cleanName(value);
8390
- if (!limit && /\blimit\b/i.test(key)) limit = value;
8391
- if (!name && /\b(sub[-\s]?limit|aggregate|each claim)\b/i.test(key) && parseCurrencyAmount(value) !== void 0) {
8392
- name = cleanName(key);
8393
- limit = limit ?? value;
8394
- }
8395
- }
8396
- if (!name || !limit) {
8397
- for (const field of fields) {
8398
- const key = field.key?.trim();
8399
- const value = field.value.trim();
8400
- if (!key || !value) continue;
8401
- if (!name && /\b(sub[-\s]?limit|coverage|aggregate|each claim)\b/i.test(key) && !parseCurrencyAmount(key)) {
8402
- name = cleanName(key);
8403
- limit = limit ?? value;
8404
- }
8405
- }
8406
- }
8407
- if (!name || !limit) return void 0;
8408
- if (isDeductibleOnly(name, rowText)) return void 0;
8409
- const normalizedLimit = normalize(limit);
8410
- const hasUsableLimit = parseCurrencyAmount(limit) !== void 0 || /\b(shared within|within coverage|as stated|included|not included)\b/i.test(normalizedLimit);
8411
- if (!hasUsableLimit) return void 0;
8412
- const deductible = firstField(fields, [/\bdeductible\b/i, /\bretention\b/i, /\bsir\b/i]);
8413
- const basis = firstField(fields, [/\bbasis\b/i]);
8414
- const retroactiveDate = firstField(fields, [/\bretroactive date\b/i, /\bretro date\b/i]);
8415
- const page = pageNumber(span);
8416
- const limitAmount = parseCurrencyAmount(limit);
8417
- const deductibleAmount = deductible ? parseCurrencyAmount(deductible) : void 0;
8418
- return {
8419
- name,
8420
- limit,
8421
- ...limitAmount !== void 0 ? { limitAmount } : {},
8422
- ...limitTypeFrom(`${name} ${limit}`) ? { limitType: limitTypeFrom(`${name} ${limit}`) } : {},
8423
- limitValueType: limitValueTypeFrom(limit),
8424
- ...deductible && !/^nil|none$/i.test(deductible.trim()) ? { deductible } : {},
8425
- ...deductibleAmount !== void 0 ? { deductibleAmount } : {},
8426
- ...deductible ? { deductibleValueType: limitValueTypeFrom(deductible) } : {},
8427
- ...basis && /claims[- ]made/i.test(basis) ? { trigger: "claims_made" } : {},
8428
- ...retroactiveDate ? { retroactiveDate } : {},
8429
- ...span.formNumber ? { formNumber: span.formNumber } : {},
8430
- ...page ? { pageNumber: page } : {},
8431
- sectionRef: span.sectionId ?? "SCHEDULE",
8432
- originalContent: rowText,
8433
- sourceSpanIds: [span.id],
8434
- sourceTextHash: span.textHash ?? span.hash
8435
- };
8436
- }
8437
- function coverageKey(coverage) {
8438
- return [
8439
- textValue(coverage.name) ?? "",
8440
- textValue(coverage.limit) ?? "",
8441
- textValue(coverage.limitType) ?? "",
8442
- numberValue2(coverage.pageNumber) ?? ""
8443
- ].map((part) => normalize(String(part))).join("|");
8444
- }
8445
- function rowMatchesExisting(row, existing) {
8446
- const rowKey = coverageKey(row);
8447
- const rowName = normalize(textValue(row.name) ?? "");
8448
- const rowLimit = normalize(textValue(row.limit) ?? "");
8449
- return existing.some((coverage) => {
8450
- if (coverageKey(coverage) === rowKey) return true;
8451
- const name = normalize(textValue(coverage.name) ?? "");
8452
- const limit = normalize(textValue(coverage.limit) ?? "");
8453
- return Boolean(rowName && rowLimit && name === rowName && limit === rowLimit);
8454
- });
8455
- }
8456
- function recoverCoverageScheduleRows(params) {
8457
- const payload = params.memory.get("coverage_limits");
8458
- const existing = Array.isArray(payload?.coverages) ? payload.coverages : [];
8459
- const pages = coveragePages(params.pageAssignments);
8460
- const candidates = params.sourceSpans.filter((span) => sourceUnit5(span) === "table_row").filter((span) => {
8461
- const page = pageNumber(span);
8462
- return page !== void 0 && pages.has(page);
8463
- }).map(coverageFromRow).filter((coverage) => Boolean(coverage));
8464
- const recovered = [];
8465
- for (const coverage of candidates) {
8466
- if (rowMatchesExisting(coverage, [...existing, ...recovered])) continue;
8467
- recovered.push(coverage);
8468
- }
8469
- if (recovered.length > 0) {
8470
- params.memory.set("coverage_limits", {
8471
- ...payload ?? {},
8472
- coverages: [...existing, ...recovered]
8473
- });
8474
- }
8475
- return {
8476
- recovered,
8477
- missingSourceRows: recovered.map((coverage) => {
8478
- const id = Array.isArray(coverage.sourceSpanIds) ? coverage.sourceSpanIds[0] : void 0;
8479
- return params.sourceSpans.find((span) => span.id === id);
8480
- }).filter((span) => Boolean(span))
8481
- };
8482
- }
8483
-
8484
8301
  // src/extraction/focused-dispatch.ts
8485
8302
  async function runFocusedExtractorWithFallback(params) {
8486
8303
  const {
@@ -8683,29 +8500,6 @@ function buildExtractionReviewReport(params) {
8683
8500
  addMissingSourceGroundingIssues(deterministicIssues, "definitions", "definitions", definitions, "term");
8684
8501
  addMissingSourceGroundingIssues(deterministicIssues, "covered_reasons", "coveredReasons", coveredReasons, "name");
8685
8502
  }
8686
- if (params.sourceSpans?.length) {
8687
- const tempCoveragePayload = {
8688
- ...memory.get("coverage_limits") ?? {},
8689
- coverages: coverages.map((coverage) => ({ ...coverage }))
8690
- };
8691
- const tempMemory = new Map(memory);
8692
- tempMemory.set("coverage_limits", tempCoveragePayload);
8693
- const scheduleRecovery = recoverCoverageScheduleRows({
8694
- memory: tempMemory,
8695
- sourceSpans: params.sourceSpans,
8696
- pageAssignments: params.pageAssignments
8697
- });
8698
- for (const recovered of scheduleRecovery.recovered) {
8699
- deterministicIssues.push({
8700
- code: "coverage_schedule_row_missing",
8701
- severity: "blocking",
8702
- message: `Coverage schedule row "${String(recovered.name ?? "unknown")}" is present in source table evidence but missing from extracted coverages.`,
8703
- extractorName: "coverage_limits",
8704
- pageNumber: typeof recovered.pageNumber === "number" ? recovered.pageNumber : void 0,
8705
- itemName: typeof recovered.name === "string" ? recovered.name : void 0
8706
- });
8707
- }
8708
- }
8709
8503
  if (mappedDefinitions && definitions.length === 0) {
8710
8504
  deterministicIssues.push({
8711
8505
  code: "definitions_mapped_but_empty",
@@ -9148,17 +8942,17 @@ var ARRAY_PATHS = [
9148
8942
  { memoryKey: "supplementary", arrayKeys: ["auxiliaryFacts", "supplementaryFacts"] },
9149
8943
  { memoryKey: "form_inventory", arrayKeys: ["forms"] }
9150
8944
  ];
9151
- function normalize2(value) {
8945
+ function normalize(value) {
9152
8946
  return value.replace(/\s+/g, " ").trim().toLowerCase();
9153
8947
  }
9154
- function textValue2(record, ...keys) {
8948
+ function textValue(record, ...keys) {
9155
8949
  for (const key of keys) {
9156
8950
  const value = record[key];
9157
8951
  if (typeof value === "string" && value.trim()) return value.trim();
9158
8952
  }
9159
8953
  return void 0;
9160
8954
  }
9161
- function numberValue3(record, ...keys) {
8955
+ function numberValue2(record, ...keys) {
9162
8956
  for (const key of keys) {
9163
8957
  const value = record[key];
9164
8958
  if (typeof value === "number" && Number.isFinite(value)) return value;
@@ -9175,27 +8969,27 @@ function pageOverlaps(recordStart, recordEnd, span) {
9175
8969
  return start <= (spanEnd ?? spanStart) && end >= spanStart;
9176
8970
  }
9177
8971
  function formMatches(record, span) {
9178
- const formNumber = textValue2(record, "formNumber");
8972
+ const formNumber = textValue(record, "formNumber");
9179
8973
  if (!formNumber || !span.formNumber) return false;
9180
- return normalize2(formNumber) === normalize2(span.formNumber);
8974
+ return normalize(formNumber) === normalize(span.formNumber);
9181
8975
  }
9182
8976
  function textMatches(record, span) {
9183
- const spanText = normalize2(span.text);
8977
+ const spanText = normalize(span.text);
9184
8978
  const candidates = [
9185
- textValue2(record, "originalContent", "content", "definition", "value"),
9186
- textValue2(record, "name", "title", "term", "field", "coverageName"),
9187
- textValue2(record, "limit", "deductible", "premium")
8979
+ textValue(record, "originalContent", "content", "definition", "value"),
8980
+ textValue(record, "name", "title", "term", "field", "coverageName"),
8981
+ textValue(record, "limit", "deductible", "premium")
9188
8982
  ].filter((value) => !!value && value.length >= 3);
9189
- return candidates.some((candidate) => spanText.includes(normalize2(candidate)));
8983
+ return candidates.some((candidate) => spanText.includes(normalize(candidate)));
9190
8984
  }
9191
8985
  function sourceHashFor(spans) {
9192
8986
  return spans.map((span) => span.textHash ?? span.hash).filter(Boolean).join(":") || void 0;
9193
8987
  }
9194
- function sourceUnit6(span) {
8988
+ function sourceUnit5(span) {
9195
8989
  return span.sourceUnit ?? span.metadata?.sourceUnit;
9196
8990
  }
9197
8991
  function hierarchyScore(span) {
9198
- switch (sourceUnit6(span)) {
8992
+ switch (sourceUnit5(span)) {
9199
8993
  case "table_row":
9200
8994
  return 5;
9201
8995
  case "table":
@@ -9218,8 +9012,8 @@ function preferParentRows(matches, sourceSpans) {
9218
9012
  const expanded = [];
9219
9013
  const seen = /* @__PURE__ */ new Set();
9220
9014
  for (const match of matches) {
9221
- const parent = sourceUnit6(match) === "table_cell" ? byId.get(parentRowId(match) ?? "") : void 0;
9222
- const preferred = parent && sourceUnit6(parent) === "table_row" ? parent : match;
9015
+ const parent = sourceUnit5(match) === "table_cell" ? byId.get(parentRowId(match) ?? "") : void 0;
9016
+ const preferred = parent && sourceUnit5(parent) === "table_row" ? parent : match;
9223
9017
  if (seen.has(preferred.id)) continue;
9224
9018
  seen.add(preferred.id);
9225
9019
  expanded.push(preferred);
@@ -9228,8 +9022,8 @@ function preferParentRows(matches, sourceSpans) {
9228
9022
  }
9229
9023
  function findSourceSpansForRecord(record, sourceSpans) {
9230
9024
  if (sourceSpans.length === 0) return [];
9231
- const pageStart2 = numberValue3(record, "pageNumber", "pageStart");
9232
- const pageEnd2 = numberValue3(record, "pageNumber", "pageEnd");
9025
+ const pageStart2 = numberValue2(record, "pageNumber", "pageStart");
9026
+ const pageEnd2 = numberValue2(record, "pageNumber", "pageEnd");
9233
9027
  const scored = sourceSpans.map((span) => {
9234
9028
  let score = 0;
9235
9029
  if (pageOverlaps(pageStart2, pageEnd2, span)) score += 4;
@@ -9371,7 +9165,6 @@ function mergeOperationalProfile(base, candidate, validNodeIds, validSpanIds) {
9371
9165
  retroactiveDate: typeof record.retroactiveDate === "string" ? cleanValue(record.retroactiveDate) : void 0,
9372
9166
  formNumber: typeof record.formNumber === "string" ? cleanValue(record.formNumber) : void 0,
9373
9167
  sectionRef: typeof record.sectionRef === "string" ? cleanValue(record.sectionRef) : void 0,
9374
- coverageOrigin: record.coverageOrigin === "core" || record.coverageOrigin === "endorsement" ? record.coverageOrigin : void 0,
9375
9168
  endorsementNumber: typeof record.endorsementNumber === "string" ? cleanValue(record.endorsementNumber) : void 0,
9376
9169
  limits,
9377
9170
  sourceNodeIds: sourceNodeIds2,
@@ -9457,7 +9250,6 @@ function mergeOperationalProfile(base, candidate, validNodeIds, validSpanIds) {
9457
9250
  expirationDate,
9458
9251
  retroactiveDate,
9459
9252
  premium,
9460
- coverageTypes: Array.isArray(candidate.coverageTypes) && candidate.coverageTypes.length > 0 ? candidate.coverageTypes : base.coverageTypes,
9461
9253
  coverages,
9462
9254
  parties,
9463
9255
  endorsementSupport,
@@ -9492,7 +9284,6 @@ var OperationalProfileCleanupSchema = import_zod41.z.object({
9492
9284
  deductible: import_zod41.z.string().nullable().optional(),
9493
9285
  premium: import_zod41.z.string().nullable().optional(),
9494
9286
  retroactiveDate: import_zod41.z.string().nullable().optional(),
9495
- coverageOrigin: import_zod41.z.enum(["core", "endorsement"]).optional(),
9496
9287
  sourceNodeIds: import_zod41.z.array(import_zod41.z.string()).optional(),
9497
9288
  sourceSpanIds: import_zod41.z.array(import_zod41.z.string()).optional(),
9498
9289
  termDecisions: import_zod41.z.array(import_zod41.z.object({
@@ -9537,7 +9328,6 @@ function compactCoverageForCleanup(coverage, coverageIndex) {
9537
9328
  deductible: coverage.deductible,
9538
9329
  premium: coverage.premium,
9539
9330
  retroactiveDate: coverage.retroactiveDate,
9540
- coverageOrigin: coverage.coverageOrigin,
9541
9331
  sourceNodeIds: compactIds(coverage.sourceNodeIds),
9542
9332
  sourceSpanIds: compactIds(coverage.sourceSpanIds),
9543
9333
  terms: coverage.limits.map((term, termIndex) => ({
@@ -9613,7 +9403,7 @@ function selectCoverageCleanupNodes(sourceTree, coverages) {
9613
9403
  ...coverage.sourceNodeIds,
9614
9404
  ...coverage.limits.flatMap((term) => term.sourceNodeIds)
9615
9405
  ]));
9616
- const coveragePages2 = /* @__PURE__ */ new Set();
9406
+ const coveragePages = /* @__PURE__ */ new Set();
9617
9407
  const coverageTerms = uniqueStrings(coverages.flatMap(
9618
9408
  (coverage) => coverageTextForSelection(coverage).toLowerCase().split(/[^a-z0-9$,.]+/i).filter((part) => part.length >= 5)
9619
9409
  ));
@@ -9621,8 +9411,8 @@ function selectCoverageCleanupNodes(sourceTree, coverages) {
9621
9411
  const node = nodeById.get(id);
9622
9412
  if (!node) continue;
9623
9413
  addNode(node, 1e3);
9624
- if (node.pageStart) coveragePages2.add(node.pageStart);
9625
- if (node.pageEnd) coveragePages2.add(node.pageEnd);
9414
+ if (node.pageStart) coveragePages.add(node.pageStart);
9415
+ if (node.pageEnd) coveragePages.add(node.pageEnd);
9626
9416
  let parentId = node.parentId;
9627
9417
  let parentScore = 940;
9628
9418
  while (parentId) {
@@ -9645,7 +9435,7 @@ function selectCoverageCleanupNodes(sourceTree, coverages) {
9645
9435
  }
9646
9436
  for (const node of sourceTree) {
9647
9437
  if (node.kind === "document") continue;
9648
- if (!node.pageStart || !coveragePages2.has(node.pageStart)) continue;
9438
+ if (!node.pageStart || !coveragePages.has(node.pageStart)) continue;
9649
9439
  const text = nodeTextForSelection(node);
9650
9440
  if (CLEANUP_KEYWORD.test(text) || nodeTextMatchesCoverage(node, coverageTerms)) {
9651
9441
  addNode(node, 600);
@@ -9666,7 +9456,6 @@ function buildOperationalProfileCleanupPrompt(sourceTree, profile, options = {})
9666
9456
  const candidate = {
9667
9457
  documentType: profile.documentType,
9668
9458
  policyTypes: profile.policyTypes,
9669
- coverageTypes: profile.coverageTypes,
9670
9459
  coverages: coverageEntries.map(({ coverage, coverageIndex }) => compactCoverageForCleanup(coverage, coverageIndex))
9671
9460
  };
9672
9461
  return `Review and clean a source-backed operational profile projection for an insurance policy.
@@ -9852,7 +9641,6 @@ function applyCoverageCleanupDecision(coverage, decision, validNodeIds, validSpa
9852
9641
  };
9853
9642
  const name = cleanProfileValue(decision.name);
9854
9643
  if (name) next.name = name;
9855
- if (decision.coverageOrigin) next.coverageOrigin = decision.coverageOrigin;
9856
9644
  if (decision.limit != null) {
9857
9645
  const value = cleanProfileValue(decision.limit);
9858
9646
  if (value) next.limit = value;
@@ -9948,7 +9736,6 @@ function applyOperationalProfileCleanup(profile, cleanup, validNodeIds, validSpa
9948
9736
  const nextProfile = {
9949
9737
  ...profile,
9950
9738
  coverages,
9951
- coverageTypes: uniqueStrings(coverages.map((coverage) => coverage.name)),
9952
9739
  warnings: uniqueStrings([
9953
9740
  ...profile.warnings,
9954
9741
  ...cleanupWarnings.map((warning) => `Operational profile cleanup warning: ${warning}`)
@@ -9969,9 +9756,9 @@ var ORGANIZABLE_KINDS = [
9969
9756
  "schedule",
9970
9757
  "clause"
9971
9758
  ];
9972
- var ORGANIZATION_TOP_LEVEL_BATCH_SIZE = 80;
9973
- var ORGANIZER_MAX_SOURCE_SPANS = 400;
9974
- var ORGANIZER_MAX_TOP_LEVEL_NODES = 18;
9759
+ var ORGANIZATION_TOP_LEVEL_BATCH_SIZE = 12;
9760
+ var ORGANIZER_MAX_TOP_LEVEL_NODES = 120;
9761
+ var ORGANIZER_MAX_BATCH_NODES = 180;
9975
9762
  var OUTLINE_CLEANUP_MAX_TOP_LEVEL_NODES = 80;
9976
9763
  var SourceTreeOrganizationSchema = import_zod42.z.object({
9977
9764
  labels: import_zod42.z.array(import_zod42.z.object({
@@ -9997,26 +9784,10 @@ var SourceTreeOrganizationSchema = import_zod42.z.object({
9997
9784
  kind: import_zod42.z.enum(ORGANIZABLE_KINDS),
9998
9785
  title: import_zod42.z.string(),
9999
9786
  description: import_zod42.z.string().optional(),
9787
+ parentNodeId: import_zod42.z.string().optional(),
10000
9788
  childNodeIds: import_zod42.z.array(import_zod42.z.string()).min(1)
10001
9789
  }))
10002
9790
  });
10003
- var SourceTreeVisualTableRepairSchema = import_zod42.z.object({
10004
- tables: import_zod42.z.array(import_zod42.z.object({
10005
- tableNodeId: import_zod42.z.string(),
10006
- columnLabels: import_zod42.z.array(import_zod42.z.object({
10007
- columnIndex: import_zod42.z.number().int().nonnegative(),
10008
- label: import_zod42.z.string()
10009
- })).default([]),
10010
- continuationRows: import_zod42.z.array(import_zod42.z.object({
10011
- sourceRowNodeId: import_zod42.z.string(),
10012
- targetRowNodeId: import_zod42.z.string(),
10013
- targetColumnIndex: import_zod42.z.number().int().nonnegative().optional(),
10014
- targetColumnLabel: import_zod42.z.string().optional(),
10015
- reason: import_zod42.z.string().optional()
10016
- })).default([])
10017
- })).default([]),
10018
- warnings: import_zod42.z.array(import_zod42.z.string()).default([])
10019
- });
10020
9791
  var SourceBackedValueForPromptSchema = import_zod42.z.object({
10021
9792
  value: import_zod42.z.string(),
10022
9793
  normalizedValue: import_zod42.z.string().optional(),
@@ -10035,7 +9806,6 @@ var OperationalProfilePromptSchema = import_zod42.z.object({
10035
9806
  expirationDate: SourceBackedValueForPromptSchema.optional(),
10036
9807
  retroactiveDate: SourceBackedValueForPromptSchema.optional(),
10037
9808
  premium: SourceBackedValueForPromptSchema.optional(),
10038
- coverageTypes: import_zod42.z.array(import_zod42.z.string()).optional(),
10039
9809
  coverages: import_zod42.z.array(import_zod42.z.object({
10040
9810
  name: import_zod42.z.string(),
10041
9811
  coverageCode: import_zod42.z.string().optional(),
@@ -10045,7 +9815,6 @@ var OperationalProfilePromptSchema = import_zod42.z.object({
10045
9815
  retroactiveDate: import_zod42.z.string().optional(),
10046
9816
  formNumber: import_zod42.z.string().optional(),
10047
9817
  sectionRef: import_zod42.z.string().optional(),
10048
- coverageOrigin: import_zod42.z.enum(["core", "endorsement"]).optional(),
10049
9818
  endorsementNumber: import_zod42.z.string().optional(),
10050
9819
  limits: import_zod42.z.array(import_zod42.z.object({
10051
9820
  kind: OperationalCoverageTermKindSchema.optional(),
@@ -10235,13 +10004,18 @@ function pageHeadingTitleFromText(text, fallback) {
10235
10004
  return fallback;
10236
10005
  }
10237
10006
  function pageFormTypeFromText(text) {
10007
+ if (hasSubstantiveDeclarationsScheduleText(text)) return "declarations";
10238
10008
  if (/\b(declarations?\s+page|declarations?\s+schedule)\b/i.test(text)) return "declarations";
10239
10009
  if (/\b(endorsement\s+(?:no\.?|number|#)|this endorsement changes the policy|[A-Z]{2,}-END\s+\d{2,})\b/i.test(text)) return "endorsement";
10240
10010
  if (/\b(technology errors?\s*&?\s*omissions.*liability insurance policy|policy form|coverage form|insuring agreement|definitions?|exclusions?|conditions?)\b/i.test(text)) return "coverage";
10241
10011
  if (/\b(important notice|privacy notice|ofac advisory|terrorism risk insurance act|tria|trade or economic sanctions)\b/i.test(text)) return "notice";
10242
10012
  return "other";
10243
10013
  }
10014
+ function hasSubstantiveDeclarationsScheduleText(text) {
10015
+ return /\bitem\s+\d+\.?\s*(?:named insured|policy number|policy period|renewal|form of business|coverage parts?|limits?|premium|extended reporting|producer|forms? and endorsements?)\b/i.test(text) || /\bforms? and endorsements attached at inception\b/i.test(text) || /\bcoverage parts?,?\s+limits? of liability,?\s+deductibles?,?\s+and retroactive dates\b/i.test(text) || /\bannual premium\s*\(all coverage parts?\)\b/i.test(text) || /\berp option\b/i.test(text) || /\bproducer\b[\s\S]{0,240}\blicense\b/i.test(text);
10016
+ }
10244
10017
  function administrativeFormTypeFromText(text) {
10018
+ if (hasSubstantiveDeclarationsScheduleText(text)) return void 0;
10245
10019
  if (/\b(important notice|privacy notice|ofac advisory|terrorism risk insurance act|tria|trade or economic sanctions|economic sanctions limitation|how to report a claim)\b/i.test(text)) {
10246
10020
  return "notice";
10247
10021
  }
@@ -10642,6 +10416,7 @@ function isDeclarationsNode(node) {
10642
10416
  }
10643
10417
  function isAdministrativeNoticeNode(node) {
10644
10418
  const text = sourceNodeText(node);
10419
+ if (hasSubstantiveDeclarationsScheduleText(text)) return false;
10645
10420
  return /\b(specimen policy|policy jacket|important notice|privacy notice|ofac advisory|terrorism risk insurance act|tria|trade or economic sanctions|economic sanctions limitation|signature|countersignature|how to report a claim)\b/i.test(text);
10646
10421
  }
10647
10422
  function mergeAdministrativeNoticesIntoFrontMatter(sourceTree) {
@@ -11159,18 +10934,36 @@ function rootChildren(sourceTree) {
11159
10934
  const rootId = sourceTreeRootId(sourceTree);
11160
10935
  return (byParent.get(rootId) ?? []).filter((node) => node.kind !== "document");
11161
10936
  }
11162
- function hasDeterministicSemanticOutline(sourceTree) {
11163
- const children = rootChildren(sourceTree);
11164
- const semanticCount = children.filter(
11165
- (node) => node.kind === "page_group" || node.kind === "form" || node.kind === "endorsement" || node.kind === "section" || node.kind === "schedule"
11166
- ).length;
11167
- return semanticCount >= 2 || children.some((node) => node.title === "Declarations") || children.some((node) => node.title === "Policy Form") || children.some((node) => node.title === "Endorsements");
11168
- }
11169
- function shouldRunSourceTreeOrganizer(sourceTree, sourceSpans) {
10937
+ function shouldRunSourceTreeOrganizer(sourceTree, _sourceSpans) {
11170
10938
  const topLevelCount = rootChildren(sourceTree).length;
11171
- if (sourceSpans.length > ORGANIZER_MAX_SOURCE_SPANS) return false;
11172
10939
  if (topLevelCount > ORGANIZER_MAX_TOP_LEVEL_NODES) return false;
11173
- return !hasDeterministicSemanticOutline(sourceTree);
10940
+ return true;
10941
+ }
10942
+ function organizationCandidateText(node) {
10943
+ return [node.title, node.description, node.textExcerpt].filter(Boolean).join(" ");
10944
+ }
10945
+ function isHighSignalOrganizationNode(node) {
10946
+ if (node.kind === "document") return false;
10947
+ if (["page", "page_group", "form", "endorsement", "section", "schedule", "clause", "table", "table_row"].includes(node.kind)) {
10948
+ return true;
10949
+ }
10950
+ if (node.kind !== "text" && node.kind !== "table_cell") return false;
10951
+ const text = organizationCandidateText(node);
10952
+ return /\b(SECTION|PART|ARTICLE|SCHEDULE)\s+[IVXLCDM0-9]+/i.test(text) || /\bItem\s+\d+[\.:]/i.test(text) || /^[A-Z]\.\s+\S/.test(cleanText(node.textExcerpt ?? node.title, "")) || /\b(forms? and endorsements?|coverage parts?|limits? of liability|extended reporting period|producer|premium|aggregate|retroactive date|endorsement no\.?)\b/i.test(text);
10953
+ }
10954
+ function organizationBatchNodes(topLevelBatch, byParent) {
10955
+ const nodes = /* @__PURE__ */ new Map();
10956
+ const queue = [...topLevelBatch];
10957
+ while (queue.length > 0 && nodes.size < ORGANIZER_MAX_BATCH_NODES) {
10958
+ const node = queue.shift();
10959
+ if (!node || nodes.has(node.id) || !isHighSignalOrganizationNode(node)) continue;
10960
+ nodes.set(node.id, node);
10961
+ for (const child of byParent.get(node.id) ?? []) {
10962
+ if (nodes.size + queue.length >= ORGANIZER_MAX_BATCH_NODES) break;
10963
+ if (isHighSignalOrganizationNode(child)) queue.push(child);
10964
+ }
10965
+ }
10966
+ return [...nodes.values()];
11174
10967
  }
11175
10968
  function organizationBatches(sourceTree) {
11176
10969
  const byParent = nodesByParent(sourceTree);
@@ -11187,14 +10980,10 @@ function organizationBatches(sourceTree) {
11187
10980
  const batches = [];
11188
10981
  for (let index = 0; index < topLevelNodes.length; index += ORGANIZATION_TOP_LEVEL_BATCH_SIZE) {
11189
10982
  const topLevelBatch = topLevelNodes.slice(index, index + ORGANIZATION_TOP_LEVEL_BATCH_SIZE);
11190
- const candidates = /* @__PURE__ */ new Map();
11191
- for (const node of topLevelBatch) {
11192
- candidates.set(node.id, node);
11193
- }
11194
10983
  batches.push({
11195
10984
  label: `top-level nodes ${index + 1}-${index + topLevelBatch.length} of ${topLevelNodes.length}`,
11196
10985
  topLevelNodeIds: topLevelBatch.map((node) => node.id),
11197
- nodes: [...candidates.values()]
10986
+ nodes: organizationBatchNodes(topLevelBatch, byParent)
11198
10987
  });
11199
10988
  }
11200
10989
  return batches;
@@ -11207,7 +10996,7 @@ function mergeOrganizationResults(results) {
11207
10996
  labels.set(label.nodeId, { ...labels.get(label.nodeId), ...label });
11208
10997
  }
11209
10998
  for (const group of result.groups) {
11210
- const key = `${group.kind}:${group.childNodeIds.join("|")}`;
10999
+ const key = `${group.parentNodeId ?? ""}:${group.kind}:${group.childNodeIds.join("|")}`;
11211
11000
  groups.set(key, group);
11212
11001
  }
11213
11002
  }
@@ -11231,9 +11020,16 @@ ${formatFormHintsForPrompt(formHints)}
11231
11020
  Rules:
11232
11021
  - Use only node IDs from the provided list.
11233
11022
  - Do not invent text, page numbers, source spans, limits, or policy facts.
11234
- - You may relabel existing nodes and group adjacent top-level/page nodes from this batch only when they are clearly one continuous form, one declarations set, one schedule, or one clause family.
11023
+ - You may relabel existing nodes and group adjacent sibling nodes from this batch only when they are clearly one continuous form, one declarations item, one policy section, one schedule, or one clause family.
11235
11024
  - Treat the form inventory as a page-range hint for the expected order: front matter/notices, declarations, policy form, then endorsements.
11236
11025
  - Prefer section hierarchy from printed title elements inside a form over page-by-page grouping.
11026
+ - Printed section markers are hard hierarchy boundaries. If source text moves from "SECTION XI" to "SECTION XII", "Section 12", "PART III", or similar sequential headings, create a new sibling section at that marker even when the marker appears mid-page after prior section text.
11027
+ - Declarations pages often use "Item 1.", "Item 2.", ... as the real section structure. Preserve each item as its own section or schedule under "Declarations"; do not bury item labels inside a single table when they mark new declaration fields.
11028
+ - For declaration item tables, a table belongs only to the current item until the next "Item N" marker. Start a new declaration item section at the next marker, even if the parser presents the marker as a table row or cell.
11029
+ - Keep forms-and-endorsements schedules attached to declarations when they appear as "Item 10", "Forms and Endorsements Attached at Inception", or a continuation page listing form numbers. Do not discard that page just because it also contains countersignature or authorized-representative language.
11030
+ - Prefer sections/schedules over table grouping when a table-like node mixes structural labels such as "Item 7", "Item 8", "SECTION XII", "Producer", or "Forms and Endorsements" with values.
11031
+ - Use group.parentNodeId only when the source clearly shows a child was nested under the wrong earlier section/table. Example: a "SECTION XII" marker nested below "SECTION XI" should be grouped with parentNodeId set to the Policy Form node so Section XII becomes a sibling of Section XI.
11032
+ - Use group.parentNodeId to place "Item N" groups under the Declarations node when parser table structure would otherwise leave those items trapped inside one table.
11237
11033
  - Group adjacent separately numbered endorsements under a single generic "Endorsements" page_group parent, with each individual endorsement preserved as its own child node.
11238
11034
  - Never create rollup titles such as "Endorsements 1-3 (...)" or merge multiple endorsements into one endorsement node.
11239
11035
  - Add concise, human-readable titles to generic text, table, row, and cell nodes when the text makes their role clear.
@@ -11264,7 +11060,7 @@ function buildOutlineCleanupPrompt(sourceTree, formHints) {
11264
11060
 
11265
11061
  Expected product-facing order:
11266
11062
  1. Optional front matter: policy jacket, important notices, privacy notices, OFAC notices, TRIA/terrorism notices, marketing/admin pages, signatures, countersignatures, or other pages that are not the declarations, policy wording, or endorsements.
11267
- 2. Declarations: declarations page(s), schedules, named insured/policy period/premium rows, coverage limit schedules, forms-and-endorsements schedules.
11063
+ 2. Declarations: declarations page(s), schedules, itemized declaration fields, named insured/policy period/premium rows, coverage limit schedules, forms-and-endorsements schedules.
11268
11064
  3. Policy Form: the main policy wording, insuring agreements, definitions, exclusions, conditions, claim provisions, and general policy terms.
11269
11065
  4. Endorsements: one generic "Endorsements" page_group containing each separately numbered endorsement as its own child.
11270
11066
 
@@ -11278,7 +11074,9 @@ Rules:
11278
11074
  - Do not merge individually numbered endorsements into one endorsement node; use the generic "Endorsements" parent for the series.
11279
11075
  - Use canonical terse titles: "Notices and Jacket", "Declarations", "Policy Form", "Endorsements", or the printed endorsement number.
11280
11076
  - Keep page_group descriptions short and include the page range when pages are known, for example "Declarations pages 6-8".
11281
- - If a page is an OFAC, privacy, terrorism/TRIA, claim-reporting notice, signature page, or jacket, do not label it as declarations or policy form.
11077
+ - If a page is only an OFAC, privacy, terrorism/TRIA, claim-reporting notice, signature page, or jacket, do not label it as declarations or policy form.
11078
+ - If a page contains declaration items, coverage schedules, premium rows, producer rows, or a forms-and-endorsements schedule, keep it in Declarations even if it also contains countersignature or authorized-representative text.
11079
+ - If a policy-form page contains a later printed section marker such as "SECTION XII \u2014 EXTENDED REPORTING PERIOD", preserve that marker as the start of a new sibling section rather than a paragraph under the previous section.
11282
11080
  - If the form inventory provides page ranges, keep groups aligned to those ranges unless the source node text clearly contradicts them.
11283
11081
  - If the existing deterministic outline is already correct, return empty labels and groups.
11284
11082
 
@@ -11300,7 +11098,6 @@ function emptyOperationalProfile() {
11300
11098
  return {
11301
11099
  documentType: "policy",
11302
11100
  policyTypes: ["other"],
11303
- coverageTypes: [],
11304
11101
  coverages: [],
11305
11102
  parties: [],
11306
11103
  endorsementSupport: [],
@@ -11324,6 +11121,10 @@ Rules:
11324
11121
  - Every returned value must include sourceNodeIds or sourceSpanIds from the provided nodes.
11325
11122
  - If a value is not directly supported, omit it.
11326
11123
  - Prefer declarations, schedules, premium tables, and endorsement schedules over generic policy wording.
11124
+ - On declarations pages, treat "Item N" labels as section boundaries. Use Item 6 or equivalent coverage-schedule rows for coverage limits, deductibles, aggregate terms, and retroactive dates; do not merge Item 7 premium, Item 8 ERP, Item 9 producer, or Item 10 forms into Item 6 coverage facts.
11125
+ - A coverage schedule row's coverage name should come from the "Coverage Part" or equivalent row label. Limit, deductible, aggregate, sublimit, retention, and retroactive-date values belong as nested terms under that coverage, not in the coverage title.
11126
+ - If a coverage schedule continues onto the next page before the next item marker, include the continuation rows in the same coverage or declaration item.
11127
+ - Forms-and-endorsements schedules are operational form inventory evidence, not coverage limits. Do not turn form schedule rows into coverage units unless the row also states a coverage-specific limit or deductible.
11327
11128
  - Keep each coverage unit tied to one evidence scope: a declaration/core schedule row, a core policy form section, or one specific endorsement schedule. Do not merge declaration facts and endorsement schedule facts into the same coverage unit, even when they use the same coverage name.
11328
11129
  - If the declarations schedule and an endorsement schedule both list Network Security, Social Engineering Fraud, Regulatory Proceedings, or another same-named coverage, return separate coverage units for each supported source scope.
11329
11130
  - Use the declaration coverage name for declaration/core schedule rows. Use the endorsement title or endorsement schedule coverage name for endorsement rows, and include formNumber and endorsementNumber when source-backed.
@@ -11331,7 +11132,6 @@ Rules:
11331
11132
  - Treat an endorsement as one coverage unit when it contains a schedule. Do not split an endorsement schedule into generic rows like "Aggregate Limit".
11332
11133
  - For coverage schedules, put each claim, aggregate, sublimit, retention, deductible, and retroactive date values in coverages[].limits with labels and source IDs. Keep the legacy coverages[].limit as the primary display value only.
11333
11134
  - Extract coinsurance, participation percentage, or insurer/named-insured split terms as coverages[].limits entries with kind "other" when they are part of a coverage schedule.
11334
- - Use coverageOrigin: "endorsement" for endorsement units and "core" for declarations/core policy coverage units.
11335
11135
  - Do not copy entire policy wording into fields.
11336
11136
  - Extract facts directly from source nodes. There is no deterministic fact baseline.
11337
11137
 
@@ -11340,15 +11140,6 @@ ${JSON.stringify(nodes, null, 2)}
11340
11140
 
11341
11141
  Return JSON for the operational profile.`;
11342
11142
  }
11343
- var VISUAL_TABLE_REPAIR_MAX_TABLES = 4;
11344
- var VISUAL_TABLE_REPAIR_MAX_ROWS = 28;
11345
- var VISUAL_TABLE_REPAIR_MAX_CELLS = 140;
11346
- function isSourceTreeHeaderRow(row) {
11347
- return row.metadata?.isHeader === true || row.metadata?.isHeader === "true";
11348
- }
11349
- function tableCellText(cell) {
11350
- return cleanText(cell.textExcerpt ?? cell.description ?? cell.title, "");
11351
- }
11352
11143
  function tableCellValueText(cell) {
11353
11144
  return cleanText(cell.textExcerpt ?? cell.description ?? "", "");
11354
11145
  }
@@ -11402,526 +11193,10 @@ function normalizeSourceTreeTableDisplayText(sourceTree) {
11402
11193
  if (updates.size === 0) return sourceTree;
11403
11194
  return sourceTree.map((node) => updates.get(node.id) ?? node);
11404
11195
  }
11405
- function tableRowTextForPrompt(row, cells) {
11406
- return cleanText(
11407
- cells.length ? cells.map(tableCellText).filter(Boolean).join(" | ") : row.textExcerpt ?? row.description ?? row.title,
11408
- row.title
11409
- );
11410
- }
11411
11196
  function tableCellColumnIndex(cell, fallbackIndex) {
11412
11197
  const metadataIndex = cell.metadata?.columnIndex;
11413
11198
  return typeof metadataIndex === "number" && Number.isInteger(metadataIndex) ? metadataIndex : fallbackIndex;
11414
11199
  }
11415
- function isGenericColumnTitle(value) {
11416
- const title = cleanText(value, "");
11417
- return !title || /^(?:column\s+\d+|table cell|value)$/i.test(title);
11418
- }
11419
- function metadataColumnName(metadata) {
11420
- const value = metadata?.columnName;
11421
- return typeof value === "string" ? cleanText(value, "") || void 0 : void 0;
11422
- }
11423
- function metadataTableColumnName(metadata) {
11424
- const table = metadata?.table;
11425
- if (!table || typeof table !== "object" || Array.isArray(table)) return void 0;
11426
- if (!("columnName" in table)) return void 0;
11427
- const value = table.columnName;
11428
- return typeof value === "string" ? cleanText(value, "") || void 0 : void 0;
11429
- }
11430
- function bboxSummary(node) {
11431
- const box = node.bbox?.[0];
11432
- if (!box) return void 0;
11433
- const round = (value) => Math.round(value * 10) / 10;
11434
- return {
11435
- page: box.page,
11436
- x: round(box.x),
11437
- y: round(box.y),
11438
- width: round(box.width),
11439
- height: round(box.height)
11440
- };
11441
- }
11442
- function tableRowsWithCells(table, byParent) {
11443
- return (byParent.get(table.id) ?? []).filter((node) => node.kind === "table_row").map((row) => ({
11444
- row,
11445
- cells: (byParent.get(row.id) ?? []).filter((child) => child.kind === "table_cell").sort(
11446
- (left, right) => tableCellColumnIndex(left, 0) - tableCellColumnIndex(right, 0) || left.order - right.order || left.id.localeCompare(right.id)
11447
- )
11448
- })).sort((left, right) => left.row.order - right.row.order || left.row.id.localeCompare(right.row.id));
11449
- }
11450
- function primaryHeaderColumnCount(rows) {
11451
- const header = rows.find(({ row, cells }) => isSourceTreeHeaderRow(row) && cells.length > 1);
11452
- if (header) return header.cells.length;
11453
- return Math.max(0, ...rows.map(({ cells }) => cells.length));
11454
- }
11455
- function visualTableRepairScore(candidate) {
11456
- const rows = candidate.rows;
11457
- if (rows.length < 3) return 0;
11458
- const headerCount = primaryHeaderColumnCount(rows);
11459
- if (headerCount < 2) return 0;
11460
- const firstHeaderIndex = rows.findIndex(({ row, cells }) => isSourceTreeHeaderRow(row) && cells.length > 1);
11461
- const repeatedHeader = firstHeaderIndex >= 0 && rows.some(({ row }, index) => index > firstHeaderIndex && isSourceTreeHeaderRow(row));
11462
- const shortContinuation = rows.some(
11463
- ({ row, cells }, index) => index > 0 && !isSourceTreeHeaderRow(row) && cells.length > 0 && cells.length < headerCount && !/^(?:item\s+\d+|[A-Z]\.)\b/i.test(tableCellText(cells[0]))
11464
- );
11465
- const genericDataLabels = rows.some(
11466
- ({ row, cells }) => !isSourceTreeHeaderRow(row) && cells.length >= 2 && cells.some((cell) => isGenericColumnTitle(cell.title))
11467
- );
11468
- const danglingSlash = rows.some(
11469
- ({ row, cells }) => !isSourceTreeHeaderRow(row) && /\/\s*$/.test(tableRowTextForPrompt(row, cells))
11470
- );
11471
- return (repeatedHeader ? 4 : 0) + (danglingSlash ? 3 : 0) + (shortContinuation ? 3 : 0) + (genericDataLabels ? 2 : 0);
11472
- }
11473
- function visualTableCandidates(sourceTree) {
11474
- const byParent = nodesByParent(sourceTree);
11475
- return sourceTree.filter((node) => node.kind === "table" && typeof node.pageStart === "number").map((table) => ({
11476
- table,
11477
- page: table.pageStart,
11478
- rows: tableRowsWithCells(table, byParent)
11479
- })).map((candidate) => ({ ...candidate, repairScore: visualTableRepairScore(candidate) })).filter((candidate) => candidate.repairScore > 0).sort(
11480
- (left, right) => right.repairScore - left.repairScore || left.page - right.page || left.table.order - right.table.order || left.table.id.localeCompare(right.table.id)
11481
- ).slice(0, VISUAL_TABLE_REPAIR_MAX_TABLES).map(({ repairScore: _repairScore, ...candidate }) => candidate);
11482
- }
11483
- function compactVisualTableCandidate(candidate) {
11484
- let cellCount = 0;
11485
- const rows = candidate.rows.slice(0, VISUAL_TABLE_REPAIR_MAX_ROWS).map(({ row, cells }) => {
11486
- const compactCells = cells.slice(0, Math.max(0, VISUAL_TABLE_REPAIR_MAX_CELLS - cellCount)).map((cell, index) => ({
11487
- cellNodeId: cell.id,
11488
- columnIndex: tableCellColumnIndex(cell, index),
11489
- currentColumnName: cell.title,
11490
- text: tableCellText(cell),
11491
- bbox: bboxSummary(cell)
11492
- }));
11493
- cellCount += compactCells.length;
11494
- return {
11495
- rowNodeId: row.id,
11496
- order: row.order,
11497
- isHeader: isSourceTreeHeaderRow(row),
11498
- text: tableRowTextForPrompt(row, cells),
11499
- bbox: bboxSummary(row),
11500
- cells: compactCells
11501
- };
11502
- });
11503
- return {
11504
- tableNodeId: candidate.table.id,
11505
- page: candidate.page,
11506
- title: candidate.table.title,
11507
- bbox: bboxSummary(candidate.table),
11508
- rows
11509
- };
11510
- }
11511
- function buildVisualTableRepairPrompt(candidate) {
11512
- return `Compare a parsed insurance source table against the original page visual layout.
11513
-
11514
- If a page image is attached, use it as the primary reference. If no image is available, use the bbox coordinates below as the visual layout reference.
11515
-
11516
- Task:
11517
- - Identify rows that are not real standalone rows because they are visually wrapped continuation text for a nearby row.
11518
- - Identify the primary printed column labels for the table.
11519
-
11520
- Rules:
11521
- - Return only high-confidence repairs.
11522
- - Use only rowNodeId/tableNodeId/cellNodeId values from the provided JSON.
11523
- - Do not invent policy facts, values, row text, source spans, or page numbers.
11524
- - continuationRows.sourceRowNodeId must be a parsed row that should be removed as a standalone row.
11525
- - continuationRows.targetRowNodeId must be the row that visually owns that wrapped text, usually the immediately previous non-header row.
11526
- - targetColumnIndex/targetColumnLabel should point to the visual column that owns the wrapped text, usually the limit/amount/value column.
11527
- - Do not mark actual data rows as continuations when they begin a new item, coverage part, endorsement, form, location, person, or premium/tax row.
11528
- - columnLabels should be the primary visual header labels, not later wrapped cell text that the parser misread as a header.
11529
-
11530
- Parsed table with visual coordinates:
11531
- ${JSON.stringify(compactVisualTableCandidate(candidate), null, 2)}
11532
-
11533
- Return JSON with tables[].columnLabels and tables[].continuationRows. Return empty arrays if no repair is needed.`;
11534
- }
11535
- function sourceSpanIdsForNodes(nodes) {
11536
- return [...new Set(nodes.flatMap((node) => node.sourceSpanIds))];
11537
- }
11538
- function appendDistinctText(base, addition) {
11539
- const current = cleanText(base, "");
11540
- const next = cleanText(addition, "");
11541
- if (!current) return next || void 0;
11542
- if (!next) return current;
11543
- if (current.toLowerCase().includes(next.toLowerCase())) return current;
11544
- const joinsWithSpace = /(?:[/(:;-]|,\s*)$/.test(current) || /\b(?:part of|including|subject to|not in addition to)$/i.test(current) || /^(?:aggregate|claim|loss|proceeding|occurrence|each\s+(?:claim|loss|proceeding|occurrence)|coverage\s+part\b)/i.test(next);
11545
- const delimiter = joinsWithSpace ? " " : " / ";
11546
- return cleanText(`${current}${delimiter}${next}`, current);
11547
- }
11548
- function mergedBbox(nodes) {
11549
- const boxes = nodes.flatMap((node) => node.bbox ?? []);
11550
- return boxes.length ? boxes.slice(0, 12) : void 0;
11551
- }
11552
- function normalizedRepairLabel(value) {
11553
- const label = cleanText(value, "");
11554
- if (!label || label.length > 80) return void 0;
11555
- if (/^(?:source|page|row|table)$/i.test(label)) return void 0;
11556
- return label;
11557
- }
11558
- function findCellForContinuation(params) {
11559
- if (typeof params.targetColumnIndex === "number") {
11560
- const byIndex = params.cells.find(
11561
- (cell, index) => tableCellColumnIndex(cell, index) === params.targetColumnIndex
11562
- );
11563
- if (byIndex) return byIndex;
11564
- }
11565
- const label = normalizedRepairLabel(params.targetColumnLabel);
11566
- if (label) {
11567
- const byLabel = params.cells.find(
11568
- (cell) => cleanText(cell.title, "").toLowerCase() === label.toLowerCase()
11569
- );
11570
- if (byLabel) return byLabel;
11571
- }
11572
- return params.cells[1] ?? params.cells[params.cells.length - 1];
11573
- }
11574
- function bboxCenterX(node) {
11575
- const box = node.bbox?.[0];
11576
- if (!box) return void 0;
11577
- return box.x + box.width / 2;
11578
- }
11579
- function findCellByVisualPosition(sourceCell, targetCells) {
11580
- const sourceX = bboxCenterX(sourceCell);
11581
- if (sourceX === void 0) return void 0;
11582
- const positioned = targetCells.map((cell) => ({ cell, centerX: bboxCenterX(cell) })).filter(
11583
- (entry) => entry.centerX !== void 0
11584
- );
11585
- if (positioned.length === 0) return void 0;
11586
- positioned.sort(
11587
- (left, right) => Math.abs(left.centerX - sourceX) - Math.abs(right.centerX - sourceX)
11588
- );
11589
- return positioned[0]?.cell;
11590
- }
11591
- function isDateLikeColumn(label) {
11592
- return /\b(?:date|effective|expiration|retroactive)\b/i.test(cleanText(label, ""));
11593
- }
11594
- function containsDateValue(text) {
11595
- return /\b\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b/.test(text) || /\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?\s+\d{1,2},?\s+\d{2,4}\b/i.test(text);
11596
- }
11597
- function looksLikePolicyProse(text) {
11598
- const words = text.split(/\s+/).filter(Boolean);
11599
- if (words.length < 8) return false;
11600
- return /\b(?:are|is|will|shall|must|may|includes?|included|reduce|subject|payment|terms?|conditions?|provided|pursuant)\b/i.test(text);
11601
- }
11602
- function shouldMergeVisualContinuation(params) {
11603
- if (startsNewVisualTableItem(params.sourceCells)) return false;
11604
- const targetLabel = params.targetCell?.title;
11605
- if (isDateLikeColumn(targetLabel) && !containsDateValue(params.sourceText)) return false;
11606
- if (looksLikePolicyProse(params.sourceText) && !/\b(?:description|coverage|remarks?|notes?)\b/i.test(cleanText(targetLabel, ""))) {
11607
- return false;
11608
- }
11609
- return true;
11610
- }
11611
- function columnLabelStartIndex(rows) {
11612
- const headerIndex = rows.findIndex(
11613
- ({ row, cells }) => isSourceTreeHeaderRow(row) && cells.length > 1
11614
- );
11615
- return headerIndex >= 0 ? headerIndex : 0;
11616
- }
11617
- function startsNewVisualTableItem(cells) {
11618
- const firstText = tableCellText(cells[0]);
11619
- return /^(?:item\s+\d+\b|[A-Z][.)]\s+|coverage\s+part\b|endorsement\s+(?:no\.?|number|#|\d+)\b)/i.test(firstText);
11620
- }
11621
- function rowMatchesColumnLabels(cells, columnLabels) {
11622
- if (columnLabels.size === 0 || cells.length < columnLabels.size) return false;
11623
- return cells.every((cell, index) => {
11624
- const label = columnLabels.get(tableCellColumnIndex(cell, index));
11625
- return !label || tableCellText(cell).toLowerCase() === label.toLowerCase();
11626
- });
11627
- }
11628
- function implicitContinuationRows(rows, columnLabels, firstLabelRowIndex) {
11629
- const continuations = [];
11630
- let targetRowId;
11631
- const targetColumnLabel = columnLabels.get(1);
11632
- for (const [rowIndex, { row, cells }] of rows.entries()) {
11633
- if (rowIndex < firstLabelRowIndex) continue;
11634
- if (rowIndex === firstLabelRowIndex && rowMatchesColumnLabels(cells, columnLabels)) continue;
11635
- if (startsNewVisualTableItem(cells)) {
11636
- targetRowId = row.id;
11637
- continue;
11638
- }
11639
- if (!targetRowId || cells.length === 0) continue;
11640
- const isSpuriousHeader = isSourceTreeHeaderRow(row) && !rowMatchesColumnLabels(cells, columnLabels);
11641
- const isShortContinuation = !isSourceTreeHeaderRow(row) && cells.length < Math.max(2, columnLabels.size);
11642
- if (!isSpuriousHeader && !isShortContinuation) continue;
11643
- continuations.push({
11644
- sourceRowNodeId: row.id,
11645
- targetRowNodeId: targetRowId,
11646
- targetColumnIndex: 1,
11647
- targetColumnLabel,
11648
- reason: "Continuation row inferred from repaired table header."
11649
- });
11650
- }
11651
- return continuations;
11652
- }
11653
- function metadataWithColumnLabel(metadata, label) {
11654
- const next = {
11655
- ...metadata ?? {},
11656
- columnName: label,
11657
- visualTableRepairColumnLabel: label
11658
- };
11659
- if (metadata?.table && typeof metadata.table === "object" && !Array.isArray(metadata.table)) {
11660
- next.table = {
11661
- ...metadata.table,
11662
- columnName: label
11663
- };
11664
- }
11665
- return next;
11666
- }
11667
- function tableCellDescription(cell, label) {
11668
- const text = tableCellText(cell);
11669
- return cleanText(
11670
- text && text.toLowerCase() !== label.toLowerCase() ? `${label} | ${text}` : label,
11671
- cell.description
11672
- );
11673
- }
11674
- function applyVisualTableRepair(sourceTree, repair) {
11675
- if (repair.tables.length === 0) return sourceTree;
11676
- const byId = new Map(sourceTree.map((node) => [node.id, node]));
11677
- const byParent = nodesByParent(sourceTree);
11678
- const updates = /* @__PURE__ */ new Map();
11679
- const removeIds = /* @__PURE__ */ new Set();
11680
- const rowsToRebuildText = /* @__PURE__ */ new Set();
11681
- const currentNode = (id) => updates.get(id) ?? byId.get(id);
11682
- for (const tableRepair of repair.tables) {
11683
- const table = byId.get(tableRepair.tableNodeId);
11684
- if (!table || table.kind !== "table") continue;
11685
- const rows = tableRowsWithCells(table, byParent);
11686
- const rowIds = new Set(rows.map(({ row }) => row.id));
11687
- const rowOrder = new Map(rows.map(({ row }, index) => [row.id, index]));
11688
- const columnLabels = /* @__PURE__ */ new Map();
11689
- for (const label of tableRepair.columnLabels) {
11690
- const normalized = normalizedRepairLabel(label.label);
11691
- if (normalized) columnLabels.set(label.columnIndex, normalized);
11692
- }
11693
- const firstLabelRowIndex = columnLabelStartIndex(rows);
11694
- if (columnLabels.size > 0) {
11695
- const normalizedLabels = new Set([...columnLabels.values()].map((label) => label.toLowerCase()));
11696
- for (const [rowIndex, { row, cells }] of rows.entries()) {
11697
- if (removeIds.has(row.id)) continue;
11698
- if (rowIndex < firstLabelRowIndex) {
11699
- for (const cell of cells) {
11700
- const metadataLabel = metadataColumnName(cell.metadata);
11701
- if (metadataLabel && isGenericColumnTitle(metadataLabel) && normalizedLabels.has(cleanText(cell.title, "").toLowerCase())) {
11702
- updates.set(cell.id, {
11703
- ...currentNode(cell.id) ?? cell,
11704
- title: metadataLabel,
11705
- description: tableCellDescription(cell, metadataLabel),
11706
- metadata: metadataWithColumnLabel(cell.metadata, metadataLabel)
11707
- });
11708
- rowsToRebuildText.add(row.id);
11709
- }
11710
- }
11711
- continue;
11712
- }
11713
- for (const [fallbackIndex, cell] of cells.entries()) {
11714
- const columnIndex = tableCellColumnIndex(cell, fallbackIndex);
11715
- const label = columnLabels.get(columnIndex);
11716
- if (!label) continue;
11717
- const current = currentNode(cell.id) ?? cell;
11718
- if (current.title === label && metadataColumnName(current.metadata) === label && (metadataTableColumnName(current.metadata) ?? label) === label) {
11719
- continue;
11720
- }
11721
- updates.set(cell.id, {
11722
- ...current,
11723
- title: label,
11724
- description: tableCellDescription(current, label),
11725
- metadata: metadataWithColumnLabel(current.metadata, label)
11726
- });
11727
- rowsToRebuildText.add(row.id);
11728
- }
11729
- if (cells.length > 0) rowsToRebuildText.add(row.id);
11730
- }
11731
- }
11732
- const continuationRows = [
11733
- ...tableRepair.continuationRows,
11734
- ...implicitContinuationRows(rows, columnLabels, firstLabelRowIndex)
11735
- ];
11736
- const seenContinuationRows = /* @__PURE__ */ new Set();
11737
- for (const continuation of continuationRows) {
11738
- const continuationKey = `${continuation.sourceRowNodeId}:${continuation.targetRowNodeId}`;
11739
- if (seenContinuationRows.has(continuationKey)) continue;
11740
- seenContinuationRows.add(continuationKey);
11741
- if (!rowIds.has(continuation.sourceRowNodeId) || !rowIds.has(continuation.targetRowNodeId)) continue;
11742
- if (continuation.sourceRowNodeId === continuation.targetRowNodeId) continue;
11743
- const sourceIndex = rowOrder.get(continuation.sourceRowNodeId);
11744
- const targetIndex = rowOrder.get(continuation.targetRowNodeId);
11745
- if (sourceIndex === void 0 || targetIndex === void 0) continue;
11746
- if (Math.abs(sourceIndex - targetIndex) > 3) continue;
11747
- const sourceRow = currentNode(continuation.sourceRowNodeId);
11748
- const targetRow = currentNode(continuation.targetRowNodeId);
11749
- if (!sourceRow || !targetRow || sourceRow.kind !== "table_row" || targetRow.kind !== "table_row") continue;
11750
- if (isSourceTreeHeaderRow(targetRow)) continue;
11751
- const sourceCells = (byParent.get(sourceRow.id) ?? []).filter((node) => node.kind === "table_cell").map((node) => currentNode(node.id) ?? node);
11752
- const targetCells = (byParent.get(targetRow.id) ?? []).filter((node) => node.kind === "table_cell").map((node) => currentNode(node.id) ?? node);
11753
- const sourceText = tableRowTextForPrompt(sourceRow, sourceCells);
11754
- if (!sourceText) continue;
11755
- const targetCell = findCellForContinuation({
11756
- cells: targetCells,
11757
- targetColumnIndex: continuation.targetColumnIndex,
11758
- targetColumnLabel: continuation.targetColumnLabel
11759
- });
11760
- if (!shouldMergeVisualContinuation({ sourceText, sourceCells, targetCell })) continue;
11761
- const sourceNodes = [sourceRow, ...sourceCells];
11762
- const sourceSpanIds = sourceSpanIdsForNodes(sourceNodes);
11763
- let mergedIntoCells = false;
11764
- if (sourceCells.length > 0 && targetCells.length > 0) {
11765
- for (const sourceCell of sourceCells) {
11766
- const cellText = tableCellValueText(sourceCell);
11767
- if (!cellText) continue;
11768
- const visualTargetCell = findCellByVisualPosition(sourceCell, targetCells) ?? targetCell;
11769
- if (!visualTargetCell) continue;
11770
- const currentTargetCell = currentNode(visualTargetCell.id) ?? visualTargetCell;
11771
- const nextCellText = appendDistinctText(tableCellText(currentTargetCell), cellText);
11772
- if (!nextCellText) continue;
11773
- updates.set(visualTargetCell.id, {
11774
- ...currentTargetCell,
11775
- textExcerpt: nextCellText,
11776
- description: cleanText(
11777
- [currentTargetCell.title, nextCellText].filter(Boolean).join(" | "),
11778
- currentTargetCell.description
11779
- ),
11780
- sourceSpanIds: [
11781
- .../* @__PURE__ */ new Set([
11782
- ...currentTargetCell.sourceSpanIds,
11783
- ...sourceRow.sourceSpanIds,
11784
- ...sourceCell.sourceSpanIds
11785
- ])
11786
- ],
11787
- bbox: mergedBbox([currentTargetCell, sourceCell]),
11788
- metadata: {
11789
- ...currentTargetCell.metadata ?? {},
11790
- visualTableRepair: "merged_continuation"
11791
- }
11792
- });
11793
- mergedIntoCells = true;
11794
- }
11795
- if (mergedIntoCells) rowsToRebuildText.add(targetRow.id);
11796
- }
11797
- if (!mergedIntoCells && targetCell) {
11798
- const nextCellText = appendDistinctText(tableCellText(targetCell), sourceText);
11799
- if (nextCellText) {
11800
- const mergedNodes = [targetCell, ...sourceNodes];
11801
- updates.set(targetCell.id, {
11802
- ...currentNode(targetCell.id) ?? targetCell,
11803
- textExcerpt: nextCellText,
11804
- description: cleanText([targetCell.title, nextCellText].filter(Boolean).join(" | "), targetCell.description),
11805
- sourceSpanIds: [.../* @__PURE__ */ new Set([...targetCell.sourceSpanIds, ...sourceSpanIds])],
11806
- bbox: mergedBbox(mergedNodes),
11807
- metadata: {
11808
- ...targetCell.metadata ?? {},
11809
- visualTableRepair: "merged_continuation"
11810
- }
11811
- });
11812
- rowsToRebuildText.add(targetRow.id);
11813
- }
11814
- }
11815
- const fallbackRowText = mergedIntoCells ? void 0 : appendDistinctText(targetRow.textExcerpt ?? targetRow.description, sourceText);
11816
- updates.set(targetRow.id, {
11817
- ...currentNode(targetRow.id) ?? targetRow,
11818
- ...mergedIntoCells ? {} : {
11819
- textExcerpt: fallbackRowText,
11820
- description: cleanText(
11821
- [targetRow.title, fallbackRowText].filter(Boolean).join(" | "),
11822
- targetRow.description
11823
- )
11824
- },
11825
- sourceSpanIds: [.../* @__PURE__ */ new Set([...targetRow.sourceSpanIds, ...sourceSpanIds])],
11826
- bbox: mergedBbox([targetRow, ...sourceNodes]),
11827
- metadata: {
11828
- ...targetRow.metadata ?? {},
11829
- visualTableRepair: "merged_continuation"
11830
- }
11831
- });
11832
- removeIds.add(sourceRow.id);
11833
- for (const sourceCell of sourceCells) removeIds.add(sourceCell.id);
11834
- }
11835
- }
11836
- for (const rowId of rowsToRebuildText) {
11837
- if (removeIds.has(rowId)) continue;
11838
- const row = currentNode(rowId);
11839
- if (!row || row.kind !== "table_row") continue;
11840
- const cells = (byParent.get(row.id) ?? []).filter((node) => node.kind === "table_cell" && !removeIds.has(node.id)).map((node) => currentNode(node.id) ?? node).sort(
11841
- (left, right) => tableCellColumnIndex(left, 0) - tableCellColumnIndex(right, 0) || left.order - right.order || left.id.localeCompare(right.id)
11842
- );
11843
- const textExcerpt = tableRowTextFromCells(cells);
11844
- if (!textExcerpt) continue;
11845
- updates.set(row.id, {
11846
- ...row,
11847
- textExcerpt,
11848
- description: cleanText([row.title, textExcerpt].filter(Boolean).join(" | "), row.description)
11849
- });
11850
- }
11851
- if (updates.size === 0 && removeIds.size === 0) return sourceTree;
11852
- const repaired = sourceTree.filter((node) => !removeIds.has(node.id)).map((node) => updates.get(node.id) ?? node);
11853
- return normalizeDocumentSourceTreePaths(normalizeContainerEvidenceFromChildren(repaired));
11854
- }
11855
- async function runVisualTableRepair(params) {
11856
- const candidates = visualTableCandidates(params.sourceTree);
11857
- if (candidates.length === 0) return { sourceTree: params.sourceTree, warnings: [] };
11858
- let sourceTree = params.sourceTree;
11859
- const warnings = [];
11860
- const repairResults = await Promise.all(candidates.map(async (candidate, index) => {
11861
- const label = `source_tree_visual_table_repair_p${candidate.page}`;
11862
- try {
11863
- const budget = params.resolveBudget("extraction_visual_table_repair", 1800);
11864
- const maxTokens = Math.min(budget.maxTokens, 2400);
11865
- const startedAt = Date.now();
11866
- const response = await safeGenerateObject(
11867
- params.generateObject,
11868
- {
11869
- prompt: buildVisualTableRepairPrompt(candidate),
11870
- schema: SourceTreeVisualTableRepairSchema,
11871
- maxTokens,
11872
- taskKind: "extraction_visual_table_repair",
11873
- budgetDiagnostics: { ...budget, maxTokens },
11874
- trace: {
11875
- label,
11876
- startPage: candidate.page,
11877
- endPage: candidate.page,
11878
- batchIndex: index + 1,
11879
- batchCount: candidates.length,
11880
- sourceBacked: true
11881
- }
11882
- },
11883
- {
11884
- fallback: { tables: [], warnings: [] },
11885
- maxRetries: 0,
11886
- log: params.log,
11887
- retry: false
11888
- }
11889
- );
11890
- return {
11891
- index,
11892
- candidate,
11893
- label,
11894
- maxTokens,
11895
- durationMs: Date.now() - startedAt,
11896
- usage: response.usage,
11897
- repair: response.object
11898
- };
11899
- } catch (error) {
11900
- return {
11901
- index,
11902
- candidate,
11903
- error: error instanceof Error ? error.message : String(error)
11904
- };
11905
- }
11906
- }));
11907
- for (const result of repairResults.sort((left, right) => left.index - right.index)) {
11908
- if ("error" in result) {
11909
- warnings.push(`Visual table repair skipped on page ${result.candidate.page}; parsed table kept (${result.error})`);
11910
- continue;
11911
- }
11912
- params.trackUsage(result.usage, {
11913
- taskKind: "extraction_visual_table_repair",
11914
- label: result.label,
11915
- maxTokens: result.maxTokens,
11916
- durationMs: result.durationMs
11917
- });
11918
- sourceTree = applyVisualTableRepair(sourceTree, result.repair);
11919
- warnings.push(...result.repair.warnings.map(
11920
- (warning) => `Visual table repair warning on page ${result.candidate.page}: ${warning}`
11921
- ));
11922
- }
11923
- return { sourceTree, warnings };
11924
- }
11925
11200
  function groupNodeId(documentId, group) {
11926
11201
  return [
11927
11202
  documentId.replace(/[^a-zA-Z0-9_.:-]/g, "_"),
@@ -11930,6 +11205,17 @@ function groupNodeId(documentId, group) {
11930
11205
  group.childNodeIds.join("_").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 80)
11931
11206
  ].join(":");
11932
11207
  }
11208
+ function isDescendantOf(nodeId2, ancestorId, byId) {
11209
+ let parentId = nodeId2 ? byId.get(nodeId2)?.parentId : void 0;
11210
+ const seen = /* @__PURE__ */ new Set();
11211
+ while (parentId) {
11212
+ if (parentId === ancestorId) return true;
11213
+ if (seen.has(parentId)) return false;
11214
+ seen.add(parentId);
11215
+ parentId = byId.get(parentId)?.parentId;
11216
+ }
11217
+ return false;
11218
+ }
11933
11219
  function applyOrganization(sourceTree, organization) {
11934
11220
  const byId = new Map(sourceTree.map((node) => [node.id, node]));
11935
11221
  const labels = new Map(organization.labels.map((label) => [label.nodeId, label]));
@@ -11947,8 +11233,19 @@ function applyOrganization(sourceTree, organization) {
11947
11233
  const children = group.childNodeIds.map((id2) => byId.get(id2)).filter((node2) => Boolean(node2));
11948
11234
  if (children.length === 0) continue;
11949
11235
  if (rejectsOrganizerGroup(group, children)) continue;
11950
- const parentId = children[0].parentId;
11951
- if (!children.every((child) => child.parentId === parentId)) continue;
11236
+ const originalParentId = children[0].parentId;
11237
+ const requestedParent = group.parentNodeId ? byId.get(group.parentNodeId) : void 0;
11238
+ if (requestedParent && children.some((child) => child.id === requestedParent.id || isDescendantOf(requestedParent.id, child.id, byId))) {
11239
+ continue;
11240
+ }
11241
+ if (requestedParent) {
11242
+ if (!children.every((child) => child.parentId === requestedParent.id || hasAncestor(child, requestedParent.id, byId))) {
11243
+ continue;
11244
+ }
11245
+ } else if (!children.every((child) => child.parentId === originalParentId)) {
11246
+ continue;
11247
+ }
11248
+ const parentId = requestedParent?.id ?? originalParentId;
11952
11249
  const documentId = children[0].documentId;
11953
11250
  const title = simplifyOrganizerTitle(group.title, group.title, group.kind);
11954
11251
  const description = descriptionWithPages(cleanText(group.description, title), children);
@@ -12050,7 +11347,6 @@ function materializeDocument(params) {
12050
11347
  retroactiveDate: coverage.retroactiveDate,
12051
11348
  formNumber: coverage.formNumber,
12052
11349
  sectionRef: coverage.sectionRef,
12053
- coverageOrigin: coverage.coverageOrigin,
12054
11350
  endorsementNumber: coverage.endorsementNumber,
12055
11351
  limits: coverage.limits,
12056
11352
  sourceSpanIds: coverage.sourceSpanIds,
@@ -12083,7 +11379,7 @@ function materializeDocument(params) {
12083
11379
  carrier !== "Unknown" ? carrier : void 0,
12084
11380
  policyNumber !== "Unknown" ? `#${policyNumber}` : void 0,
12085
11381
  insuredName !== "Unknown" ? `for ${insuredName}` : void 0,
12086
- profile.coverageTypes.length ? `covering ${profile.coverageTypes.slice(0, 5).join(", ")}` : void 0
11382
+ profile.policyTypes.length ? `covering ${profile.policyTypes.slice(0, 5).join(", ")}` : void 0
12087
11383
  ].filter(Boolean).join(" ");
12088
11384
  const base = {
12089
11385
  id: params.id,
@@ -12145,44 +11441,7 @@ function materializeDocument(params) {
12145
11441
  };
12146
11442
  }
12147
11443
  function coverageCleanupGroups(profile) {
12148
- const groups = [];
12149
- const coreIndexes = [];
12150
- const endorsementIndexes = [];
12151
- const unclassifiedIndexes = [];
12152
- profile.coverages.forEach((coverage, coverageIndex) => {
12153
- if (coverage.coverageOrigin === "core") {
12154
- coreIndexes.push(coverageIndex);
12155
- } else if (coverage.coverageOrigin === "endorsement") {
12156
- endorsementIndexes.push(coverageIndex);
12157
- } else {
12158
- unclassifiedIndexes.push(coverageIndex);
12159
- }
12160
- });
12161
- if (coreIndexes.length) {
12162
- groups.push({
12163
- id: "policy",
12164
- label: "Coverage schedule cleanup: policy schedules",
12165
- coverageIndexes: coreIndexes
12166
- });
12167
- }
12168
- if (endorsementIndexes.length) {
12169
- groups.push({
12170
- id: "endorsements",
12171
- label: "Coverage schedule cleanup: endorsement schedules",
12172
- coverageIndexes: endorsementIndexes
12173
- });
12174
- }
12175
- if (unclassifiedIndexes.length) {
12176
- groups.push({
12177
- id: "source_backed",
12178
- label: "Coverage schedule cleanup: source-backed schedules",
12179
- coverageIndexes: unclassifiedIndexes
12180
- });
12181
- }
12182
- return groups.length > 1 ? groups : [{
12183
- id: "all",
12184
- label: "Coverage schedule cleanup"
12185
- }];
11444
+ return profile.coverages.length ? [{ id: "all", label: "Coverage schedule cleanup" }] : [];
12186
11445
  }
12187
11446
  async function cleanupOperationalCoverageSchedules(params) {
12188
11447
  const groups = coverageCleanupGroups(params.operationalProfile);
@@ -12197,7 +11456,7 @@ async function cleanupOperationalCoverageSchedules(params) {
12197
11456
  prompt: buildOperationalProfileCleanupPrompt(
12198
11457
  params.sourceTree,
12199
11458
  params.operationalProfile,
12200
- { coverageIndexes: group.coverageIndexes, label: group.label }
11459
+ { label: group.label }
12201
11460
  ),
12202
11461
  schema: OperationalProfileCleanupSchema,
12203
11462
  maxTokens: budget.maxTokens,
@@ -12207,7 +11466,7 @@ async function cleanupOperationalCoverageSchedules(params) {
12207
11466
  trace: {
12208
11467
  phase: "coverage_cleanup",
12209
11468
  label: group.label,
12210
- itemCount: group.coverageIndexes?.length ?? params.operationalProfile.coverages.length,
11469
+ itemCount: params.operationalProfile.coverages.length,
12211
11470
  coverageGroup: group.id,
12212
11471
  batchIndex: groups.length > 1 ? groupIndex + 1 : void 0,
12213
11472
  batchCount: groups.length > 1 ? groups.length : void 0,
@@ -12355,15 +11614,7 @@ async function runSourceTreeExtraction(params) {
12355
11614
  warnings.push(`Source-tree outline cleanup failed; deterministic tree used (${error instanceof Error ? error.message : String(error)})`);
12356
11615
  }
12357
11616
  }
12358
- const visualTableRepair = await runVisualTableRepair({
12359
- sourceTree,
12360
- generateObject: params.generateObject,
12361
- resolveBudget: params.resolveBudget,
12362
- trackUsage: localTrack,
12363
- log: params.log
12364
- });
12365
- sourceTree = normalizeSourceTreeTableDisplayText(visualTableRepair.sourceTree);
12366
- warnings.push(...visualTableRepair.warnings);
11617
+ sourceTree = normalizeSourceTreeTableDisplayText(sourceTree);
12367
11618
  const emptyProfile = emptyOperationalProfile();
12368
11619
  let operationalProfile = emptyProfile;
12369
11620
  try {
@@ -13227,14 +12478,6 @@ ${pageText}`;
13227
12478
  mergeMemoryResult(result.name, result.data, memory);
13228
12479
  }
13229
12480
  }
13230
- const recoveredCoverages = recoverCoverageScheduleRows({
13231
- memory,
13232
- sourceSpans,
13233
- pageAssignments
13234
- });
13235
- if (recoveredCoverages.recovered.length > 0) {
13236
- await log?.(`Recovered ${recoveredCoverages.recovered.length} source-backed coverage schedule row(s) from table evidence`);
13237
- }
13238
12481
  const planIncludesSupplementary = tasks.some((task) => task.extractorName === "supplementary");
13239
12482
  if (!planIncludesSupplementary && hasSupplementaryExtractionSignal(pageAssignments, formInventory, memory)) {
13240
12483
  onProgress?.("Extracting supplementary retrieval facts...");
@@ -13401,14 +12644,6 @@ ${pageText}`;
13401
12644
  mergeMemoryResult(result.name, result.data, memory);
13402
12645
  }
13403
12646
  }
13404
- const recoveredCoverages = recoverCoverageScheduleRows({
13405
- memory,
13406
- sourceSpans,
13407
- pageAssignments
13408
- });
13409
- if (recoveredCoverages.recovered.length > 0) {
13410
- await log?.(`Recovered ${recoveredCoverages.recovered.length} source-backed coverage schedule row(s) from follow-up table evidence`);
13411
- }
13412
12647
  }
13413
12648
  } else {
13414
12649
  onProgress?.("Skipping LLM extraction review; deterministic checks passed.");
@@ -17661,7 +16896,7 @@ var COI_GENERATION_TOOL = {
17661
16896
  };
17662
16897
  var COVERAGE_COMPARISON_TOOL = {
17663
16898
  name: "coverage_comparison",
17664
- description: "Compare coverages across two or more insurance documents (policies and/or quotes). Returns a side-by-side comparison of coverage types, limits, and deductibles.",
16899
+ description: "Compare coverages across two or more insurance documents (policies and/or quotes). Returns a side-by-side comparison of policy types, limits, and deductibles.",
17665
16900
  input_schema: {
17666
16901
  type: "object",
17667
16902
  properties: {
@@ -17670,10 +16905,10 @@ var COVERAGE_COMPARISON_TOOL = {
17670
16905
  items: { type: "string" },
17671
16906
  description: "Array of document IDs (policies or quotes) to compare."
17672
16907
  },
17673
- coverageTypes: {
16908
+ policyTypes: {
17674
16909
  type: "array",
17675
16910
  items: { type: "string" },
17676
- description: "Optional filter: only compare these coverage types (e.g. 'General Liability', 'Workers Compensation'). Omit to compare all."
16911
+ description: "Optional filter: only compare these policy types (e.g. 'General Liability', 'Workers Compensation'). Omit to compare all."
17677
16912
  }
17678
16913
  },
17679
16914
  required: ["documentIds"]