@remnic/core 9.3.697 → 9.3.698
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/access-boundary.d.ts +1 -1
- package/dist/access-boundary.js +6 -6
- package/dist/access-cli.js +18 -18
- package/dist/access-http.d.ts +1 -1
- package/dist/access-http.js +9 -9
- package/dist/access-mcp.d.ts +1 -1
- package/dist/access-mcp.js +8 -8
- package/dist/access-operations.d.ts +1 -1
- package/dist/access-operations.js +7 -7
- package/dist/{access-service-BqBQeUJd.d.ts → access-service-DftqtNUy.d.ts} +10 -0
- package/dist/access-service.d.ts +1 -1
- package/dist/access-service.js +5 -5
- package/dist/access-surface-catalog.d.ts +1 -1
- package/dist/briefing.js +3 -3
- package/dist/causal-consolidation.js +4 -4
- package/dist/{chunk-75KYTVFK.js → chunk-2K64VH66.js} +2 -2
- package/dist/{chunk-62Q2QA4Z.js → chunk-2KJG6ZZK.js} +2 -2
- package/dist/{chunk-AYMVRRDP.js → chunk-2ULWWAQH.js} +2 -2
- package/dist/{chunk-HKE7UREW.js → chunk-A62RAIBN.js} +2 -2
- package/dist/{chunk-6YXRSHKG.js → chunk-ANZLT74L.js} +2 -2
- package/dist/{chunk-N5UHWRGK.js → chunk-COEZR6F5.js} +2 -2
- package/dist/{chunk-3LLLRQPV.js → chunk-CQ4PGFMC.js} +3 -3
- package/dist/{chunk-AUGA5JZD.js → chunk-E6GOVHHJ.js} +3 -3
- package/dist/{chunk-WHJ4WTHH.js → chunk-EZWQZYLK.js} +2 -2
- package/dist/{chunk-4X3LO5OF.js → chunk-FEB7W5JG.js} +103 -15
- package/dist/chunk-FEB7W5JG.js.map +1 -0
- package/dist/{chunk-GPHHYOQC.js → chunk-FSEQXHEZ.js} +2 -2
- package/dist/{chunk-F5J5OVWF.js → chunk-HZ5DRA4Q.js} +13 -13
- package/dist/{chunk-2IYYMOQZ.js → chunk-IZ5E6ZTK.js} +4 -4
- package/dist/{chunk-FLV6YAS3.js → chunk-JYVD2XZ4.js} +13 -13
- package/dist/{chunk-TAEO72ZC.js → chunk-LIWU4QI6.js} +4 -4
- package/dist/{chunk-4LM6W5SX.js → chunk-M4DQWUKX.js} +2 -2
- package/dist/{chunk-WDLJCSZ4.js → chunk-MRX6S22R.js} +2 -2
- package/dist/{chunk-TFZKNDVY.js → chunk-N55RJT4N.js} +2 -2
- package/dist/{chunk-AEPUGOPY.js → chunk-PJIHCOGV.js} +2 -2
- package/dist/{chunk-UZW4UWIK.js → chunk-RIC5U67B.js} +2 -2
- package/dist/{chunk-BQEZPX6Z.js → chunk-SIDSEXUG.js} +2 -2
- package/dist/{chunk-4FXCAY7J.js → chunk-SJQ4HY3E.js} +2 -2
- package/dist/{chunk-5JTY7OXQ.js → chunk-UDDSC6PO.js} +5 -5
- package/dist/{chunk-5MNL24XY.js → chunk-XFG3PVZE.js} +27 -7
- package/dist/chunk-XFG3PVZE.js.map +1 -0
- package/dist/{chunk-TLIVN7IU.js → chunk-XL5RSHZP.js} +2 -2
- package/dist/{chunk-VXNJGBUK.js → chunk-YY2HGKWR.js} +2 -2
- package/dist/{cli-DBDgdvh9.d.ts → cli-DUMkkdLl.d.ts} +1 -1
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +20 -20
- package/dist/compounding/engine.js +3 -3
- package/dist/connectors/codex-materialize-runner.js +3 -3
- package/dist/connectors/index.js +3 -3
- package/dist/entity-retrieval.js +3 -3
- package/dist/extraction-faithfulness.d.ts +23 -3
- package/dist/extraction-faithfulness.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +26 -26
- package/dist/maintenance/memory-governance.js +3 -3
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +3 -3
- package/dist/maintenance/rebuild-memory-projection.js +4 -4
- package/dist/mcp-memory-inspector-app.d.ts +1 -1
- package/dist/namespaces/migrate.js +4 -4
- package/dist/namespaces/storage.js +3 -3
- package/dist/operator-toolkit.js +8 -8
- package/dist/orchestration/maintenance.js +5 -5
- package/dist/orchestrator.js +14 -14
- package/dist/semantic-consolidation.js +4 -4
- package/dist/semantic-rule-promotion.js +3 -3
- package/dist/semantic-rule-verifier.js +3 -3
- package/dist/storage.js +2 -2
- package/dist/verified-recall.js +3 -3
- package/package.json +2 -2
- package/src/access-service.ts +17 -0
- package/src/coding/session-delta-surfaces.test.ts +185 -1
- package/src/coding/session-delta-surfaces.ts +30 -1
- package/src/coding/session-delta.test.ts +46 -0
- package/src/coding/session-delta.ts +18 -1
- package/src/extraction-faithfulness.test.ts +149 -5
- package/src/extraction-faithfulness.ts +195 -21
- package/dist/chunk-4X3LO5OF.js.map +0 -1
- package/dist/chunk-5MNL24XY.js.map +0 -1
- /package/dist/{chunk-75KYTVFK.js.map → chunk-2K64VH66.js.map} +0 -0
- /package/dist/{chunk-62Q2QA4Z.js.map → chunk-2KJG6ZZK.js.map} +0 -0
- /package/dist/{chunk-AYMVRRDP.js.map → chunk-2ULWWAQH.js.map} +0 -0
- /package/dist/{chunk-HKE7UREW.js.map → chunk-A62RAIBN.js.map} +0 -0
- /package/dist/{chunk-6YXRSHKG.js.map → chunk-ANZLT74L.js.map} +0 -0
- /package/dist/{chunk-N5UHWRGK.js.map → chunk-COEZR6F5.js.map} +0 -0
- /package/dist/{chunk-3LLLRQPV.js.map → chunk-CQ4PGFMC.js.map} +0 -0
- /package/dist/{chunk-AUGA5JZD.js.map → chunk-E6GOVHHJ.js.map} +0 -0
- /package/dist/{chunk-WHJ4WTHH.js.map → chunk-EZWQZYLK.js.map} +0 -0
- /package/dist/{chunk-GPHHYOQC.js.map → chunk-FSEQXHEZ.js.map} +0 -0
- /package/dist/{chunk-F5J5OVWF.js.map → chunk-HZ5DRA4Q.js.map} +0 -0
- /package/dist/{chunk-2IYYMOQZ.js.map → chunk-IZ5E6ZTK.js.map} +0 -0
- /package/dist/{chunk-FLV6YAS3.js.map → chunk-JYVD2XZ4.js.map} +0 -0
- /package/dist/{chunk-TAEO72ZC.js.map → chunk-LIWU4QI6.js.map} +0 -0
- /package/dist/{chunk-4LM6W5SX.js.map → chunk-M4DQWUKX.js.map} +0 -0
- /package/dist/{chunk-WDLJCSZ4.js.map → chunk-MRX6S22R.js.map} +0 -0
- /package/dist/{chunk-TFZKNDVY.js.map → chunk-N55RJT4N.js.map} +0 -0
- /package/dist/{chunk-AEPUGOPY.js.map → chunk-PJIHCOGV.js.map} +0 -0
- /package/dist/{chunk-UZW4UWIK.js.map → chunk-RIC5U67B.js.map} +0 -0
- /package/dist/{chunk-BQEZPX6Z.js.map → chunk-SIDSEXUG.js.map} +0 -0
- /package/dist/{chunk-4FXCAY7J.js.map → chunk-SJQ4HY3E.js.map} +0 -0
- /package/dist/{chunk-5JTY7OXQ.js.map → chunk-UDDSC6PO.js.map} +0 -0
- /package/dist/{chunk-TLIVN7IU.js.map → chunk-XL5RSHZP.js.map} +0 -0
- /package/dist/{chunk-VXNJGBUK.js.map → chunk-YY2HGKWR.js.map} +0 -0
|
@@ -72,6 +72,18 @@ export interface SessionDelta {
|
|
|
72
72
|
commits: GitCommit[];
|
|
73
73
|
/** Touched files since last seen, capped to {@link MAX_DELTA_FILES}. */
|
|
74
74
|
touchedFiles: string[];
|
|
75
|
+
/**
|
|
76
|
+
* Uncapped total commit count. The {@link commits} slice is capped for
|
|
77
|
+
* transport; this total reports the true delta size so summaries and
|
|
78
|
+
* metrics never under-report on large repos (issue #1630 fix 1).
|
|
79
|
+
*/
|
|
80
|
+
totalCommits: number;
|
|
81
|
+
/**
|
|
82
|
+
* Uncapped total touched-file count. The {@link touchedFiles} slice is
|
|
83
|
+
* capped for transport; this total reports the true delta size (issue
|
|
84
|
+
* #1630 fix 1).
|
|
85
|
+
*/
|
|
86
|
+
totalTouchedFiles: number;
|
|
75
87
|
/** A single human-readable summary line for briefing injection. */
|
|
76
88
|
summaryLine: string;
|
|
77
89
|
}
|
|
@@ -159,7 +171,12 @@ export function computeSessionDelta(
|
|
|
159
171
|
delta: {
|
|
160
172
|
commits,
|
|
161
173
|
touchedFiles,
|
|
162
|
-
|
|
174
|
+
// Uncapped totals — the slices above are capped for transport, but
|
|
175
|
+
// the summary/metrics must report the true delta size so callers
|
|
176
|
+
// never under-report on large repos (issue #1630 fix 1).
|
|
177
|
+
totalCommits: current.commits.length,
|
|
178
|
+
totalTouchedFiles: current.touchedFiles.length,
|
|
179
|
+
summaryLine: buildSummaryLine(current.commits.length, current.touchedFiles.length, lastSeen.at),
|
|
163
180
|
},
|
|
164
181
|
nextState,
|
|
165
182
|
};
|
|
@@ -794,12 +794,13 @@ test("applyFaithfulnessVerdict: per-fact backend failure (ok:false) → unchecke
|
|
|
794
794
|
assert.equal(r.enforceStatus, undefined);
|
|
795
795
|
});
|
|
796
796
|
|
|
797
|
-
test("locateFactQuote: finds the best-overlap sentence", () => {
|
|
797
|
+
test("locateFactQuote: finds the best-overlap sentence (returns LocatedQuote, issue #1633)", () => {
|
|
798
798
|
const src = "I drove to Berlin yesterday. My favorite editor is Vim.";
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
799
|
+
const located = locateFactQuote("The user likes Vim.", src);
|
|
800
|
+
assert.ok(located, "expected a located quote");
|
|
801
|
+
assert.equal(located!.quote, "My favorite editor is Vim.");
|
|
802
|
+
// offset must point at the matched candidate's actual position in sourceText.
|
|
803
|
+
assert.equal(located!.offset, src.indexOf("My favorite editor is Vim."));
|
|
803
804
|
});
|
|
804
805
|
|
|
805
806
|
test("locateFactQuote: returns undefined below the overlap threshold", () => {
|
|
@@ -812,6 +813,120 @@ test("locateFactQuote: empty inputs → undefined", () => {
|
|
|
812
813
|
assert.equal(locateFactQuote("fact", ""), undefined);
|
|
813
814
|
});
|
|
814
815
|
|
|
816
|
+
test("locateFactQuote: centers the bounded window on matched terms for >maxQuoteChars candidates (issue #1633, codex :747)", () => {
|
|
817
|
+
// The supporting terms ("PostgreSQL", "migration") fall well past the
|
|
818
|
+
// ~maxQuoteChars prefix. Returning the prefix would drop the evidence and
|
|
819
|
+
// route an actually-entailed fact to pending_review in enforce mode.
|
|
820
|
+
const filler = "Lorem ipsum dolor sit amet ".repeat(28); // ~728-char preamble
|
|
821
|
+
const sourceText = filler + "The team completed the PostgreSQL migration last quarter.";
|
|
822
|
+
const located = locateFactQuote(
|
|
823
|
+
"The team finished the PostgreSQL migration.",
|
|
824
|
+
sourceText,
|
|
825
|
+
200,
|
|
826
|
+
);
|
|
827
|
+
assert.ok(located, "expected a located quote");
|
|
828
|
+
assert.ok(
|
|
829
|
+
located!.quote.length <= 200,
|
|
830
|
+
`bounded quote must respect maxQuoteChars (got ${located!.quote.length})`,
|
|
831
|
+
);
|
|
832
|
+
// The matched evidence must survive truncation — the whole point of centering.
|
|
833
|
+
assert.ok(located!.quote.includes("PostgreSQL"), "bounded quote keeps 'PostgreSQL'");
|
|
834
|
+
assert.ok(located!.quote.includes("migration"), "bounded quote keeps 'migration'");
|
|
835
|
+
// offset must locate the returned (possibly bounded) quote within sourceText.
|
|
836
|
+
assert.equal(
|
|
837
|
+
sourceText.slice(located!.offset, located!.offset + located!.quote.length),
|
|
838
|
+
located!.quote,
|
|
839
|
+
"offset must point at the returned quote within sourceText",
|
|
840
|
+
);
|
|
841
|
+
});
|
|
842
|
+
|
|
843
|
+
test("locateFactQuote: tracks the matched occurrence offset for repeated anaphoric lines (issue #1633, codex :710, :710-thread-S)", () => {
|
|
844
|
+
// Two entities with the EXACT SAME anaphoric sentence afterward — the
|
|
845
|
+
// fact is about Zeta, which appears SECOND. Both "It launched in March."
|
|
846
|
+
// candidates score identically on own-overlap, so the locator must use the
|
|
847
|
+
// preceding-neighbor tiebreak to pick the occurrence whose neighbor ("Zeta")
|
|
848
|
+
// names the fact's entity. The offset must then point at the Zeta clause.
|
|
849
|
+
const sourceText =
|
|
850
|
+
"We started the Acme project in January. It launched in March. " +
|
|
851
|
+
"Then we began the Zeta initiative in February. It launched in March.";
|
|
852
|
+
const located = locateFactQuote("The Zeta initiative launched in March.", sourceText);
|
|
853
|
+
assert.ok(located, "expected a located quote");
|
|
854
|
+
// The matched quote is the (identical) anaphoric line; offset must point at
|
|
855
|
+
// the SECOND occurrence (the one after the Zeta clause), not the first.
|
|
856
|
+
const firstOccurrence = sourceText.indexOf("It launched in March.");
|
|
857
|
+
const secondOccurrence = sourceText.indexOf("It launched in March.", firstOccurrence + 1);
|
|
858
|
+
assert.ok(secondOccurrence > firstOccurrence, "test fixture must contain two occurrences");
|
|
859
|
+
assert.equal(
|
|
860
|
+
located!.offset,
|
|
861
|
+
secondOccurrence,
|
|
862
|
+
"offset must point at the second (Zeta) occurrence, not the first (Acme)",
|
|
863
|
+
);
|
|
864
|
+
assert.equal(
|
|
865
|
+
sourceText.slice(located!.offset, located!.offset + located!.quote.length),
|
|
866
|
+
located!.quote,
|
|
867
|
+
"offset must point at the start of the matched quote",
|
|
868
|
+
);
|
|
869
|
+
});
|
|
870
|
+
|
|
871
|
+
test("locateFactQuote: bounded window keeps the densest evidence cluster when matches span wider than maxQuoteChars (codex :747-thread-O)", () => {
|
|
872
|
+
// Fact tokens appear at BOTH ENDS of a long candidate with filler between.
|
|
873
|
+
// A naive midpoint-centered window would land in the filler and contain no
|
|
874
|
+
// evidence. The densest-cluster window must capture actual matched terms.
|
|
875
|
+
const head = "PostgreSQL migration completed. "; // matches at the very start
|
|
876
|
+
const filler = "and ".repeat(220); // ~880 chars of filler (no fact tokens)
|
|
877
|
+
const tail = " for the user."; // matches at the very end
|
|
878
|
+
const sourceText = head + filler + tail; // one long sentence, no period inside
|
|
879
|
+
// Fact spans tokens from both ends: postgresql, migration (head) + user (tail).
|
|
880
|
+
const located = locateFactQuote(
|
|
881
|
+
"The user completed the PostgreSQL migration.",
|
|
882
|
+
sourceText,
|
|
883
|
+
120,
|
|
884
|
+
);
|
|
885
|
+
assert.ok(located, "expected a located quote");
|
|
886
|
+
assert.ok(
|
|
887
|
+
located!.quote.length <= 120,
|
|
888
|
+
`bounded quote must respect maxQuoteChars (got ${located!.quote.length})`,
|
|
889
|
+
);
|
|
890
|
+
// The densest cluster is the head (2 matches: postgresql, migration); the
|
|
891
|
+
// window must contain at least one of them. (user appears alone at the tail,
|
|
892
|
+
// so a tail-anchored window would be sparser and is not chosen.)
|
|
893
|
+
assert.ok(
|
|
894
|
+
located!.quote.includes("PostgreSQL") || located!.quote.includes("migration"),
|
|
895
|
+
"bounded window must include matched evidence, not pure filler",
|
|
896
|
+
);
|
|
897
|
+
});
|
|
898
|
+
|
|
899
|
+
test("locateFactQuote: bounded window stays linear with many repeated matched tokens (codex PRRT_kwDORJXyws6Ocih3)", () => {
|
|
900
|
+
// A long unpunctuated candidate with thousands of repeats of a fact token
|
|
901
|
+
// (pasted logs / minified text). The densest-cluster selection must stay
|
|
902
|
+
// O(n) via the two-pointer sliding window; the O(n^2) nested loop would
|
|
903
|
+
// stall extraction on ~5k repeats. This test asserts both correctness (the
|
|
904
|
+
// bounded window contains the densest cluster) and that the call returns
|
|
905
|
+
// promptly — under O(n^2) this fixture (~5k repeats) would take seconds.
|
|
906
|
+
const repeats = 5000;
|
|
907
|
+
const token = "PostgreSQL "; // one fact token per repeat
|
|
908
|
+
const filler = "x ".repeat(50); // leading filler so the cluster is mid-string
|
|
909
|
+
const sourceText = filler + token.repeat(repeats) + "migration done";
|
|
910
|
+
const start = Date.now();
|
|
911
|
+
const located = locateFactQuote("PostgreSQL migration done.", sourceText, 200);
|
|
912
|
+
const elapsed = Date.now() - start;
|
|
913
|
+
assert.ok(located, "expected a located quote");
|
|
914
|
+
assert.ok(
|
|
915
|
+
located!.quote.length <= 200,
|
|
916
|
+
`bounded quote must respect maxQuoteChars (got ${located!.quote.length})`,
|
|
917
|
+
);
|
|
918
|
+
// The densest cluster is the run of PostgreSQL repeats; the window must be
|
|
919
|
+
// anchored inside it (not in the leading filler) and contain evidence.
|
|
920
|
+
assert.ok(
|
|
921
|
+
located!.quote.includes("PostgreSQL"),
|
|
922
|
+
"bounded window must anchor inside the densest cluster",
|
|
923
|
+
);
|
|
924
|
+
assert.ok(
|
|
925
|
+
elapsed < 1000,
|
|
926
|
+
`bounded window must stay linear (took ${elapsed}ms for ${repeats} repeats)`,
|
|
927
|
+
);
|
|
928
|
+
});
|
|
929
|
+
|
|
815
930
|
test("applyFaithfulnessVerdict: bumps verdict counters at apply time (cursor review)", () => {
|
|
816
931
|
const counters = createFaithfulnessCounters();
|
|
817
932
|
const map: Map<number, FaithfulnessResult> = new Map([
|
|
@@ -1042,6 +1157,35 @@ test("extractContextWindow: returns undefined when quote is absent from sourceTe
|
|
|
1042
1157
|
assert.equal(extractContextWindow("source", "s", 0), undefined);
|
|
1043
1158
|
});
|
|
1044
1159
|
|
|
1160
|
+
test("extractContextWindow: matchedOffset selects the matched occurrence, not the first (issue #1633, codex :710)", () => {
|
|
1161
|
+
// The same anaphoric line appears twice — once about Acme, once about Zeta.
|
|
1162
|
+
// Without matchedOffset, indexOf centers context on Acme (the first hit).
|
|
1163
|
+
// With the locator's offset, the window must center on the matched (Zeta) hit.
|
|
1164
|
+
const sourceText =
|
|
1165
|
+
"Acme context before. It launched in March. Acme context after. " +
|
|
1166
|
+
"Zeta context before. It launched in March. Zeta context after.";
|
|
1167
|
+
const quote = "It launched in March.";
|
|
1168
|
+
const firstOccurrence = sourceText.indexOf(quote);
|
|
1169
|
+
const zetaOccurrence = sourceText.indexOf("Zeta context before");
|
|
1170
|
+
assert.ok(firstOccurrence >= 0 && zetaOccurrence > firstOccurrence);
|
|
1171
|
+
// Budget 50 captures the surrounding entity tag without spanning both
|
|
1172
|
+
// occurrences (which would make them indistinguishable).
|
|
1173
|
+
const ctxDefault = extractContextWindow(sourceText, quote, 50);
|
|
1174
|
+
const ctxMatched = extractContextWindow(sourceText, quote, 50, zetaOccurrence);
|
|
1175
|
+
const ctxFirst = extractContextWindow(sourceText, quote, 50, firstOccurrence);
|
|
1176
|
+
assert.ok(ctxDefault && ctxMatched && ctxFirst, "all windows must resolve");
|
|
1177
|
+
assert.ok(
|
|
1178
|
+
ctxDefault!.includes("Acme") && !ctxDefault!.includes("Zeta"),
|
|
1179
|
+
"default (no offset) centers on the first (Acme) occurrence, not Zeta",
|
|
1180
|
+
);
|
|
1181
|
+
assert.ok(
|
|
1182
|
+
ctxMatched!.includes("Zeta") && !ctxMatched!.includes("Acme"),
|
|
1183
|
+
"matchedOffset centers on the matched (Zeta) occurrence, not Acme",
|
|
1184
|
+
);
|
|
1185
|
+
assert.notEqual(ctxMatched, ctxDefault, "windows must differ when offset disambiguates");
|
|
1186
|
+
assert.equal(ctxFirst, ctxDefault, "explicit first-occurrence offset equals the default");
|
|
1187
|
+
});
|
|
1188
|
+
|
|
1045
1189
|
test("runFaithfulnessGateBatch: fallback locator injects CONTEXT into the verifier prompt (codex P2 PRRT_kwDORJXyws6OblI1)", async () => {
|
|
1046
1190
|
// No #1575 sources → the fallback locator locates a quote from sourceText.
|
|
1047
1191
|
// Previously the input never set `context`, so the surrounding turn text
|
|
@@ -718,9 +718,26 @@ export function extractContextWindow(
|
|
|
718
718
|
sourceText: string,
|
|
719
719
|
quote: string,
|
|
720
720
|
contextChars: number,
|
|
721
|
+
/**
|
|
722
|
+
* Character offset of `quote` within `sourceText` (from `locateFactQuote`).
|
|
723
|
+
* When the quote string appears more than once — e.g. repeated anaphoric
|
|
724
|
+
* lines after different entities — pass the matched occurrence's offset so
|
|
725
|
+
* the context window centers on the actual match, not the first occurrence
|
|
726
|
+
* (issue #1633, codex PRRT_kwDORJXyws6ObzwI). Defaults to the first
|
|
727
|
+
* occurrence via indexOf for backward compatibility.
|
|
728
|
+
*/
|
|
729
|
+
matchedOffset?: number,
|
|
721
730
|
): string | undefined {
|
|
722
731
|
if (!sourceText || !quote || !(contextChars > 0)) return undefined;
|
|
723
|
-
|
|
732
|
+
let idx: number;
|
|
733
|
+
if (matchedOffset !== undefined && matchedOffset >= 0) {
|
|
734
|
+
const at = sourceText.indexOf(quote, matchedOffset);
|
|
735
|
+
// Fall back to the first occurrence if the matched offset is stale (e.g.
|
|
736
|
+
// the quote was bounded and is not a literal substring at that offset).
|
|
737
|
+
idx = at >= 0 ? at : sourceText.indexOf(quote);
|
|
738
|
+
} else {
|
|
739
|
+
idx = sourceText.indexOf(quote);
|
|
740
|
+
}
|
|
724
741
|
if (idx < 0) return undefined;
|
|
725
742
|
const quoteEnd = idx + quote.length;
|
|
726
743
|
const center = Math.floor((idx + quoteEnd) / 2);
|
|
@@ -733,31 +750,179 @@ export function extractContextWindow(
|
|
|
733
750
|
return window.length > 0 ? window : undefined;
|
|
734
751
|
}
|
|
735
752
|
|
|
753
|
+
/**
|
|
754
|
+
* A located fallback quote plus the offset it begins at in the source text.
|
|
755
|
+
* `offset` lets `extractContextWindow` disambiguate repeated occurrences of
|
|
756
|
+
* the same quote string (issue #1633).
|
|
757
|
+
*/
|
|
758
|
+
export interface LocatedQuote {
|
|
759
|
+
/** Verbatim source span, centered on the matched terms when truncated. */
|
|
760
|
+
quote: string;
|
|
761
|
+
/** Character offset of `quote` within sourceText. */
|
|
762
|
+
offset: number;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
interface SourceCandidate {
|
|
766
|
+
/** Trimmed candidate text. */
|
|
767
|
+
text: string;
|
|
768
|
+
/** Character offset of `text` within the source string. */
|
|
769
|
+
start: number;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Split source text into candidate spans (sentences, then line segments as a
|
|
774
|
+
* fallback for transcripts without sentence punctuation), tracking each
|
|
775
|
+
* candidate's start offset so repeated occurrences can be disambiguated
|
|
776
|
+
* (issue #1633).
|
|
777
|
+
*/
|
|
778
|
+
function splitSourceCandidates(sourceText: string): SourceCandidate[] {
|
|
779
|
+
const candidates: SourceCandidate[] = [];
|
|
780
|
+
const re = /(?<=[.!?])\s+|\n+/g;
|
|
781
|
+
let lastEnd = 0;
|
|
782
|
+
let m: RegExpExecArray | null;
|
|
783
|
+
while ((m = re.exec(sourceText)) !== null) {
|
|
784
|
+
pushCandidate(candidates, sourceText, lastEnd, m.index);
|
|
785
|
+
lastEnd = re.lastIndex;
|
|
786
|
+
}
|
|
787
|
+
pushCandidate(candidates, sourceText, lastEnd, sourceText.length);
|
|
788
|
+
return candidates;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function pushCandidate(
|
|
792
|
+
out: SourceCandidate[],
|
|
793
|
+
source: string,
|
|
794
|
+
begin: number,
|
|
795
|
+
end: number,
|
|
796
|
+
): void {
|
|
797
|
+
const seg = source.slice(begin, end);
|
|
798
|
+
const leadingWS = seg.length - seg.trimStart().length;
|
|
799
|
+
const trimmed = seg.trim();
|
|
800
|
+
if (trimmed.length > 0) {
|
|
801
|
+
out.push({ text: trimmed, start: begin + leadingWS });
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/**
|
|
806
|
+
* Locate the start offsets of fact-token matches inside a candidate. Used by
|
|
807
|
+
* `locateFactQuote` to build a bounded window that is guaranteed to contain
|
|
808
|
+
* real evidence (issue #1633, codex PRRT_kwDORJXyws6Obrwe / PRRT_kwDORJXyws6Oce-O).
|
|
809
|
+
*/
|
|
810
|
+
function locateMatchedTokens(factTokens: Set<string>, candidate: string): number[] {
|
|
811
|
+
const lower = candidate.toLowerCase();
|
|
812
|
+
const wordRe = /[a-z0-9]+/g;
|
|
813
|
+
const positions: number[] = [];
|
|
814
|
+
let m: RegExpExecArray | null;
|
|
815
|
+
while ((m = wordRe.exec(lower)) !== null) {
|
|
816
|
+
const word = m[0];
|
|
817
|
+
if (word.length <= 1) continue;
|
|
818
|
+
if (STOPWORDS.has(word)) continue;
|
|
819
|
+
if (factTokens.has(crudeStem(word))) {
|
|
820
|
+
positions.push(m.index);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
return positions;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Build a bounded window of `maxChars` from `text` that contains the densest
|
|
828
|
+
* cluster of matched-token positions. Slides a maxChars-wide window anchored
|
|
829
|
+
* at each matched token and keeps the one that captures the most matches
|
|
830
|
+
* (tiebreak: earliest anchor). This guarantees the window includes real
|
|
831
|
+
* evidence even when the matched span is wider than `maxChars` (e.g. fact
|
|
832
|
+
* tokens at both ends of a long sentence with filler between). Centering on
|
|
833
|
+
* the densest cluster's midpoint then uses any leftover budget as leading and
|
|
834
|
+
* trailing context. Returns the window text and its start offset within `text`
|
|
835
|
+
* so callers can translate the in-candidate offset back to a source-text offset.
|
|
836
|
+
*/
|
|
837
|
+
function boundedWindow(
|
|
838
|
+
text: string,
|
|
839
|
+
matchedPositions: number[],
|
|
840
|
+
maxChars: number,
|
|
841
|
+
): { text: string; start: number } {
|
|
842
|
+
if (matchedPositions.length === 0) {
|
|
843
|
+
// Defensive: overlap scoring accepted the candidate but no individual
|
|
844
|
+
// token matched (e.g. all matches were stopwords). Fall back to prefix.
|
|
845
|
+
const end = Math.min(text.length, maxChars);
|
|
846
|
+
return { text: text.slice(0, end), start: 0 };
|
|
847
|
+
}
|
|
848
|
+
// matchedPositions is sorted ascending (the regex scans left-to-right), so a
|
|
849
|
+
// two-pointer sliding window finds the densest maxChars-wide cluster in O(n)
|
|
850
|
+
// instead of O(n^2). This matters when a long unpunctuated candidate carries
|
|
851
|
+
// many repeats of a fact token (pasted logs, minified text) — thousands of
|
|
852
|
+
// positions would otherwise stall extraction before the LLM call (codex
|
|
853
|
+
// PRRT_kwDORJXyws6Ocih3).
|
|
854
|
+
let bestAnchor = matchedPositions[0]!;
|
|
855
|
+
let bestCount = 0;
|
|
856
|
+
let bestLast = bestAnchor;
|
|
857
|
+
let j = 0;
|
|
858
|
+
for (let i = 0; i < matchedPositions.length; i++) {
|
|
859
|
+
const anchor = matchedPositions[i]!;
|
|
860
|
+
const winEnd = anchor + maxChars;
|
|
861
|
+
if (j < i) j = i;
|
|
862
|
+
while (j + 1 < matchedPositions.length && matchedPositions[j + 1]! < winEnd) {
|
|
863
|
+
j++;
|
|
864
|
+
}
|
|
865
|
+
const count = j - i + 1;
|
|
866
|
+
if (count > bestCount) {
|
|
867
|
+
bestCount = count;
|
|
868
|
+
bestAnchor = anchor;
|
|
869
|
+
bestLast = matchedPositions[j]!;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
// The densest cluster [bestAnchor, bestLast] fits within maxChars by
|
|
873
|
+
// construction; center a maxChars window on its midpoint, clamped to text.
|
|
874
|
+
const center = Math.floor((bestAnchor + bestLast) / 2);
|
|
875
|
+
const half = Math.floor(maxChars / 2);
|
|
876
|
+
let start = Math.max(0, center - half);
|
|
877
|
+
const end = Math.min(text.length, start + maxChars);
|
|
878
|
+
// Re-anchor start so the window uses the full budget when end clamped.
|
|
879
|
+
start = Math.max(0, end - maxChars);
|
|
880
|
+
return { text: text.slice(start, end), start };
|
|
881
|
+
}
|
|
882
|
+
|
|
736
883
|
export function locateFactQuote(
|
|
737
884
|
factText: string,
|
|
738
885
|
sourceText: string,
|
|
739
886
|
maxQuoteChars = 600,
|
|
740
|
-
):
|
|
887
|
+
): LocatedQuote | undefined {
|
|
741
888
|
if (!factText || !sourceText) return undefined;
|
|
742
889
|
const factTokens = tokenize(factText);
|
|
743
890
|
if (factTokens.size === 0) return undefined;
|
|
744
|
-
|
|
745
|
-
// fallback for transcripts without sentence punctuation.
|
|
746
|
-
const candidates: string[] = [];
|
|
747
|
-
for (const sentence of sourceText.split(/(?<=[.!?])\s+|\n+/)) {
|
|
748
|
-
const s = sentence.trim();
|
|
749
|
-
if (s.length > 0) candidates.push(s);
|
|
750
|
-
}
|
|
891
|
+
const candidates = splitSourceCandidates(sourceText);
|
|
751
892
|
if (candidates.length === 0) return undefined;
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
893
|
+
// Pick the best-overlap candidate. Tiebreak equal own-overlap scores by a
|
|
894
|
+
// "context" score that includes the immediately PRECEDING candidate's text,
|
|
895
|
+
// so a repeated anaphoric line ("It launched in March") resolves to the
|
|
896
|
+
// occurrence whose neighbor names the fact's entity (issue #1633, codex
|
|
897
|
+
// PRRT_kwDORJXyws6Oce-S). Without this tiebreak the first occurrence wins
|
|
898
|
+
// even when the second is the one the fact refers to.
|
|
899
|
+
let best: { candidate: SourceCandidate; score: number; contextScore: number } | null = null;
|
|
900
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
901
|
+
const candidate = candidates[i]!;
|
|
902
|
+
const score = overlapCoefficient(factTokens, tokenize(candidate.text));
|
|
903
|
+
const prevText = i > 0 ? candidates[i - 1]!.text : "";
|
|
904
|
+
const contextText = prevText ? `${prevText} ${candidate.text}` : candidate.text;
|
|
905
|
+
const contextScore = overlapCoefficient(factTokens, tokenize(contextText));
|
|
906
|
+
if (
|
|
907
|
+
!best ||
|
|
908
|
+
score > best.score ||
|
|
909
|
+
(score === best.score && contextScore > best.contextScore)
|
|
910
|
+
) {
|
|
911
|
+
best = { candidate, score, contextScore };
|
|
912
|
+
}
|
|
756
913
|
}
|
|
757
914
|
if (!best || best.score < LOCATE_QUOTE_MIN_OVERLAP) return undefined;
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
:
|
|
915
|
+
const { text, start } = best.candidate;
|
|
916
|
+
if (text.length <= maxQuoteChars) {
|
|
917
|
+
return { quote: text, offset: start };
|
|
918
|
+
}
|
|
919
|
+
// Build a bounded window around the densest cluster of matched terms instead
|
|
920
|
+
// of returning the first maxQuoteChars prefix (issue #1633). Returning the
|
|
921
|
+
// prefix drops supporting words that fall after char ~600, routing
|
|
922
|
+
// actually-entailed facts to pending_review in enforce mode.
|
|
923
|
+
const matched = locateMatchedTokens(factTokens, text);
|
|
924
|
+
const win = boundedWindow(text, matched, maxQuoteChars);
|
|
925
|
+
return { quote: win.text, offset: start + win.start };
|
|
761
926
|
}
|
|
762
927
|
export async function runFaithfulnessGateBatch(
|
|
763
928
|
facts: readonly FaithfulnessGateFact[],
|
|
@@ -793,11 +958,19 @@ export async function runFaithfulnessGateBatch(
|
|
|
793
958
|
.map((s) => (s && typeof s.quote === "string" ? s.quote.trim() : ""))
|
|
794
959
|
.filter((q) => q.length > 0);
|
|
795
960
|
const usingFallbackLocator = sourceQuotes.length === 0;
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
961
|
+
let quote: string;
|
|
962
|
+
let matchedOffset: number | undefined;
|
|
963
|
+
if (sourceQuotes.length > 0) {
|
|
964
|
+
quote = sourceQuotes.join("\n");
|
|
965
|
+
} else {
|
|
966
|
+
// Fallback locator returns the matched span AND its offset so the
|
|
967
|
+
// context window centers on the occurrence that actually matched the
|
|
968
|
+
// fact, not the first indexOf hit (issue #1633).
|
|
969
|
+
const located = locateFactQuote(f.content, sourceText);
|
|
970
|
+
if (!located) continue; // no located span — applyFaithfulnessVerdict tags skipped_no_span
|
|
971
|
+
quote = located.quote;
|
|
972
|
+
matchedOffset = located.offset;
|
|
973
|
+
}
|
|
801
974
|
// Pass source context into the verifier so extractionFaithfulnessContextChars
|
|
802
975
|
// actually applies in the fallback-locator path (codex P2
|
|
803
976
|
// PRRT_kwDORJXyws6OblI1). #1575 verified spans already carry full evidence,
|
|
@@ -808,6 +981,7 @@ export async function runFaithfulnessGateBatch(
|
|
|
808
981
|
sourceText,
|
|
809
982
|
quote,
|
|
810
983
|
config.extractionFaithfulnessContextChars,
|
|
984
|
+
matchedOffset,
|
|
811
985
|
)
|
|
812
986
|
: undefined;
|
|
813
987
|
inputs.push({
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/extraction-faithfulness.ts"],"sourcesContent":["/**\n * Extraction faithfulness gate — entailment verification of extracted\n * facts against their verified source spans (issue #1576).\n *\n * Part of #1572 (glass-box memory). Depends on #1575 (provenance spans).\n * Improved later by #1585 (fine-tuned local gate model).\n *\n * Unlike the extraction-judge (#376), which gates on fact-worthiness\n * (\"is this worth remembering?\"), this module gates on faithfulness\n * (\"is this fact actually supported by what was said?\"). Hallucinated\n * or mis-paraphrased extractions become durable memories, get recalled\n * with confidence, and poison downstream answers — the highest-severity\n * accuracy failure a memory system can have.\n *\n * Design constraints:\n * - Tagged results only — a backend failure is distinguishable from a\n * genuine verdict (rule 34 / checklist §22: never conflate \"empty\"\n * with \"failed\").\n * - The gate consumes the QUOTE, not the whole conversation — passing\n * full turns re-introduces the hallucination surface you're guarding\n * and blows the latency budget.\n * - No module-level state — batch queues hang off the orchestrator\n * instance (rule 11).\n * - Byte-identical pre-feature pipeline when mode is \"off\" (rule 39).\n * - Graceful degradation — a backend failure never blocks writes\n * (checklist §4); the fact proceeds with verdict \"unchecked\".\n * - Never mutate mw_*\\/trust fields — faithfulness is its own\n * frontmatter island consumed by #1577.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { log } from \"./logger.js\";\nimport type { PluginConfig, MemoryFrontmatter, FaithfulnessFrontmatter } from \"./types.js\";\nimport type { LocalLlmClient } from \"./local-llm.js\";\nimport { type FallbackLlmClient, gatewayTaskChainOptions } from \"./fallback-llm.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\n\n// Re-export for callers importing from this module.\nexport type { FaithfulnessFrontmatter } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * The three entailment verdicts. \"unchecked\" is NOT a member of this union —\n * it lives only in the frontmatter to mark facts that bypassed the gate\n * (backend failure, no span, mode=off). A real verdict is always one of\n * these three.\n */\nexport type FaithfulnessVerdict = \"entailed\" | \"contradicted\" | \"unsupported\";\n\n/**\n * Failure codes for tagged-error results. Each is distinguishable so callers\n * and telemetry can tell \"no span available\" from \"the backend was down\".\n */\nexport type FaithfulnessFailureCode =\n | \"no_span\"\n | \"backend_unavailable\"\n | \"malformed_output\"\n | \"timeout\";\n\n/**\n * Tagged result — success carries the verdict + model + optional rationale;\n * failure carries only the error code. Never conflate the two (rule 34).\n */\nexport type FaithfulnessResult =\n | { ok: true; verdict: FaithfulnessVerdict; model: string; rationale?: string }\n | { ok: false; error: { code: FaithfulnessFailureCode } };\n\n/**\n * Input for a single faithfulness check. The quote is the verified span from\n * #1575; context is optional surrounding turn text (bounded by\n * faithfulnessContextChars).\n */\nexport interface FaithfulnessCheckInput {\n factText: string;\n quote: string;\n context?: string;\n}\n\n/**\n * Shape persisted to frontmatter (issue #1576). Serialized as a single JSON\n * line so it round-trips through the existing YAML parser without special\n * handling.\n *\n * `verdict: \"unchecked\"` marks a fact that entered the gate but could not be\n * evaluated (backend failure, timeout). It is distinct from the field being\n * absent (which means the gate was off entirely or the fact predates #1576).\n */\n\n// ---------------------------------------------------------------------------\n// Sealed prompt (hash lets #1573-style caching key on it)\n// ---------------------------------------------------------------------------\n\nconst FAITHFULNESS_SYSTEM_PROMPT = `You are a faithfulness verifier for a memory system. Given a QUOTE from the source conversation and an extracted FACT, determine whether the FACT is supported by the QUOTE.\n\nRules:\n- \"entailed\" — the FACT directly follows from the QUOTE (paraphrase is OK).\n- \"contradicted\" — the FACT asserts something the QUOTE directly negates.\n- \"unsupported\" — the FACT introduces information not present in the QUOTE.\n\nAnswer with a JSON array. Each element: {\"index\": <int>, \"verdict\": \"entailed\"|\"contradicted\"|\"unsupported\", \"rationale\": \"<one sentence>\"}.\n\nExamples:\nQUOTE: \"I've been using Vim for about ten years now.\"\nFACT: \"The user has used Vim for approximately a decade.\"\n{\"index\": 0, \"verdict\": \"entailed\", \"rationale\": \"Paraphrase of the same duration.\"}\n\nQUOTE: \"I've been using Vim for about ten years now.\"\nFACT: \"The user prefers Emacs.\"\n{\"index\": 0, \"verdict\": \"unsupported\", \"rationale\": \"QUOTE mentions Vim, not Emacs.\"}\n\nQUOTE: \"I stopped drinking coffee last month.\"\nFACT: \"The user drinks coffee regularly.\"\n{\"index\": 0, \"verdict\": \"contradicted\", \"rationale\": \"QUOTE says they stopped; FACT claims the opposite.\"}`;\n\n/**\n * SHA-256 hash of the sealed system prompt. Cache keys and prompt-version\n * telemetry include this so a prompt change is detectable (#1573-style\n * caching can invalidate stale entries).\n */\nexport const FAITHFULNESS_PROMPT_HASH = createHash(\"sha256\")\n .update(FAITHFULNESS_SYSTEM_PROMPT)\n .digest(\"hex\");\n\n// ---------------------------------------------------------------------------\n// Prompt construction\n// ---------------------------------------------------------------------------\n\n/**\n * Build the user-prompt payload for a batch of (fact, quote) pairs.\n * Each pair is numbered so the LLM's response can be correlated back.\n *\n * Context (when provided) is included after the quote, clearly delimited,\n * so the model knows it is supplementary — not the primary evidence.\n */\nfunction buildBatchPrompt(inputs: FaithfulnessCheckInput[], contextChars: number): string {\n const parts: string[] = [];\n for (let i = 0; i < inputs.length; i++) {\n const inp = inputs[i];\n if (!inp) continue;\n // The QUOTE is the primary entailment evidence and is already bounded\n // upstream (provenance.maxQuoteChars / locateFactQuote). Send it whole\n // so the verifier never judges entailment on a truncated span. Only the\n // supplementary CONTEXT is bounded by contextChars (the config's \"window\n // around the quote\" semantics — cursor review).\n parts.push(`--- Item ${i} ---\nQUOTE: \"${inp.quote}\"`);\n if (inp.context && inp.context.trim().length > 0) {\n parts.push(`CONTEXT: \"${inp.context.slice(0, contextChars)}\"`);\n }\n parts.push(`FACT: \"${inp.factText}\"\n\nRespond with the JSON array entry for index ${i}.`);\n }\n parts.push(`\\nRespond now with a single JSON array covering indexes 0–${inputs.length - 1}.`);\n return parts.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Response parsing\n// ---------------------------------------------------------------------------\n\nconst VALID_VERDICTS = new Set<string>([\"entailed\", \"contradicted\", \"unsupported\"]);\n\n/**\n * Parsed LLM response entry — validated shape.\n */\ninterface ParsedFaithfulnessEntry {\n index: number;\n verdict: FaithfulnessVerdict;\n rationale?: string;\n}\n\n/**\n * Parse the LLM response into a map of index → entry. Returns null when the\n * response is unparseable (rules 13/18: malformed output → tagged error,\n * never a crash).\n *\n * Accepts both a bare JSON array and a JSON array embedded in surrounding\n * text (the `extractJsonCandidates` helper handles fenced blocks and\n * code-block-wrapped JSON).\n */\nexport function parseFaithfulnessResponse(\n raw: string,\n expectedCount: number,\n): Map<number, ParsedFaithfulnessEntry> | null {\n if (!raw || typeof raw !== \"string\" || raw.trim().length === 0) {\n return null;\n }\n\n const candidates = extractJsonCandidates(raw);\n for (const candidate of candidates) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(candidate);\n } catch {\n continue;\n }\n const map = parseEntries(parsed, expectedCount);\n if (map) return map;\n }\n\n // Last resort: the model may have returned bare objects without array\n // wrapping — try parsing the whole thing as a single entry.\n try {\n const single = JSON.parse(raw.trim());\n const map = parseEntries([single], expectedCount);\n if (map) return map;\n } catch {\n // fall through\n }\n\n return null;\n}\n\nfunction parseEntries(\n data: unknown,\n expectedCount: number,\n): Map<number, ParsedFaithfulnessEntry> | null {\n if (!Array.isArray(data)) {\n // Accept object-wrapped arrays — {\"results\":[...]}, {\"verdicts\":[...]},\n // {\"entries\":[...]}, {\"facts\":[...]} — a common JSON-object prompt shape the\n // extraction-judge parser already accepts. Rejecting them marked the whole\n // batch malformed_output; in enforce mode those facts then wrote as ACTIVE\n // (gate bypass — codex Ob4RO).\n if (data && typeof data === \"object\") {\n for (const key of [\"results\", \"verdicts\", \"entries\", \"facts\"]) {\n const inner = (data as Record<string, unknown>)[key];\n if (Array.isArray(inner)) return parseEntries(inner, expectedCount);\n }\n }\n return null;\n }\n const map = new Map<number, ParsedFaithfulnessEntry>();\n for (const entry of data) {\n if (!entry || typeof entry !== \"object\") continue;\n const obj = entry as Record<string, unknown>;\n const idx = typeof obj.index === \"number\" ? obj.index : undefined;\n if (idx === undefined || idx < 0 || idx >= expectedCount) continue;\n const verdictRaw = typeof obj.verdict === \"string\" ? obj.verdict : undefined;\n if (!verdictRaw || !VALID_VERDICTS.has(verdictRaw)) continue;\n const rationale =\n typeof obj.rationale === \"string\" && obj.rationale.trim().length > 0\n ? obj.rationale.trim().slice(0, 500)\n : undefined;\n map.set(idx, {\n index: idx,\n verdict: verdictRaw as FaithfulnessVerdict,\n rationale,\n });\n }\n return map.size > 0 ? map : null;\n}\n\n// ---------------------------------------------------------------------------\n// LLM call helper\n// ---------------------------------------------------------------------------\n\ninterface LlmCallResult {\n content: string | null;\n modelUsed: string | null;\n}\n\n/**\n * Call the model routing chain (local → fallback) with the faithfulness\n * classification prompt. Mirrors `callJudgeLlm` in extraction-judge.ts so\n * the same routing, model-override, and gateway-chain logic applies.\n *\n * Returns the raw content string and the model that produced it, or\n * `{ content: null, modelUsed: null }` when every backend is unavailable.\n */\nasync function callFaithfulnessLlm(\n systemPrompt: string,\n userPrompt: string,\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<LlmCallResult> {\n const messages: Array<{ role: \"system\" | \"user\"; content: string }> = [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userPrompt },\n ];\n\n const modelOverride = config.extractionFaithfulnessModel || undefined;\n\n // Skip the local backend when (a) modelSource is \"gateway\", or (b) a\n // faithfulness model override is set. The local client always sends\n // config.localLlmModel and silently ignores options.model, so a local\n // success would run the wrong model and prevent the override from ever\n // reaching the gateway. Routing straight to the gateway honors the\n // override (codex review PRRT_kwDORJXyws6ObYQ8).\n const skipLocal = config.modelSource === \"gateway\" || Boolean(modelOverride);\n const gatewayChain = gatewayTaskChainOptions(config);\n\n let modelUsed: string | null = null;\n\n // Try local LLM first (only when no override routes the call to gateway).\n // The local client uses its OWN per-attempt AbortController keyed on\n // `timeoutMs` (it does not read options.signal — see LocalLlmChatCompletionOptions),\n // so the batch `signal` is not forwarded here; `timeoutMs` bounds each local\n // attempt instead. The batch AbortController still governs the fallback path,\n // which DOES honor the signal. (Matches extraction-judge.ts, which also passes\n // no signal to the local client.)\n if (localLlm && !skipLocal) {\n try {\n const result = await callLocalLlm(localLlm, messages, {\n temperature: 0.1,\n maxTokens: 2048,\n responseFormat: { type: \"json_object\" },\n timeoutMs,\n operation: \"extraction-faithfulness\",\n });\n if (result.content) {\n return { content: result.content, modelUsed: result.modelUsed ?? \"local\" };\n }\n } catch (err) {\n log.debug(\n `extraction-faithfulness: local LLM failed, trying fallback: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n // Try fallback LLM\n if (fallbackLlm) {\n try {\n const result = await fallbackLlm.chatCompletion(\n messages as Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n {\n temperature: 0.1,\n maxTokens: 2048,\n timeoutMs,\n ...(modelOverride ? { model: modelOverride } : {}),\n ...gatewayChain,\n ...(signal ? { signal } : {}),\n },\n );\n if (result?.content) {\n return { content: result.content, modelUsed: result.modelUsed ?? \"fallback\" };\n }\n } catch (err) {\n log.debug(\n `extraction-faithfulness: fallback LLM failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n return { content: null, modelUsed: null };\n}\n\n/**\n * Call the local LLM's chatCompletion through a narrow, typed interface.\n * LocalLlmClient.chatCompletion accepts an options bag that includes an\n * `operation` discriminator; we forward it so the client can route\n * appropriately.\n */\ninterface LocalLlmCallOptions {\n temperature: number;\n maxTokens: number;\n responseFormat?: { type: string };\n timeoutMs: number;\n operation: string;\n}\n\ninterface LocalLlmCallResponse {\n content: string | null;\n modelUsed?: string;\n}\n\nasync function callLocalLlm(\n client: LocalLlmClient,\n messages: Array<{ role: \"system\" | \"user\"; content: string }>,\n options: LocalLlmCallOptions,\n): Promise<LocalLlmCallResponse> {\n // LocalLlmClient.chatCompletion returns { content: string } — we use a\n // typed call signature so no `any` leaks. The local client does not\n // expose modelUsed, so we return \"local\" as the model identifier.\n const result = await client.chatCompletion(messages, options);\n return {\n content: result?.content ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Core batch check\n// ---------------------------------------------------------------------------\n\n/**\n * Result of a batch faithfulness check — per-input results plus timing.\n */\nexport interface FaithfulnessBatchResult {\n results: FaithfulnessResult[];\n /** Wall-clock duration of the LLM call (0 when backend was not called). */\n elapsedMs: number;\n}\n\n/**\n * Evaluate a batch of (fact, quote) pairs for faithfulness.\n *\n * - Calls the LLM once with all pairs (bounded by `inputs.length`).\n * - On timeout → every input gets `{ ok: false, code: \"timeout\" }`.\n * - On backend unavailable → `{ ok: false, code: \"backend_unavailable\" }`.\n * - On malformed output → `{ ok: false, code: \"malformed_output\" }`.\n * - Inputs with empty quotes get `{ ok: false, code: \"no_span\" }` and are\n * NOT sent to the LLM.\n *\n * No module-level state: the caller (orchestrator) owns any caches.\n */\nexport async function checkFaithfulnessBatch(\n inputs: FaithfulnessCheckInput[],\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n): Promise<FaithfulnessBatchResult> {\n const timeoutMs =\n typeof config.extractionFaithfulnessTimeoutMs === \"number\" &&\n Number.isFinite(config.extractionFaithfulnessTimeoutMs) &&\n config.extractionFaithfulnessTimeoutMs > 0\n ? config.extractionFaithfulnessTimeoutMs\n : 8000;\n\n const contextChars =\n typeof config.extractionFaithfulnessContextChars === \"number\" &&\n Number.isFinite(config.extractionFaithfulnessContextChars) &&\n config.extractionFaithfulnessContextChars > 0\n ? config.extractionFaithfulnessContextChars\n : 400;\n\n // Partition: inputs with a real quote vs. inputs without one.\n const results: FaithfulnessResult[] = new Array(inputs.length);\n const checkableIndices: number[] = [];\n const checkableInputs: FaithfulnessCheckInput[] = [];\n\n for (let i = 0; i < inputs.length; i++) {\n const inp = inputs[i];\n if (!inp || !inp.quote || inp.quote.trim().length === 0) {\n results[i] = { ok: false, error: { code: \"no_span\" } };\n } else if (!inp.factText || inp.factText.trim().length === 0) {\n results[i] = { ok: false, error: { code: \"no_span\" } };\n } else {\n checkableIndices.push(i);\n checkableInputs.push(inp);\n }\n }\n\n if (checkableInputs.length === 0) {\n return { results, elapsedMs: 0 };\n }\n\n const userPrompt = buildBatchPrompt(checkableInputs, contextChars);\n const startedAt = Date.now();\n\n let timedOut = false;\n const controller = new AbortController();\n // Race the LLM call against the budget so the batch fails open at\n // `timeoutMs` regardless of which backend is in flight. The local backend\n // ignores the batch AbortSignal (it aborts each attempt via its own\n // controller keyed on `timeoutMs`), so awaiting callFaithfulnessLlm directly\n // could block past the budget on a slow/retrying local verifier. The timer\n // both aborts the fallback (which honors the signal) and resolves the race\n // so the batch returns promptly; the in-flight local call aborts on its own\n // per-attempt timeoutMs. (codex review PRRT_kwDORJXyws6ObgMJ.)\n // Manual deferred instead of Promise.withResolvers (ES2024) — plugin-openclaw's\n // standalone tsconfig targets ES2022 lib and this module is reachable from its\n // type graph, so withResolvers would TS2550 there.\n let resolveTimeout!: (value: true) => void;\n const racedTimeout = new Promise<true>((resolve) => {\n resolveTimeout = resolve;\n });\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n resolveTimeout(true);\n }, timeoutMs);\n\n try {\n const callPromise = callFaithfulnessLlm(\n FAITHFULNESS_SYSTEM_PROMPT,\n userPrompt,\n config,\n localLlm,\n fallbackLlm,\n timeoutMs,\n controller.signal,\n );\n const settled = await Promise.race([\n callPromise.then(\n (r) => ({ done: true as const, result: r }),\n // An unexpected throw is treated as \"no content\" (backend_unavailable)\n // so the race never rejects and the outer catch is the final safety net.\n () => ({ done: true as const, result: { content: null, modelUsed: null } }),\n ),\n racedTimeout.then(() => ({ done: false as const })),\n ]);\n const elapsedMs = Date.now() - startedAt;\n\n if (!settled.done) {\n // The budget elapsed before any backend returned content. Fail open as\n // timeout; the orphaned callPromise resolves/rejects harmlessly (the\n // fallback was aborted; the local client aborts on its own timeoutMs).\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"timeout\" } };\n }\n return { results, elapsedMs };\n }\n\n const llmResult = settled.result;\n\n // Cursor review: if the LLM returned usable content, use it even when\n // the abort timer raced — a response that lands just as the timer fires\n // has real verdicts. Only fall back to timeout errors when there is no\n // content to parse (the call genuinely did not complete in time).\n if (timedOut && !llmResult.content) {\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"timeout\" } };\n }\n return { results, elapsedMs };\n }\n\n if (!llmResult.content) {\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"backend_unavailable\" } };\n }\n return { results, elapsedMs };\n }\n\n const parsed = parseFaithfulnessResponse(llmResult.content, checkableInputs.length);\n if (!parsed) {\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"malformed_output\" } };\n }\n return { results, elapsedMs };\n }\n\n for (let j = 0; j < checkableIndices.length; j++) {\n const inputIdx = checkableIndices[j];\n if (inputIdx === undefined) continue;\n const entry = parsed.get(j);\n if (entry) {\n results[inputIdx] = {\n ok: true,\n verdict: entry.verdict,\n model: llmResult.modelUsed ?? \"unknown\",\n ...(entry.rationale ? { rationale: entry.rationale } : {}),\n };\n } else {\n // LLM response was missing this index\n results[inputIdx] = { ok: false, error: { code: \"malformed_output\" } };\n }\n }\n\n return { results, elapsedMs };\n } catch (err) {\n const elapsedMs = Date.now() - startedAt;\n if (timedOut || isAbortError(err)) {\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"timeout\" } };\n }\n return { results, elapsedMs };\n }\n log.warn(\n `extraction-faithfulness: batch check threw unexpectedly: ${err instanceof Error ? err.message : String(err)}`,\n );\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"backend_unavailable\" } };\n }\n return { results, elapsedMs };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const maybe = err as { name?: string; message?: string };\n return (\n maybe.name === \"AbortError\" ||\n maybe.message === \"This operation was aborted\" ||\n maybe.message === \"The operation was aborted\"\n );\n}\n\n\n// ---------------------------------------------------------------------------\n// Extraction-path orchestration helpers (issue #1576)\n//\n// These wrap checkFaithfulnessBatch + verdict application so the orchestrator\n// holds only thin delegation (ground rule 4: god files gain thin wiring only).\n// The core algorithm lives above; these are call-site glue.\n// ---------------------------------------------------------------------------\n\n/**\n * Telemetry counters for the faithfulness gate. Hang off the orchestrator\n * instance (rule 11: no module-level state) and surface via console_state so\n * `remnic doctor` renders the verdict distribution.\n */\nexport interface FaithfulnessGateCounters {\n entailed: number;\n contradicted: number;\n unsupported: number;\n unchecked: number;\n skippedNoSpan: number;\n}\n\n/**\n * Create a fresh zeroed counters object. Callers store it on the orchestrator\n * instance and pass it by reference to the gate helpers, which mutate it.\n */\nexport function createFaithfulnessCounters(): FaithfulnessGateCounters {\n return { entailed: 0, contradicted: 0, unsupported: 0, unchecked: 0, skippedNoSpan: 0 };\n}\n\n/**\n * Structural slice of an extracted fact that the gate reads. Kept loose so\n * this pure module does not depend on the full `ExtractedFact` type.\n */\nexport interface FaithfulnessGateFact {\n content: string;\n sources?: { quote?: string }[];\n}\n\n/**\n * Run the faithfulness batch over a list of extracted facts and return a map\n * keyed by the ORIGINAL fact index → result. Facts without a usable verified\n * source span are omitted from the batch (they are tagged `skipped_no_span`\n * at apply time, never gated — don't punish legacy data). Updates `counters`\n * for console_state telemetry.\n *\n * Fail-open: any pipeline error is caught, logged, and an empty map returned\n * so the caller records `unchecked`/`skipped_no_span` and proceeds — a gate\n * outage must never block memory writes (checklist §4).\n */\n// Common English stopwords — filtered before overlap scoring so function\n// words (the, a, is, ...) don't dilute the signal between a fact and its\n// source sentence.\nconst STOPWORDS = new Set([\n \"the\",\"a\",\"an\",\"and\",\"or\",\"but\",\"is\",\"are\",\"was\",\"were\",\"be\",\"been\",\"being\",\n \"to\",\"of\",\"in\",\"on\",\"at\",\"for\",\"with\",\"from\",\"by\",\"as\",\"it\",\"its\",\"this\",\"that\",\n \"these\",\"those\",\"i\",\"you\",\"he\",\"she\",\"we\",\"they\",\"my\",\"your\",\"his\",\"her\",\"our\",\"their\",\n \"has\",\"have\",\"had\",\"do\",\"does\",\"did\",\"will\",\"would\",\"can\",\"could\",\"should\",\"not\",\"no\",\n \"s\",\"very\",\"really\",\"just\",\"so\",\"than\",\"then\",\"there\",\"here\",\"about\",\"into\",\"over\",\"under\",\n]);\n\n/**\n * Crude stemmer: strip common suffixes so \"prefers\"/\"prefer\",\n * \"using\"/\"use\", \"started\"/\"start\" collapse to one token. Not a real\n * stemmer — just enough to raise recall for the interim locator (#1575 will\n * replace this with NLI-verified spans).\n */\nfunction crudeStem(word: string): string {\n if (word.length > 5 && word.endsWith(\"ing\")) return word.slice(0, -3);\n if (word.length > 4 && word.endsWith(\"ed\")) return word.slice(0, -2);\n if (word.length > 3 && (word.endsWith(\"s\")) && !word.endsWith(\"ss\")) return word.slice(0, -1);\n return word;\n}\n\n/**\n * Tokenize text into a lowercase, stopword-filtered, crudely-stemmed token\n * set for overlap scoring.\n */\nfunction tokenize(text: string): Set<string> {\n const tokens = new Set<string>();\n for (const raw of text.toLowerCase().split(/[^a-z0-9]+/)) {\n if (raw.length <= 1) continue;\n if (STOPWORDS.has(raw)) continue;\n tokens.add(crudeStem(raw));\n }\n return tokens;\n}\n\n/**\n * Overlap coefficient: |A ∩ B| / min(|A|, |B|). Robust for paraphrase\n * matching where a short fact paraphrases a longer source sentence — a short\n * fact fully supported by a long sentence scores high, unrelated text scores 0.\n */\nfunction overlapCoefficient(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 || b.size === 0) return 0;\n let intersection = 0;\n const [small, large] = a.size <= b.size ? [a, b] : [b, a];\n for (const t of small) if (large.has(t)) intersection++;\n return intersection / small.size;\n}\n\n/**\n * Minimum overlap for a located quote to be trusted as the fact's source span.\n * Below this the fact is treated as having no located span (skipped_no_span)\n * rather than judged against an unrelated sentence.\n */\nconst LOCATE_QUOTE_MIN_OVERLAP = 0.3;\n\n/**\n * Locate the best-matching verbatim span (sentence) from the source turn text\n * for an extracted fact, by token overlap. Returns the quote when a confident\n * match is found, `undefined` otherwise (the gate then records\n * skipped_no_span — never judged against an unrelated span).\n *\n * This is the interim source-text locator that makes the gate functional on\n * real extraction output (where #1575 has not yet attached per-fact\n * `sources`). It produces a genuine located quote per fact so the gate\n * consumes a span, not the whole conversation (issue #1576 design constraint).\n * #1575's NLI-verified per-fact locator will replace this when it lands.\n */\n/**\n * Extract a bounded window of `sourceText` centered on the located `quote`,\n * bounded by `contextChars` (the config's \"window around the quote\" semantics).\n *\n * Used by the fallback-locator path in `runFaithfulnessGateBatch` so the\n * verifier sees surrounding turn text — without it,\n * `extractionFaithfulnessContextChars` is effectively ignored in the\n * production path (codex review PRRT_kwDORJXyws6OblI1). Returns undefined when\n * the quote is absent from sourceText (e.g. it was truncated by maxQuoteChars).\n */\nexport function extractContextWindow(\n sourceText: string,\n quote: string,\n contextChars: number,\n): string | undefined {\n if (!sourceText || !quote || !(contextChars > 0)) return undefined;\n const idx = sourceText.indexOf(quote);\n if (idx < 0) return undefined;\n const quoteEnd = idx + quote.length;\n const center = Math.floor((idx + quoteEnd) / 2);\n const half = Math.floor(contextChars / 2);\n let start = Math.max(0, center - half);\n const end = Math.min(sourceText.length, start + contextChars);\n // Re-anchor start so the window uses the full budget when end clamped.\n start = Math.max(0, end - contextChars);\n const window = sourceText.slice(start, end).trim();\n return window.length > 0 ? window : undefined;\n}\n\nexport function locateFactQuote(\n factText: string,\n sourceText: string,\n maxQuoteChars = 600,\n): string | undefined {\n if (!factText || !sourceText) return undefined;\n const factTokens = tokenize(factText);\n if (factTokens.size === 0) return undefined;\n // Split source into candidate spans: sentences, then line segments as a\n // fallback for transcripts without sentence punctuation.\n const candidates: string[] = [];\n for (const sentence of sourceText.split(/(?<=[.!?])\\s+|\\n+/)) {\n const s = sentence.trim();\n if (s.length > 0) candidates.push(s);\n }\n if (candidates.length === 0) return undefined;\n let best: { quote: string; score: number } | null = null;\n for (const candidate of candidates) {\n const score = overlapCoefficient(factTokens, tokenize(candidate));\n if (!best || score > best.score) best = { quote: candidate, score };\n }\n if (!best || best.score < LOCATE_QUOTE_MIN_OVERLAP) return undefined;\n return best.quote.length > maxQuoteChars\n ? best.quote.slice(0, maxQuoteChars)\n : best.quote;\n}\nexport async function runFaithfulnessGateBatch(\n facts: readonly FaithfulnessGateFact[],\n mode: \"shadow\" | \"enforce\",\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n counters: FaithfulnessGateCounters,\n /**\n * The verbatim source turn text the facts were extracted from. When a fact\n * has no #1575 `sources`, locateFactQuote finds a fallback span here so the\n * gate runs on real extraction output. May be empty (replay/import paths\n * with no source turns) — facts then get skipped_no_span.\n */\n sourceText = \"\",\n): Promise<Map<number, FaithfulnessResult> | null> {\n // Phase 1 — build the checkable inputs. This is pure (no LLM, no throw):\n // locateFactQuote and the source/span selection never reject. Keeping it\n // outside the try lets the catch walk the same inputs to tag a pipeline\n // failure as \"unchecked\" rather than dropping it on the floor.\n const inputs: { factIndex: number; input: FaithfulnessCheckInput }[] = [];\n for (let fi = 0; fi < facts.length; fi++) {\n const f = facts[fi];\n if (!f || typeof f.content !== \"string\" || !f.content.trim()) continue;\n // Prefer #1575 verified spans; fall back to a located quote from the\n // source turn text so the gate runs even before per-fact sources are\n // attached. Without either, the fact is skipped_no_span (never gated).\n // A composite fact may be supported by multiple adjacent spans — collect\n // every valid source quote so the verifier sees the full evidence, not\n // just sources[0] (codex review PRRT_kwDORJXyws6ObYQ_).\n const sources = Array.isArray(f.sources) ? f.sources : [];\n const sourceQuotes = sources\n .map((s) => (s && typeof s.quote === \"string\" ? s.quote.trim() : \"\"))\n .filter((q) => q.length > 0);\n const usingFallbackLocator = sourceQuotes.length === 0;\n const quote =\n sourceQuotes.length > 0\n ? sourceQuotes.join(\"\\n\")\n : locateFactQuote(f.content, sourceText);\n if (!quote) continue; // no located span — applyFaithfulnessVerdict tags skipped_no_span\n // Pass source context into the verifier so extractionFaithfulnessContextChars\n // actually applies in the fallback-locator path (codex P2\n // PRRT_kwDORJXyws6OblI1). #1575 verified spans already carry full evidence,\n // so context is only synthesized for the fallback locator.\n const fallbackContext =\n usingFallbackLocator\n ? extractContextWindow(\n sourceText,\n quote,\n config.extractionFaithfulnessContextChars,\n )\n : undefined;\n inputs.push({\n factIndex: fi,\n input: {\n factText: f.content,\n quote,\n ...(fallbackContext ? { context: fallbackContext } : {}),\n },\n });\n }\n const resultsByFactIndex = new Map<number, FaithfulnessResult>();\n if (inputs.length === 0) return resultsByFactIndex;\n try {\n const batch = await checkFaithfulnessBatch(\n inputs.map((x) => x.input),\n config,\n localLlm,\n fallbackLlm,\n );\n for (let j = 0; j < inputs.length; j++) {\n const entry = inputs[j];\n if (entry) resultsByFactIndex.set(entry.factIndex, batch.results[j]!);\n }\n // Verdict-distribution counters are bumped in applyFaithfulnessVerdict\n // (at the per-fact apply point), NOT here, so console_state reflects\n // facts that actually reached verdict application — not facts later\n // dropped by dedup, importance, or judge gates (cursor review).\n log.info(\n `extraction-faithfulness[${mode}]: ${inputs.length} facts checked, ${batch.elapsedMs}ms`,\n );\n } catch (err) {\n // Fail-open: a pipeline error never blocks writes (checklist §4). Tag each\n // checkable fact as backend_unavailable so applyFaithfulnessVerdict records\n // \"unchecked\" (issue spec: backend failure → unchecked). Returning null\n // here would make a shadow/enforce batch failure indistinguishable from\n // gate-off, losing the telemetry signal (cursor review). Facts with no\n // located span stay absent → skipped_no_span at apply time.\n log.warn(\n `extraction-faithfulness: pipeline error, tagging ${inputs.length} checkable facts as unchecked (fail-open): ${err instanceof Error ? err.message : String(err)}`,\n );\n for (const { factIndex } of inputs) {\n resultsByFactIndex.set(factIndex, { ok: false, error: { code: \"backend_unavailable\" } });\n }\n }\n return resultsByFactIndex;\n}\n\n/**\n * Apply a pre-computed faithfulness verdict to a single fact, producing the\n * frontmatter record + an optional enforce-mode `pending_review` status.\n *\n * - `resultsByFactIndex` null (gate off) → nothing (rule 39: byte-identical).\n * - fact has no entry (no verified span) → `skipped_no_span`, never gated.\n * - backend failure (`ok: false`) → `unchecked`, fact proceeds (checklist §4).\n * - enforce + unsupported/contradicted → `pending_review` (memory persists,\n * enters the review queue, never silently dropped).\n *\n * Mutates `counters.skippedNoSpan` for facts without a span.\n */\nexport function applyFaithfulnessVerdict(\n resultsByFactIndex: Map<number, FaithfulnessResult> | null,\n factLoopIndex: number,\n mode: \"off\" | \"shadow\" | \"enforce\",\n factContent: string,\n counters: FaithfulnessGateCounters,\n): {\n faithfulness: FaithfulnessFrontmatter | undefined;\n enforceStatus: \"pending_review\" | undefined;\n} {\n if (!resultsByFactIndex) {\n return { faithfulness: undefined, enforceStatus: undefined };\n }\n const result = resultsByFactIndex.get(factLoopIndex);\n if (!result) {\n // No result for this fact index — it had no verified source span.\n counters.skippedNoSpan++;\n return {\n faithfulness: { verdict: \"skipped_no_span\", at: new Date().toISOString() },\n enforceStatus: undefined,\n };\n }\n if (result.ok) {\n if (result.verdict === \"entailed\") counters.entailed++;\n else if (result.verdict === \"contradicted\") counters.contradicted++;\n else if (result.verdict === \"unsupported\") counters.unsupported++;\n const fm: FaithfulnessFrontmatter = {\n verdict: result.verdict,\n ...(result.model ? { model: result.model } : {}),\n ...(result.rationale ? { rationale: result.rationale } : {}),\n at: new Date().toISOString(),\n };\n let enforceStatus: \"pending_review\" | undefined;\n if (\n mode === \"enforce\" &&\n (result.verdict === \"unsupported\" || result.verdict === \"contradicted\")\n ) {\n enforceStatus = \"pending_review\";\n log.info(\n `extraction-faithfulness[enforce]: routing \"${factContent.slice(0, 60)}…\" to pending_review (verdict=${result.verdict})`,\n );\n }\n return { faithfulness: fm, enforceStatus };\n }\n // Backend failure — record as unchecked, fact proceeds (graceful degradation).\n counters.unchecked++;\n return {\n faithfulness: { verdict: \"unchecked\", at: new Date().toISOString() },\n enforceStatus: undefined,\n };\n}\n// ---------------------------------------------------------------------------\n// Frontmatter serialization (single-line JSON, like provenance sources)\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical key order for the serialized `faithfulness` frontmatter field.\n * Deterministic emission (rule 38).\n */\nconst FAITHFULNESS_KEY_ORDER = [\"verdict\", \"model\", \"rationale\", \"at\"] as const;\n\n/**\n * Serialize the `faithfulness` frontmatter field as a single JSON line,\n * appended to `lines`. Called from `serializeFrontmatter` in storage.ts.\n *\n * Contract: when `fm.faithfulness` is absent, no line is emitted — the\n * memory round-trips byte-identical to pre-#1576 behavior (rule 39).\n */\nexport function serializeFaithfulnessFields(fm: MemoryFrontmatter, lines: string[]): void {\n if (!fm.faithfulness) return;\n const fm2 = fm.faithfulness;\n const canonical: Record<string, unknown> = {};\n for (const key of FAITHFULNESS_KEY_ORDER) {\n const val = fm2[key];\n if (val !== undefined && val !== null && val !== \"\") {\n canonical[key] = val;\n }\n }\n // verdict is always present on a valid FaithfulnessFrontmatter\n if (!canonical.verdict) return;\n lines.push(`faithfulness: ${JSON.stringify(canonical)}`);\n}\n\n/**\n * Parse the `faithfulness` frontmatter line from its single-line JSON form.\n * Returns `undefined` for missing, blank, or corrupt values so a malformed\n * frontmatter never poisons downstream readers (rule 34 spirit).\n */\nexport function parseFaithfulnessField(\n raw: string | undefined,\n): FaithfulnessFrontmatter | undefined {\n if (!raw || typeof raw !== \"string\" || raw.trim().length === 0) return undefined;\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return undefined;\n const obj = parsed as Record<string, unknown>;\n const verdictRaw = typeof obj.verdict === \"string\" ? obj.verdict : undefined;\n if (!verdictRaw) return undefined;\n const validVerdicts = new Set([\n \"entailed\",\n \"contradicted\",\n \"unsupported\",\n \"unchecked\",\n \"skipped_no_span\",\n ]);\n if (!validVerdicts.has(verdictRaw)) return undefined;\n const result: FaithfulnessFrontmatter = {\n verdict: verdictRaw as FaithfulnessFrontmatter[\"verdict\"],\n };\n if (typeof obj.model === \"string\" && obj.model.length > 0) {\n result.model = obj.model;\n }\n if (typeof obj.rationale === \"string\" && obj.rationale.length > 0) {\n result.rationale = obj.rationale.slice(0, 500);\n }\n if (typeof obj.at === \"string\" && obj.at.length > 0) {\n result.at = obj.at;\n }\n return result;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8BA,SAAS,kBAAkB;AAkE3B,IAAM,6BAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2B5B,IAAM,2BAA2B,WAAW,QAAQ,EACxD,OAAO,0BAA0B,EACjC,OAAO,KAAK;AAaf,SAAS,iBA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