@agent-wiki/mcp 0.21.3 → 0.21.5

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.
@@ -1,4 +1,5 @@
1
1
  import { resolveCanonicalId, displayLabel, normalizeCopybookName } from "./graph.js";
2
+ import { parseReplacingPairs } from "./db2-table-lineage.js";
2
3
  function emptyDiagnosticsByKind() {
3
4
  return { "parsed-zero-data-items": 0 };
4
5
  }
@@ -20,22 +21,34 @@ export function normalizeLoadedFieldLineage(raw) {
20
21
  ...raw,
21
22
  summary: {
22
23
  ...summary,
24
+ deterministic: {
25
+ ...summary.deterministic,
26
+ // #39 Phase B — pre-#39 artifacts don't carry this split; backfill to 0.
27
+ viaReplacing: summary.deterministic?.viaReplacing ?? 0,
28
+ },
29
+ inferred: {
30
+ ...summary.inferred,
31
+ // #35 — pre-#35 artifacts predate the semantic tier; backfill to 0.
32
+ semantic: summary.inferred?.semantic ?? 0,
33
+ },
23
34
  diagnosticsByKind: summary.diagnosticsByKind ?? emptyDiagnosticsByKind(),
24
35
  },
25
36
  diagnostics: raw.diagnostics ?? [],
37
+ inferredSemantic: raw.inferredSemantic ?? [],
26
38
  };
27
39
  }
28
40
  function emptyCopybookLineage() {
29
41
  return {
30
42
  summary: {
31
- deterministic: { copybooks: 0, programs: 0, fields: 0 },
32
- inferred: { copybooks: 0, programs: 0, highConfidence: 0, ambiguous: 0 },
43
+ deterministic: { copybooks: 0, programs: 0, fields: 0, viaReplacing: 0 },
44
+ inferred: { copybooks: 0, programs: 0, highConfidence: 0, ambiguous: 0, semantic: 0 },
33
45
  diagnosticsByKind: emptyDiagnosticsByKind(),
34
46
  },
35
47
  copybookUsage: [],
36
48
  deterministic: [],
37
49
  inferredHighConfidence: [],
38
50
  inferredAmbiguous: [],
51
+ inferredSemantic: [],
39
52
  diagnostics: [],
40
53
  };
41
54
  }
@@ -90,7 +103,7 @@ function compareProgram(a, b) {
90
103
  function compareCopybook(a, b) {
91
104
  return a.id.localeCompare(b.id) || a.sourceFile.localeCompare(b.sourceFile);
92
105
  }
93
- function buildEntry(linkage, fields, programs, rationale) {
106
+ function buildEntry(linkage, fields, programs, rationale, replacingPair) {
94
107
  const copybooks = [...new Map(fields.map((field) => [field.copybookId, { id: field.copybookId, sourceFile: field.copybookSourceFile }])).values()].sort(compareCopybook);
95
108
  return {
96
109
  linkage,
@@ -104,9 +117,70 @@ function buildEntry(linkage, fields, programs, rationale) {
104
117
  pictures: sortUnique(fields.map((field) => field.picture).filter((value) => Boolean(value))),
105
118
  usages: sortUnique(fields.map((field) => field.usage).filter((value) => Boolean(value))),
106
119
  levels: [...new Set(fields.map((field) => field.level))].sort((a, b) => a - b),
120
+ ...(replacingPair ? { replacing: replacingPair } : {}),
107
121
  rationale,
108
122
  };
109
123
  }
124
+ function groupConsumersByReplacing(consumers) {
125
+ const byKey = new Map();
126
+ for (const c of consumers) {
127
+ const raw = c.replacing ?? [];
128
+ const key = JSON.stringify(raw);
129
+ let cohort = byKey.get(key);
130
+ if (!cohort) {
131
+ cohort = { key, pairs: parseReplacingPairs(raw), consumers: [] };
132
+ byKey.set(key, cohort);
133
+ }
134
+ cohort.consumers.push(c);
135
+ }
136
+ // Stable sort: empty cohort first, then by key. Keeps deterministic
137
+ // entry order across rebuilds regardless of consumer iteration order.
138
+ return [...byKey.values()].sort((a, b) => {
139
+ if (a.key === "[]")
140
+ return -1;
141
+ if (b.key === "[]")
142
+ return 1;
143
+ return a.key.localeCompare(b.key);
144
+ });
145
+ }
146
+ /**
147
+ * Carries a flattened field through a cohort's REPLACING pairs. When a
148
+ * pair's `from` matches the field's leaf name, the leaf and every
149
+ * qualified-path segment is rewritten to the pair's `to`. The original
150
+ * pair is returned alongside so the entry can carry it as evidence.
151
+ *
152
+ * Parent and qualified-path substitution: applies the pair to every
153
+ * segment of the qualified path, not just the leaf — REPLACING is purely
154
+ * textual in COBOL, so a `from` name that also occurs as a parent record
155
+ * name is renamed everywhere it appears. Multi-pair cohorts iterate pairs
156
+ * in declaration order; first hit per segment wins (matches COBOL
157
+ * REPLACING semantics — earlier pairs apply first; later pairs see the
158
+ * post-substitution text).
159
+ */
160
+ function projectFieldThroughReplacing(field, pairs) {
161
+ if (pairs.length === 0) {
162
+ return { ...field };
163
+ }
164
+ const sub = (segment) => {
165
+ const upper = segment.toUpperCase();
166
+ for (const p of pairs) {
167
+ if (p.from === upper)
168
+ return p.to;
169
+ }
170
+ return segment;
171
+ };
172
+ const matchedLeaf = pairs.find((p) => p.from === field.fieldName.toUpperCase());
173
+ return {
174
+ ...field,
175
+ fieldName: matchedLeaf?.to ?? field.fieldName,
176
+ qualifiedName: field.qualifiedName.split(".").map(sub).join("."),
177
+ parentQualifiedName: field.parentQualifiedName?.split(".").map(sub).join("."),
178
+ siblings: field.siblings.map(sub),
179
+ replacingPair: matchedLeaf
180
+ ? { fromName: matchedLeaf.from, toName: matchedLeaf.to }
181
+ : undefined,
182
+ };
183
+ }
110
184
  function compareField(a, b) {
111
185
  return a.copybookId.localeCompare(b.copybookId)
112
186
  || a.qualifiedName.localeCompare(b.qualifiedName)
@@ -170,8 +244,18 @@ function buildInferredEntry(candidate, confidence, competingMatches) {
170
244
  ...candidate.evidence,
171
245
  competingMatches,
172
246
  };
247
+ // For semantic entries the two fields have intentionally different names —
248
+ // start the rationale with the rename pair so a human reviewer sees the gap
249
+ // up front, instead of the misleading "Same field name" prefix that's
250
+ // accurate for the name-keyed tiers. Participant carries the qualified
251
+ // path; the leaf segment is the field name.
252
+ const leftLeaf = ordered.left.qualifiedName.split(".").pop() ?? "";
253
+ const rightLeaf = ordered.right.qualifiedName.split(".").pop() ?? "";
254
+ const namePart = confidence === "semantic"
255
+ ? `Renamed field (${leftLeaf} ↔ ${rightLeaf})`
256
+ : "Same field name";
173
257
  const rationaleParts = [
174
- "Same field name",
258
+ namePart,
175
259
  evidence.pictureMatch ? "matching PIC" : undefined,
176
260
  evidence.usageEvidence === "explicit-match" ? "matching USAGE" : undefined,
177
261
  evidence.levelMatch ? `same level ${ordered.left.level}` : undefined,
@@ -217,8 +301,10 @@ function formatInferredStructure(participant) {
217
301
  * copybook, the origin is appended as `from CUSTID` so the user can trace
218
302
  * it without grepping. Unresolved vars are tagged with `(?)` — a paired
219
303
  * `host-var-unresolved` diagnostic in the exclusions table tells the
220
- * user why. `<br>` separates entries so a many-host-var cell stays
221
- * readable in the markdown table.
304
+ * user why. When the field was reached via REPLACING substitution (#37
305
+ * Phase A), the rename trail (`from CUSTOMER-ID via REPLACING`) appears so
306
+ * a reviewer sees why the SQL name and copybook name disagree. `<br>`
307
+ * separates entries so a many-host-var cell stays readable.
222
308
  */
223
309
  function formatHostVars(hostVars) {
224
310
  if (hostVars.length === 0)
@@ -227,10 +313,18 @@ function formatHostVars(hostVars) {
227
313
  if (!hv.dataItem)
228
314
  return `\`${hv.name}\` (?)`;
229
315
  const shape = hv.dataItem.picture ?? "group";
230
- const origin = hv.dataItem.originCopybook
231
- ? ` from \`${hv.dataItem.originCopybook}\``
232
- : "";
233
- return `\`${hv.name}\` (${shape}${origin})`;
316
+ // Substitution wins over plain origin: the user needs to see the rename
317
+ // pair first, then the copybook. A field reached via REPLACING always
318
+ // has originCopybook set (the substitution is per-COPY), so we read both
319
+ // out of the same HostVarRef.
320
+ let trail = "";
321
+ if (hv.dataItem.replacingSubstitution) {
322
+ trail = ` from \`${hv.dataItem.replacingSubstitution.fromName}\` via REPLACING in \`${hv.dataItem.originCopybook}\``;
323
+ }
324
+ else if (hv.dataItem.originCopybook) {
325
+ trail = ` from \`${hv.dataItem.originCopybook}\``;
326
+ }
327
+ return `\`${hv.name}\` (${shape}${trail})`;
234
328
  }).join("<br>");
235
329
  }
236
330
  export function buildFieldLineage(models) {
@@ -316,12 +410,17 @@ export function buildFieldLineage(models) {
316
410
  const copybookId = `copybook:${logicalName}`;
317
411
  const consumers = [...new Map((consumersByCopybook.get(normalizeCopybookName(logicalName)) ?? [])
318
412
  .map((consumer) => [`${consumer.id}@${consumer.sourceFile}`, consumer])).values()].sort(compareProgram);
319
- const exactPrograms = consumers.filter((program) => !program.replacing || program.replacing.length === 0);
413
+ // #39 Phase B — cohort by the consumer's raw REPLACING tuple. Same
414
+ // tuple = same post-substitution shape = same deterministic plane.
415
+ // Empty/missing replacing collapses to the "exact COPY" cohort (key
416
+ // "[]"); this is byte-identical to the pre-#39 exactPrograms gate
417
+ // for REPLACING-free corpora.
418
+ const cohorts = groupConsumersByReplacing(consumers);
320
419
  return {
321
420
  copybookId,
322
421
  sourceFile: copybook.sourceFile,
323
422
  programs: consumers,
324
- exactPrograms,
423
+ cohorts,
325
424
  fieldCount: flattenedByCopybook.get(copybookId)?.length ?? 0,
326
425
  };
327
426
  }).filter((entry) => entry.programs.length > 0)
@@ -329,19 +428,52 @@ export function buildFieldLineage(models) {
329
428
  if (rawCopybookUsage.length === 0) {
330
429
  return diagnostics.length > 0 ? withDiagnostics(emptyCopybookLineage()) : null;
331
430
  }
431
+ // Per-cohort deterministic emission (#39 Phase B). Each cohort with ≥2
432
+ // consumers contributes one entry per copybook field, with REPLACING
433
+ // substitution applied to the field name and qualified-path segments
434
+ // when the cohort's pairs reference them.
332
435
  const deterministic = [];
333
436
  for (const usage of rawCopybookUsage) {
334
437
  const fields = flattenedByCopybook.get(usage.copybookId) ?? [];
335
- for (const field of fields) {
336
- if (usage.exactPrograms.length < 2)
438
+ for (const cohort of usage.cohorts) {
439
+ if (cohort.consumers.length < 2)
440
+ continue;
441
+ // Skip cohorts whose REPLACING text we couldn't structure into pairs
442
+ // — fragment / partial-token substitution (same Phase A limit). The
443
+ // consumers HAVE substitution; we just don't know what gets renamed.
444
+ // Emitting `deterministic` under the original copybook names would
445
+ // be a false positive on any field the substitution actually
446
+ // touches, so preserve the pre-#39 behavior of treating unparseable-
447
+ // REPLACING consumers as singletons.
448
+ const isUnparseableReplacing = cohort.key !== "[]" && cohort.pairs.length === 0;
449
+ if (isUnparseableReplacing)
337
450
  continue;
338
- deterministic.push(buildEntry("deterministic", [field], usage.exactPrograms, "Exact parsed copybook field shared by multiple programs through COPY."));
451
+ const isReplacingCohort = cohort.pairs.length > 0;
452
+ for (const field of fields) {
453
+ const projected = projectFieldThroughReplacing(field, cohort.pairs);
454
+ const linkage = isReplacingCohort ? "deterministic-via-replacing" : "deterministic";
455
+ const rationale = isReplacingCohort
456
+ ? "Exact parsed copybook field shared by multiple programs through identical COPY ... REPLACING."
457
+ : "Exact parsed copybook field shared by multiple programs through COPY.";
458
+ deterministic.push(buildEntry(linkage, [projected], cohort.consumers, rationale, projected.replacingPair));
459
+ }
339
460
  }
340
461
  }
341
- const candidateFields = rawCopybookUsage.flatMap((usage) => (flattenedByCopybook.get(usage.copybookId) ?? [])
342
- .filter((field) => usage.exactPrograms.length > 0)
343
- .filter((field) => Boolean(field.picture) || Boolean(field.usage))
344
- .map((field) => ({ field, programs: usage.exactPrograms })));
462
+ // Inferred candidate sourcing keeps the original (pre-#39) semantics: only
463
+ // empty-cohort consumers participate, and even a singleton empty cohort
464
+ // can seed candidates (cross-copybook pairing needs at least one consumer
465
+ // per copybook, not two). Phase C (REPLACING-aware inferred) is
466
+ // intentionally deferred — widening this set now would let renamed
467
+ // fields cross-match without name evidence, blowing up the precision
468
+ // contract that high/ambiguous depend on.
469
+ const candidateFields = rawCopybookUsage.flatMap((usage) => {
470
+ const exact = usage.cohorts.find((c) => c.pairs.length === 0);
471
+ if (!exact || exact.consumers.length === 0)
472
+ return [];
473
+ return (flattenedByCopybook.get(usage.copybookId) ?? [])
474
+ .filter((field) => Boolean(field.picture) || Boolean(field.usage))
475
+ .map((field) => ({ field, programs: exact.consumers }));
476
+ });
345
477
  const candidateGroups = new Map();
346
478
  for (const candidate of candidateFields) {
347
479
  const key = candidate.field.fieldName.toUpperCase();
@@ -428,9 +560,98 @@ export function buildFieldLineage(models) {
428
560
  || a.left.qualifiedName.localeCompare(b.left.qualifiedName)
429
561
  || compareCopybook(a.right.copybook, b.right.copybook)
430
562
  || a.right.qualifiedName.localeCompare(b.right.qualifiedName));
563
+ // #35 — second pass: shape-keyed matcher for renamed-field detection.
564
+ // Groups candidates by `(PIC, USAGE, level)` instead of field name and
565
+ // emits a pair only when *all five* gates hold:
566
+ // 1. picture match — implicit in the shape-key grouping
567
+ // 2. usage explicit on both sides — `both-missing` doesn't qualify;
568
+ // losing the name signal AND missing USAGE leaves too little
569
+ // 3. parent context exact — top-level / suffix don't qualify
570
+ // 4. ≥ 2 shared siblings — one is too weak without name alignment
571
+ // 5. zero competing matches inside the semantic pool — no
572
+ // `semantic-ambiguous` companion tier in this iteration
573
+ //
574
+ // Pairs whose field names match would already have been emitted by the
575
+ // name-keyed pass; drop them here to avoid double-reporting.
576
+ const semanticCandidateFields = rawCopybookUsage.flatMap((usage) => {
577
+ const exact = usage.cohorts.find((c) => c.pairs.length === 0);
578
+ if (!exact || exact.consumers.length === 0)
579
+ return [];
580
+ return (flattenedByCopybook.get(usage.copybookId) ?? [])
581
+ .filter((field) => Boolean(field.picture) && Boolean(field.usage))
582
+ .map((field) => ({ field, programs: exact.consumers }));
583
+ });
584
+ const shapeGroups = new Map();
585
+ for (const candidate of semanticCandidateFields) {
586
+ const shapeKey = `${normalizePicture(candidate.field.picture)}|${normalizeUsage(candidate.field.usage)}|${candidate.field.level}`;
587
+ const list = shapeGroups.get(shapeKey) ?? [];
588
+ list.push(candidate);
589
+ shapeGroups.set(shapeKey, list);
590
+ }
591
+ const semanticCandidatesRaw = [];
592
+ for (const [, fields] of shapeGroups.entries()) {
593
+ for (let i = 0; i < fields.length; i++) {
594
+ for (let j = i + 1; j < fields.length; j++) {
595
+ const left = fields[i];
596
+ const right = fields[j];
597
+ if (left.field.copybookId === right.field.copybookId)
598
+ continue;
599
+ if (compareField(left.field, right.field) > 0)
600
+ continue;
601
+ // Name-matched pairs belong to the high / ambiguous tier — exclude
602
+ // them here so they don't double up.
603
+ if (left.field.fieldName.toUpperCase() === right.field.fieldName.toUpperCase())
604
+ continue;
605
+ const parentContextMatch = determineParentContextMatch(left.field, right.field);
606
+ if (parentContextMatch !== "exact")
607
+ continue; // Gate 3
608
+ const siblingOverlap = sortUnique(left.field.siblings.filter((sibling) => right.field.siblings.includes(sibling)));
609
+ if (siblingOverlap.length < 2)
610
+ continue; // Gate 4
611
+ // Gates 1, 2, and level match are guaranteed by the shape-key grouping.
612
+ semanticCandidatesRaw.push({
613
+ fieldName: left.field.fieldName, // display value; left/right names actually differ
614
+ left: left.field,
615
+ right: right.field,
616
+ leftPrograms: left.programs,
617
+ rightPrograms: right.programs,
618
+ evidence: {
619
+ pictureMatch: true,
620
+ usageEvidence: "explicit-match",
621
+ levelMatch: true,
622
+ qualifiedNameMatch: "renamed",
623
+ parentContextMatch,
624
+ siblingOverlap,
625
+ },
626
+ });
627
+ }
628
+ }
629
+ }
630
+ // Competing-match count is local to the semantic pool — a field that's
631
+ // also in a name-keyed pair doesn't count as "competing" with its
632
+ // semantic peers, and vice-versa.
633
+ const semanticCounts = new Map();
634
+ for (const candidate of semanticCandidatesRaw) {
635
+ semanticCounts.set(inferredCandidateKey(candidate.left), (semanticCounts.get(inferredCandidateKey(candidate.left)) ?? 0) + 1);
636
+ semanticCounts.set(inferredCandidateKey(candidate.right), (semanticCounts.get(inferredCandidateKey(candidate.right)) ?? 0) + 1);
637
+ }
638
+ const inferredSemantic = semanticCandidatesRaw
639
+ .map((candidate) => {
640
+ const competingMatches = Math.max((semanticCounts.get(inferredCandidateKey(candidate.left)) ?? 1) - 1, (semanticCounts.get(inferredCandidateKey(candidate.right)) ?? 1) - 1);
641
+ return { candidate, competingMatches };
642
+ })
643
+ .filter(({ competingMatches }) => competingMatches === 0) // Gate 5
644
+ .map(({ candidate, competingMatches }) => buildInferredEntry(candidate, "semantic", competingMatches))
645
+ .sort((a, b) => compareCopybook(a.left.copybook, b.left.copybook)
646
+ || a.left.qualifiedName.localeCompare(b.left.qualifiedName)
647
+ || compareCopybook(a.right.copybook, b.right.copybook)
648
+ || a.right.qualifiedName.localeCompare(b.right.qualifiedName));
431
649
  const sortedDeterministic = deterministic.sort((a, b) => a.copybooks[0].id.localeCompare(b.copybooks[0].id) ||
432
650
  a.qualifiedNames[0].localeCompare(b.qualifiedNames[0]));
433
- if (sortedDeterministic.length === 0 && inferredHighConfidence.length === 0 && inferredAmbiguous.length === 0) {
651
+ if (sortedDeterministic.length === 0
652
+ && inferredHighConfidence.length === 0
653
+ && inferredAmbiguous.length === 0
654
+ && inferredSemantic.length === 0) {
434
655
  return diagnostics.length > 0 ? withDiagnostics(emptyCopybookLineage()) : null;
435
656
  }
436
657
  const participatingCopybookIds = new Set();
@@ -474,12 +695,18 @@ export function buildFieldLineage(models) {
474
695
  copybooks: participatingCopybookIds.size,
475
696
  programs: participatingProgramIds.size,
476
697
  fields: sortedDeterministic.length,
698
+ viaReplacing: sortedDeterministic.filter((e) => e.linkage === "deterministic-via-replacing").length,
477
699
  },
478
700
  inferred: {
701
+ // `copybooks` / `programs` deliberately count name-keyed entries only
702
+ // (high + ambiguous). Excluding semantic keeps this counter byte-
703
+ // stable on corpora without rename pairs — the regression-lock
704
+ // contract from #35.
479
705
  copybooks: inferredCopybookIds.size,
480
706
  programs: inferredProgramIds.size,
481
707
  highConfidence: inferredHighConfidence.length,
482
708
  ambiguous: inferredAmbiguous.length,
709
+ semantic: inferredSemantic.length,
483
710
  },
484
711
  diagnosticsByKind: countDiagnosticsByKind(diagnostics),
485
712
  },
@@ -487,6 +714,7 @@ export function buildFieldLineage(models) {
487
714
  deterministic: sortedDeterministic,
488
715
  inferredHighConfidence,
489
716
  inferredAmbiguous,
717
+ inferredSemantic,
490
718
  diagnostics,
491
719
  };
492
720
  }
@@ -509,6 +737,12 @@ export function generateFieldLineagePage(lineage) {
509
737
  ...entry.left.programs.map((program) => `"raw/${program.sourceFile}"`),
510
738
  ...entry.right.programs.map((program) => `"raw/${program.sourceFile}"`),
511
739
  ]),
740
+ ...(lineage.inferredSemantic ?? []).flatMap((entry) => [
741
+ `"raw/${entry.left.copybook.sourceFile}"`,
742
+ `"raw/${entry.right.copybook.sourceFile}"`,
743
+ ...entry.left.programs.map((program) => `"raw/${program.sourceFile}"`),
744
+ ...entry.right.programs.map((program) => `"raw/${program.sourceFile}"`),
745
+ ]),
512
746
  ...(callBound?.entries.flatMap((entry) => [
513
747
  `"raw/${entry.caller.sourceFile}"`,
514
748
  `"raw/${entry.callee.sourceFile}"`,
@@ -525,10 +759,13 @@ export function generateFieldLineagePage(lineage) {
525
759
  lines.push(`sources: [${sources.join(", ")}]`);
526
760
  lines.push("---");
527
761
  lines.push("");
762
+ renderCoverageSection(lines, lineage, callBound, db2);
763
+ const semanticCount = lineage.summary.inferred?.semantic ?? 0;
528
764
  const overviewHasCopybook = lineage.copybookUsage.length > 0
529
765
  || lineage.deterministic.length > 0
530
766
  || lineage.inferredHighConfidence.length > 0
531
- || lineage.inferredAmbiguous.length > 0;
767
+ || lineage.inferredAmbiguous.length > 0
768
+ || semanticCount > 0;
532
769
  lines.push("## Overview");
533
770
  lines.push("");
534
771
  lines.push("| Metric | Count |");
@@ -541,6 +778,11 @@ export function generateFieldLineagePage(lineage) {
541
778
  lines.push(`| Inferred programs | ${lineage.summary.inferred.programs} |`);
542
779
  lines.push(`| Inferred high-confidence candidates | ${lineage.summary.inferred.highConfidence} |`);
543
780
  lines.push(`| Inferred ambiguous candidates | ${lineage.summary.inferred.ambiguous} |`);
781
+ // Only surface the semantic row when there's content — keeps Overview
782
+ // byte-identical for rename-free corpora (#35 regression-lock contract).
783
+ if (semanticCount > 0) {
784
+ lines.push(`| Semantic-inferred candidates | ${semanticCount} |`);
785
+ }
544
786
  }
545
787
  if (callBound) {
546
788
  lines.push(`| Call sites with USING args | ${callBound.summary.callSites} |`);
@@ -576,7 +818,8 @@ export function generateFieldLineagePage(lineage) {
576
818
  const hasCopybookContent = lineage.copybookUsage.length > 0
577
819
  || lineage.deterministic.length > 0
578
820
  || lineage.inferredHighConfidence.length > 0
579
- || lineage.inferredAmbiguous.length > 0;
821
+ || lineage.inferredAmbiguous.length > 0
822
+ || (lineage.inferredSemantic ?? []).length > 0;
580
823
  if (hasCopybookContent) {
581
824
  lines.push("## Copybook Usage");
582
825
  lines.push("");
@@ -603,7 +846,14 @@ export function generateFieldLineagePage(lineage) {
603
846
  lines.push("| Copybook | Field | Structure | Programs | PIC | Linkage |");
604
847
  lines.push("|----------|-------|-----------|----------|-----|---------|");
605
848
  for (const entry of lineage.deterministic) {
606
- lines.push(`| ${formatCopybooks(entry.copybooks)} | ${entry.fieldName} | ${entry.qualifiedNames.join("<br>")} | ${formatPrograms(entry.programs)} | ${entry.pictures.join(", ") || "—"} | ${entry.linkage} |`);
849
+ // #39 Phase B — when the cohort renamed this field, surface the
850
+ // rename pair inline so the user sees both names without having to
851
+ // cross-reference the artifact. Field cell only — Structure column
852
+ // already shows the post-substitution qualified path.
853
+ const fieldCell = entry.replacing
854
+ ? `${entry.fieldName} (was ${entry.replacing.fromName})`
855
+ : entry.fieldName;
856
+ lines.push(`| ${formatCopybooks(entry.copybooks)} | ${fieldCell} | ${entry.qualifiedNames.join("<br>")} | ${formatPrograms(entry.programs)} | ${entry.pictures.join(", ") || "—"} | ${entry.linkage} |`);
607
857
  }
608
858
  }
609
859
  lines.push("");
@@ -641,6 +891,31 @@ export function generateFieldLineagePage(lineage) {
641
891
  }
642
892
  }
643
893
  lines.push("");
894
+ // Semantic-inferred (#35) — only render when present. Keeping the
895
+ // subsection conditional preserves byte-identical output on rename-free
896
+ // corpora (regression lock from the issue).
897
+ const semanticEntries = lineage.inferredSemantic ?? [];
898
+ if (semanticEntries.length > 0) {
899
+ lines.push("### Semantic-Inferred");
900
+ lines.push("");
901
+ lines.push("Pairs matched on shape `(PIC, USAGE, level)` plus exact parent path plus ≥2 sibling overlap. **No name alignment** — the two fields have different names. Lower trust than high-confidence; review one-by-one before relying on these.");
902
+ lines.push("");
903
+ lines.push("| Left field | Right field | Left | Right | Programs | Evidence |");
904
+ lines.push("|------------|-------------|------|-------|----------|----------|");
905
+ for (const entry of semanticEntries) {
906
+ const leftLeaf = entry.left.qualifiedName.split(".").pop() ?? entry.fieldName;
907
+ const rightLeaf = entry.right.qualifiedName.split(".").pop() ?? entry.fieldName;
908
+ const evidence = [
909
+ `PIC ${entry.left.picture ?? "—"}`,
910
+ `USAGE ${entry.left.usage ?? "—"}`,
911
+ entry.evidence.siblingOverlap.length > 0
912
+ ? `siblings: ${entry.evidence.siblingOverlap.join(", ")}`
913
+ : undefined,
914
+ ].filter((v) => Boolean(v)).join("; ");
915
+ lines.push(`| ${leftLeaf} | ${rightLeaf} | ${displayLabel(entry.left.copybook.id)}<br>${formatInferredStructure(entry.left)} | ${displayLabel(entry.right.copybook.id)}<br>${formatInferredStructure(entry.right)} | ${formatInferredPrograms(entry.left, entry.right)} | ${evidence} |`);
916
+ }
917
+ lines.push("");
918
+ }
644
919
  }
645
920
  if (callBound && (callBound.entries.length > 0 || callBound.diagnostics.length > 0)) {
646
921
  lines.push("## Call Boundary Field Lineage");
@@ -824,6 +1099,103 @@ function renderDb2Exclusions(lines, diagnostics) {
824
1099
  }
825
1100
  lines.push("");
826
1101
  }
1102
+ /**
1103
+ * Compact "top N excluded reasons" for a coverage-row cell. Kinds with
1104
+ * zero counts are dropped first so the cell never renders a noise entry
1105
+ * like `0 system-call`. Sort is count desc, kind asc on tie — pinning the
1106
+ * tie-break gives byte-stable output across rebuilds when two kinds have
1107
+ * the same count.
1108
+ */
1109
+ function topExclusionReasons(byKind, limit = 2) {
1110
+ const ranked = Object.entries(byKind)
1111
+ .filter(([, count]) => count > 0)
1112
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
1113
+ if (ranked.length === 0)
1114
+ return "—";
1115
+ return ranked.slice(0, limit).map(([kind, count]) => `${count} ${kind}`).join(", ");
1116
+ }
1117
+ /**
1118
+ * Coverage gauge rendered at the top of `field-lineage.md`. Three rows —
1119
+ * Copybook / Call boundary / DB2 — each showing what was indexed, what
1120
+ * yielded lineage, and the top excluded reasons. Empty families omit their
1121
+ * row. All counts derive from existing summary fields on the artifact; no
1122
+ * new aggregation logic.
1123
+ */
1124
+ function renderCoverageSection(lines, lineage, callBound, db2) {
1125
+ // Pre-#30 in-memory shapes may lack diagnosticsByKind; declaring as
1126
+ // Record<string, number> means the `?? 0` reads on known keys are
1127
+ // defensible even if the field is absent.
1128
+ const copybookDiagByKind = lineage.summary.diagnosticsByKind ?? {};
1129
+ const zeroDataItemsCount = copybookDiagByKind["parsed-zero-data-items"] ?? 0;
1130
+ const semanticCount = lineage.summary.inferred?.semantic ?? 0;
1131
+ const copybookHasContent = lineage.copybookUsage.length > 0
1132
+ || lineage.deterministic.length > 0
1133
+ || lineage.inferredHighConfidence.length > 0
1134
+ || lineage.inferredAmbiguous.length > 0
1135
+ || semanticCount > 0
1136
+ || zeroDataItemsCount > 0;
1137
+ const rows = [];
1138
+ if (copybookHasContent) {
1139
+ // Indexed = universe of copybooks observed = participating (yielded
1140
+ // lineage) + zero-data-items drops. Single-consumer / REPLACING-only
1141
+ // copybooks aren't currently tracked as diagnostics so they don't
1142
+ // appear; once added, sum their counter in here.
1143
+ const indexed = lineage.copybookUsage.length + zeroDataItemsCount;
1144
+ // Yielding splits inferred into the name-keyed and shape-keyed halves
1145
+ // (#35) and the deterministic count into the regular cohort and the
1146
+ // REPLACING cohort (#39 Phase B). Both `(R via REPLACING)` and
1147
+ // `semantic` suffixes are conditional so the cell stays byte-identical
1148
+ // on corpora without rename pairs / without REPLACING — regression
1149
+ // lock contract.
1150
+ //
1151
+ // Both numbers in the deterministic cell are copybook counts (so the
1152
+ // parenthetical is a true subset of the main count). The artifact's
1153
+ // `summary.deterministic.viaReplacing` exposes the entry count for
1154
+ // JSON consumers; the renderer recomputes copybooks for display
1155
+ // because that's the visible apples-to-apples number.
1156
+ const replacingCopybookCount = new Set(lineage.deterministic
1157
+ .filter((e) => e.linkage === "deterministic-via-replacing")
1158
+ .flatMap((e) => e.copybooks.map((c) => c.id))).size;
1159
+ const deterministicCell = replacingCopybookCount > 0
1160
+ ? `${lineage.summary.deterministic.copybooks} deterministic (${replacingCopybookCount} via REPLACING)`
1161
+ : `${lineage.summary.deterministic.copybooks} deterministic`;
1162
+ const yielding = semanticCount > 0
1163
+ ? `${deterministicCell}, ${lineage.summary.inferred.copybooks} inferred, ${semanticCount} semantic`
1164
+ : `${deterministicCell}, ${lineage.summary.inferred.copybooks} inferred`;
1165
+ rows.push(`| Copybook | ${indexed} | ${yielding} | ${topExclusionReasons(copybookDiagByKind)} |`);
1166
+ }
1167
+ if (callBound) {
1168
+ // Indexed = total CALL ... USING sites attempted = resolved sites
1169
+ // (`summary.callSites`) + per-site drops. shape-mismatch and
1170
+ // caller-arg-not-top-level are per-arg drops *within* a resolved
1171
+ // site, so they don't add to the site total.
1172
+ const cbd = callBound.summary.diagnosticsByKind;
1173
+ const siteDropped = cbd["unresolved-callee"]
1174
+ + cbd["dynamic-call"]
1175
+ + cbd["arity-mismatch"]
1176
+ + cbd["system-call"];
1177
+ const totalSites = callBound.summary.callSites + siteDropped;
1178
+ rows.push(`| Call boundary | ${totalSites} call site(s) | ${callBound.summary.pairs} pair(s) | ${topExclusionReasons(callBound.summary.diagnosticsByKind)} |`);
1179
+ }
1180
+ if (db2) {
1181
+ // Indexed = all distinct DB2 tables touched by ≥1 program =
1182
+ // sharedTables (had both writer and reader) + writer-only +
1183
+ // reader-only. non-classifiable-op is per-reference, not per-table,
1184
+ // and self-loop is per-pair within a shared table — neither adds to
1185
+ // the table total.
1186
+ const dbd = db2.summary.diagnosticsByKind;
1187
+ const totalTables = db2.summary.sharedTables + dbd["writer-only"] + dbd["reader-only"];
1188
+ rows.push(`| DB2 | ${totalTables} table(s) | ${db2.summary.pairs} writer→reader pair(s) | ${topExclusionReasons(db2.summary.diagnosticsByKind)} |`);
1189
+ }
1190
+ if (rows.length === 0)
1191
+ return;
1192
+ lines.push("## Coverage");
1193
+ lines.push("");
1194
+ lines.push("| Family | Indexed | Yielding lineage | Excluded (top reasons) |");
1195
+ lines.push("|--------|---------|------------------|------------------------|");
1196
+ lines.push(...rows);
1197
+ lines.push("");
1198
+ }
827
1199
  function groupCallBoundByPair(entries) {
828
1200
  const groups = new Map();
829
1201
  for (const entry of entries) {