pi-muse-tether 0.1.0 → 0.2.0

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,86 +1,198 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import type { BridgeResult } from "pi-tether-core/mcp/bridge";
3
3
 
4
- /** Nonempty text parts join with one LF. Exactly [text, PNG image] adds
5
- * an image placeholder, NOT image bytes. Other rich layouts remain unqualified. */
6
- export type UnverifiableImage = { partIndex: number; sha256: string; byteLen: number; mimeType: string };
7
- function imageDeclaration(sent: BridgeResult): UnverifiableImage | undefined {
8
- if (sent.content.length !== 2 || sent.content[0]?.type !== "text" || !sent.content[0].text || sent.content[1]?.type !== "image" || sent.isError === true) return;
9
- const image = sent.content[1];
10
- if (image.mimeType !== "image/png" || !image.data) return;
11
- const bytes = Buffer.from(image.data, "base64");
12
- // Canonical base64 and the PNG signature prevent permissive Buffer decoding
13
- // from silently accepting malformed/foreign encodings before MCP delivery.
14
- if (bytes.toString("base64") !== image.data || !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) return;
15
- return { partIndex: 1, sha256: createHash("sha256").update(bytes).digest("hex"), byteLen: bytes.length, mimeType: image.mimeType };
4
+ /** MSP folds text chunks with LF boundaries and emits image metadata,
5
+ * never an attestation of pixels. Keep original parts for the Pi journal. */
6
+ export type UnverifiableImage = { partIndex: number; sha256: string; byteLen: number; mimeType: string; modelVisibility?: "omitted-error-result" };
7
+ const imageMagic: Record<string, (b: Buffer) => boolean> = {
8
+ "image/png": b => b.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])),
9
+ "image/jpeg": b => b[0] === 255 && b[1] === 216 && b[2] === 255,
10
+ "image/gif": b => ["GIF87a", "GIF89a"].includes(b.subarray(0,6).toString("ascii")),
11
+ "image/webp": b => b.subarray(0,4).toString("ascii") === "RIFF" && b.subarray(8,12).toString("ascii") === "WEBP",
12
+ };
13
+ function imageDeclarations(sent: BridgeResult): UnverifiableImage[] {
14
+ const images: UnverifiableImage[] = [];
15
+ for (const [partIndex, part] of sent.content.entries()) {
16
+ if (part.type === "text" && typeof part.text === "string") continue;
17
+ if (part.type !== "image" || !part.data || !imageMagic[part.mimeType])
18
+ throw new Error("Muse tool result cannot verify MCP parts: unsupported image or content type");
19
+ const bytes = Buffer.from(part.data, "base64");
20
+ if (bytes.toString("base64") !== part.data || !imageMagic[part.mimeType](bytes))
21
+ throw new Error("Muse tool result cannot verify MCP parts: malformed image encoding or MIME signature");
22
+ images.push({ partIndex, sha256: createHash("sha256").update(bytes).digest("hex"), byteLen: bytes.length, mimeType: part.mimeType,
23
+ ...(sent.isError === true ? {modelVisibility: "omitted-error-result" as const} : {}) });
24
+ }
25
+ return images;
16
26
  }
17
27
  export function assertToolResultVerifiable(sent: BridgeResult): void {
18
- const singleText = sent.content.length === 1 && sent.content[0]?.type === "text";
19
- const multiText = sent.isError !== true && sent.content.length > 1 && sent.content.every(p => p.type === "text" && p.text.length > 0);
20
- if (!singleText && !multiText && !imageDeclaration(sent)) {
21
- const kinds = sent.content.map(p => p.type).join(",");
22
- throw new Error(`Muse tool result cannot verify MCP parts [${kinds}]: MSP visibleOutput flattens text; modelVisibleContent exposes image metadata, not bytes or part boundaries`);
23
- }
28
+ imageDeclarations(sent);
24
29
  }
25
- export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string, onRedactions?: (spans: VendorRedaction[]) => void, onImages?: (images: UnverifiableImage[]) => void): BridgeResult {
26
- assertToolResultVerifiable(sent);
27
- if (item.modelVisibleContent?.length) throw new Error("Muse text receipt unexpectedly contains modelVisibleContent");
30
+ /** visibleBytes includes any displayed ellipsis; candidate offsets address the original projection. */
31
+ export type TruncatedView = { visibleBytes: number; projectionBytes: number; omittedOffsetBytes: number; omittedByteLen: number; sha256: string; ellipsisIdentity: "not-present" | "generated" | "ambiguous"; candidateOmittedOffsetsBytes: number[]; sources: {partIndex:number;partOffsetBytes:number;byteLen:number}[] };
32
+ /** MSP 1.4.14 live capture: 65,536 view bytes ended with U+2026, after an
33
+ * exact 65,533-byte original prefix. These observed lengths are not limits. */
34
+ function viewPrefixes(visible: string, full: string): string[] {
35
+ const candidates = [visible, ...(visible.endsWith("…") ? [visible.slice(0,-1)] : [])];
36
+ return candidates.filter(prefix => !(prefix.length && /[\uD800-\uDBFF]/.test(prefix.at(-1)!)) && full.startsWith(prefix));
37
+ }
38
+ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string, onRedactions?: (spans: VendorRedaction[]) => void, onImages?: (images: UnverifiableImage[]) => void, onTruncatedView?: (view: TruncatedView) => void): BridgeResult {
39
+ const images = imageDeclarations(sent);
40
+ if (images.length && !onImages) throw new Error("Muse image receipt requires declared-unverifiable reporting");
28
41
  if (typeof item.visibleOutput !== "string") throw new Error("Muse tool result missing visibleOutput");
29
- if (item.truncated && stored === undefined) throw new Error("Muse truncated tool result has no verifiable full outputRef readback");
42
+ if (item.truncated !== undefined && typeof item.truncated !== "boolean")
43
+ throw new Error("Muse tool result truncated flag must be boolean");
44
+ const partial = item.truncated === true && stored === undefined;
45
+ if (partial && item.outputRef !== undefined && (!item.outputRef || !["missing","unsupported","accessFailed"].includes(item.outputRef.availability)))
46
+ throw new Error("Muse truncated view outputRef requires strict readback or known unavailability");
47
+ if (partial && (!onTruncatedView || sent.isError === true || images.length))
48
+ throw new Error("Muse truncated view requires full readback for this result shape");
30
49
  const output = stored ?? item.visibleOutput;
31
- if (stored !== undefined) {
32
- if (item.truncated ? !stored.startsWith(item.visibleOutput) : stored !== item.visibleOutput)
33
- throw new Error("Muse stored tool output differs from visibleOutput");
34
- }
50
+ if (stored !== undefined && (item.truncated ? viewPrefixes(item.visibleOutput,stored).length === 0 : stored !== item.visibleOutput))
51
+ throw new Error("Muse stored tool output differs from visibleOutput");
52
+ let actual = output;
35
53
  if (sent.isError === true) {
36
- // ENOENT-style error frame: failed + verbatim failureReason; the display adds this prefix.
37
54
  if (item.status !== "failed" || item.failureKind !== undefined || typeof item.failureReason !== "string")
38
55
  throw new Error("Muse MCP error receipt requires failed status and verbatim failureReason without a host failureKind");
39
56
  if (output !== `tool failed: ${item.failureReason}`) throw new Error("Muse MCP error visibleOutput differs from failureReason");
40
- return reconcileVendorRedactions(sent, { content: [{ type: "text", text: item.failureReason }], isError: true }, onRedactions);
41
- }
42
- if (item.status !== "completed" || item.failureReason !== undefined || item.failureKind !== undefined)
57
+ actual = item.failureReason;
58
+ } else if (item.status !== "completed" || item.failureReason !== undefined || item.failureKind !== undefined) {
43
59
  throw new Error("Muse successful MCP receipt has non-completed status or failure fields");
44
- if (sent.content.length === 1) return reconcileVendorRedactions(sent, { content: [{ type: "text", text: output }], isError: false }, onRedactions);
45
- const image = imageDeclaration(sent);
46
- if (image && !onImages) throw new Error("Muse image receipt requires declared-unverifiable reporting");
47
- // Verify the image placeholder BEFORE any redaction reconciliation. A vendor
48
- // marker may occur inside text parts only; it can never hide changed metadata.
49
- const suffix = image ? `\n[MCP image content: media_type=${image.mimeType}, bytes=${image.byteLen}]` : "";
50
- if (image && !output.endsWith(suffix)) throw new Error("Muse tool result image placeholder differs from Pi MIME/decoded byte length");
51
- const actualText = image ? output.slice(0, -suffix.length) : output;
52
- const expectedText = sent.content.filter(p => p.type === "text").map(p => p.text).join("\n");
53
- const projected: BridgeResult = {content:[{type:"text",text:expectedText}],isError:false};
60
+ }
61
+ // Construct the ordered native projection from Pi parts. Never search/remove
62
+ // placeholder-shaped strings: literal tool text and leading LF remain bytes.
63
+ let expected = "";
64
+ const protectedImages: { start: number; end: number }[] = [];
65
+ const textSources: {partIndex:number; start:number; end:number}[] = [];
66
+ for (const [index, part] of sent.content.entries()) {
67
+ if (part.type === "text") {
68
+ // Native string folding ignores leading empty chunks but preserves a
69
+ // separator before an empty chunk after nonempty output (captured live).
70
+ if (expected) expected += "\n";
71
+ const start = Buffer.byteLength(expected);
72
+ expected += part.text;
73
+ textSources.push({partIndex:index,start,end:Buffer.byteLength(expected)});
74
+ } else {
75
+ // The official client's failed MCP path projects text only. Images were
76
+ // delivered to MCP, NOT exposed to the model; declare that known loss.
77
+ if (sent.isError === true) continue;
78
+ const image = images.find(image => image.partIndex === index)!;
79
+ if (expected) expected += "\n";
80
+ const start = expected.length;
81
+ expected += `[MCP image content: media_type=${image.mimeType}, bytes=${image.byteLen}]`;
82
+ protectedImages.push({ start, end: expected.length });
83
+ }
84
+ }
85
+ // Failed MCP results use a separate native codec: all text parts are
86
+ // LF-joined (including leading empties), and images are dropped.
87
+ if (sent.isError === true) {
88
+ expected = sent.content.filter(part => part.type === "text").map(part => (part as {text:string}).text).join("\n");
89
+ if (!expected) expected = "MCP tool returned an error";
90
+ textSources.length=0;
91
+ let offset=0;
92
+ for(const [partIndex,part] of sent.content.entries()) if(part.type==="text") {
93
+ textSources.push({partIndex,start:offset,end:offset+Buffer.byteLength(part.text)});
94
+ offset+=Buffer.byteLength(part.text)+1;
95
+ }
96
+ } else if (!expected) expected = "[MCP tool returned no content]";
97
+ const locateSources=(redactions:VendorRedaction[])=>{
98
+ for(const span of redactions) span.sources=textSources.filter(s=>s.start<span.piOffsetBytes+span.piByteLen && s.end>span.piOffsetBytes).map(s=>({partIndex:s.partIndex,partOffsetBytes:Math.max(s.start,span.piOffsetBytes)-s.start,byteLen:Math.min(s.end,span.piOffsetBytes+span.piByteLen)-Math.max(s.start,span.piOffsetBytes)}));
99
+ };
100
+ if (partial) {
101
+ // The captured combined codec preserves line boundaries. Reconcile
102
+ // complete lines normally and the final line with the same v4 positional
103
+ // alignment in prefix mode, retaining every viable original cut.
104
+ const visibleEnd=actual.lastIndexOf("\n")+1;
105
+ let originalEnd=0;
106
+ for(let at=0;at<visibleEnd;at++) if(actual[at]==="\n") {
107
+ const next=expected.indexOf("\n",originalEnd);
108
+ if(next<0) throw new Error("Muse truncated view has more lines than native projection");
109
+ originalEnd=next+1;
110
+ }
111
+ const completeExpected=expected.slice(0,originalEnd),completeVisible=actual.slice(0,visibleEnd);
112
+ const projected:BridgeResult={content:[{type:"text",text:completeExpected}],isError:false};
113
+ let redactions:VendorRedaction[]=[];
114
+ const observed=reconcileVendorRedactions(projected,{content:[{type:"text",text:completeVisible}],isError:false},spans=>{redactions=spans;});
115
+ if ((observed.content[0] as {text:string}).text!==completeExpected)
116
+ throw new Error("Muse truncated view complete lines differ from native projection");
117
+ if(redactions.length && !onRedactions) throw new Error("Muse truncated view requires declared-redaction reporting");
118
+ const finalVisible=actual.slice(visibleEnd),finalExpected=expected.slice(originalEnd).split("\n",1)[0];
119
+ let finalSpans:VendorRedaction[]=[],prefix:PrefixAlignment|undefined;
120
+ reconcileVendorRedactions({content:[{type:"text",text:finalExpected}],isError:false},
121
+ {content:[{type:"text",text:finalVisible}],isError:false},spans=>{finalSpans=spans;},alignment=>{prefix=alignment;});
122
+ if(!prefix) throw new Error("Muse truncated view differs from native projection prefix");
123
+ const baseBytes=Buffer.byteLength(completeExpected),viewBaseBytes=Buffer.byteLength(completeVisible);
124
+ for(const span of finalSpans) {
125
+ span.piOffsetBytes+=baseBytes;span.museOffsetBytes+=viewBaseBytes;
126
+ if(span.candidateStartBytes)span.candidateStartBytes=span.candidateStartBytes.map(offset=>offset+baseBytes);
127
+ if(span.candidateEndBytes)span.candidateEndBytes=span.candidateEndBytes.map(offset=>offset+baseBytes);
128
+ }
129
+ redactions.push(...finalSpans);
130
+ if(redactions.length && !onRedactions) throw new Error("Muse truncated view requires declared-redaction reporting");
131
+ const candidateOmittedOffsetsBytes=prefix.cuts.map(cut=>baseBytes+Buffer.byteLength(finalExpected.slice(0,cut))).sort((a,b)=>a-b);
132
+ const omittedOffsetBytes=candidateOmittedOffsetsBytes[0], projectionBytes=Buffer.byteLength(expected);
133
+ const ellipsisIdentity=prefix.ellipsisIdentity;
134
+ const omitted = Buffer.from(expected, "utf8").subarray(omittedOffsetBytes);
135
+ locateSources(redactions);
136
+ // Both checks succeeded; publish no partial evidence on a rejected view.
137
+ if(redactions.length) onRedactions!(redactions);
138
+ onTruncatedView!({visibleBytes:Buffer.byteLength(item.visibleOutput),projectionBytes,omittedOffsetBytes,
139
+ omittedByteLen:omitted.length,sha256:createHash("sha256").update(omitted).digest("hex"),ellipsisIdentity,candidateOmittedOffsetsBytes,
140
+ sources:textSources.filter(s=>s.end>omittedOffsetBytes).map(s=>({partIndex:s.partIndex,
141
+ partOffsetBytes:Math.max(s.start,omittedOffsetBytes)-s.start,byteLen:s.end-Math.max(s.start,omittedOffsetBytes)}))});
142
+ return sent;
143
+ }
144
+ const projected: BridgeResult = { content: [{ type: "text", text: expected }], isError: sent.isError === true };
54
145
  let redactions: VendorRedaction[] = [];
55
- const reconciled = reconcileVendorRedactions(projected, {content:[{type:"text",text:actualText}],isError:false}, spans => { redactions = spans; });
56
- if ((reconciled.content[0] as {text:string}).text !== expectedText) throw new Error("Muse tool result text projection mismatch");
57
- // Existing intraline alignment cannot cross a part's inserted LF boundary.
58
- // Spans address this ordered LF-joined text projection, never image bytes.
146
+ const observed = reconcileVendorRedactions(projected, { content: [{ type: "text", text: actual }], isError: sent.isError === true }, spans => { redactions = spans; });
147
+ if ((observed.content[0] as { text: string }).text !== expected) {
148
+ let at=0;
149
+ while(at<expected.length && at<actual.length && expected[at]===actual[at])at++;
150
+ throw new Error(`Muse tool result text projection mismatch (image placeholder differs or text changed) at projection byte ${Buffer.byteLength(expected.slice(0,at))}, receipt byte ${Buffer.byteLength(actual.slice(0,at))}`);
151
+ }
152
+ for (const span of redactions) {
153
+ if (protectedImages.some(range => span.piOffsetBytes < Buffer.byteLength(expected.slice(0, range.end)) &&
154
+ span.piOffsetBytes + span.piByteLen > Buffer.byteLength(expected.slice(0, range.start))))
155
+ throw new Error("Muse image placeholder differs: redaction cannot hide image metadata");
156
+ }
157
+ locateSources(redactions);
59
158
  if (redactions.length) onRedactions?.(redactions);
60
- if (image) onImages?.([image]);
61
- // Preserve the original Pi shape for its exact journal hash. Image bytes here
62
- // are declared UNVERIFIABLE; the callback/ledger must not claim consumption.
159
+ if (images.length) onImages?.(images);
160
+ // modelVisibleContent may contain image derivatives or metadata. It is useful
161
+ // evidence of delivery but never upgrades these declarations to exact pixels.
63
162
  return sent;
64
163
  }
65
164
 
66
- /** Byte offsets address original Pi text and the actual Muse text receipt.
67
- * Multipart offsets use LF-joined text parts (never the image placeholder).
68
- * Never include removed text in metadata. This is declared vendor loss, NOT
69
- * proof that the model consumed the original bytes. */
70
- export type VendorRedaction = { piOffsetBytes: number; museOffsetBytes: number; piByteLen: number; sha256: string };
165
+ /** Offsets address UTF-8 bytes in the native projection and vendor receipt.
166
+ * Ambiguous spans cover the union of viable alignments, not an invented exact
167
+ * removal. Hashes describe that source range; removed bytes are never logged. */
168
+ export type VendorRedaction = {
169
+ piOffsetBytes: number; museOffsetBytes: number; piByteLen: number; sha256: string;
170
+ reason: "vendor-redaction" | "ambiguous-vendor-redaction" | "vendor-bearer-prefix";
171
+ alignment: "unique" | "ambiguous";
172
+ ambiguityReason?: "multiple-alignments" | "literal-marker-identity";
173
+ sources?: {partIndex:number;partOffsetBytes:number;byteLen:number}[];
174
+ candidateStartBytes?: number[]; candidateEndBytes?: number[];
175
+ };
71
176
  const marker = "[REDACTED]";
72
- function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, report?: (spans: VendorRedaction[]) => void): BridgeResult {
177
+ type PrefixAlignment={cuts:number[];ellipsisIdentity:TruncatedView["ellipsisIdentity"]};
178
+ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, report?: (spans: VendorRedaction[]) => void, onPrefix?: (alignment:PrefixAlignment)=>void): BridgeResult {
73
179
  const pi = (sent.content[0] as {text:string}).text;
74
180
  const muse = (observed.content[0] as {text:string}).text;
75
- if (pi === muse || !muse.includes(marker)) return observed;
76
- // DECLARED LOSSY TRANSPORT ACCEPTANCE, not verification of removed bytes.
77
- // The pinned binary exposes the marker and token prefixes, but not a complete
78
- // provable runtime pattern set. Conservative fallback: unique alignment,
79
- // nonempty single-line removed spans bounded on BOTH sides by exact text.
80
- // Literal Pi markers must match literally and may never be swallowed by a gap.
81
- type Span = { piStart: number; piEnd: number; museStart: number };
82
- const invalid = () => new Error("Muse tool result mismatch: invalid or ambiguous vendor redaction");
83
- // Match literal chunks with KMP, not a fresh suffix scan at every candidate.
181
+ if(onPrefix && !muse.includes(marker)) {
182
+ const prefixes=viewPrefixes(muse,pi);
183
+ if(!prefixes.length) throw new Error("Muse truncated view differs from native projection prefix");
184
+ onPrefix({cuts:prefixes.map(p=>p.length),ellipsisIdentity:muse.endsWith("…") ? prefixes.length===2 ? "ambiguous" : "generated" : "not-present"});
185
+ return sent;
186
+ }
187
+ if (!onPrefix && (pi === muse || !muse.includes(marker))) return observed;
188
+ const invalid = (piAt: number, museAt: number) => new Error(`Muse tool result mismatch: invalid vendor redaction at projection byte ${Buffer.byteLength(pi.slice(0, piAt))}, receipt byte ${Buffer.byteLength(muse.slice(0, museAt))}`);
189
+ const spans: VendorRedaction[] = [];
190
+ function record(start: number, end: number, visible: number, reason: VendorRedaction["reason"], alignment: VendorRedaction["alignment"], candidates?: {starts:number[];ends:number[]}) {
191
+ spans.push({piOffsetBytes:Buffer.byteLength(pi.slice(0,start)),museOffsetBytes:Buffer.byteLength(muse.slice(0,visible)),
192
+ piByteLen:Buffer.byteLength(pi.slice(start,end)),sha256:createHash("sha256").update(pi.slice(start,end)).digest("hex"),reason,alignment,
193
+ ...(candidates ? {candidateStartBytes:candidates.starts.map(a=>Buffer.byteLength(pi.slice(0,a))),candidateEndBytes:candidates.ends.map(a=>Buffer.byteLength(pi.slice(0,a)))} : {})});
194
+ }
195
+ // KMP keeps literal matching linear in the source length per marker.
84
196
  function starts(text: string, chunk: string): Uint8Array {
85
197
  const found = new Uint8Array(text.length + 1);
86
198
  if (!chunk.length) { found.fill(1); return found; }
@@ -97,70 +209,117 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
97
209
  }
98
210
  return found;
99
211
  }
100
- function lineSpans(text: string, visible: string): Span[] {
101
- const pieces = visible.split(marker), n = text.length;
102
- if (pieces.length === 1 || !text.startsWith(pieces[0])) throw invalid();
103
- // Each backward layer counts complete parses after one marker. Range sums
104
- // make a variable-length hole O(1) per position: O(n * markerCount), not
105
- // quadratic suffix rescanning for a single gap. 2 means ambiguous, not a cap.
106
- const barrier = new Int32Array(n + 1); barrier[n] = n;
107
- for (let a = n - 1; a >= 0; a--)
108
- barrier[a] = text[a] === "\r" || text.startsWith(marker, a) ? a : barrier[a + 1];
109
- let next = new Uint8Array(n + 1); next[n] = 1;
110
- const choices: Int32Array[] = [];
111
- for (let i = pieces.length - 2; i >= 0; i--) {
112
- const chunk = pieces[i + 1], matches = starts(text, chunk);
113
- const sum = new Float64Array(n + 2), first = new Int32Array(n + 2); first.fill(-1);
114
- for (let a = n; a >= 0; a--) {
115
- const ways = matches[a] ? next[a + chunk.length] ?? 0 : 0;
116
- sum[a] = sum[a + 1] + ways;
117
- first[a] = ways ? a : first[a + 1];
212
+ function line(text: string, visible: string, piBase: number, museBase: number) {
213
+ const pieces: string[] = [], widths: number[] = [], positions: number[] = [];
214
+ let cursor = 0, at: number;
215
+ while ((at = visible.indexOf(marker, cursor)) !== -1) {
216
+ pieces.push(visible.slice(cursor, at)); positions.push(at); cursor = at;
217
+ let width = 0;
218
+ while (visible.startsWith(marker, cursor)) { width++; cursor += marker.length; }
219
+ widths.push(width);
220
+ }
221
+ pieces.push(visible.slice(cursor));
222
+ const n = text.length, count = widths.length;
223
+ const boundary=(at:number)=>!(at>0 && at<n && /[\uD800-\uDBFF]/.test(text[at-1]) && /[\uDC00-\uDFFF]/.test(text[at]));
224
+ if (!count || !boundary(pieces[0].length)) throw invalid(piBase, museBase);
225
+ const matches = pieces.map((chunk,i) => {
226
+ const exact = starts(text, chunk);
227
+ // Captured official-client codec: `bearer permission.` becomes
228
+ // `Bearer [REDACTED]`. ONLY the prefix immediately before a marker is
229
+ // case-folded; no other text/case/status/metadata normalization is allowed.
230
+ if (i < count && chunk.endsWith("Bearer ")) {
231
+ const prefix = chunk.slice(0,-7), candidates = starts(text,prefix);
232
+ for(let a=0;a+chunk.length<=n;a++)
233
+ if(candidates[a] && text.slice(a+prefix.length,a+chunk.length).toLowerCase()==="bearer ") exact[a]=1;
118
234
  }
119
- const current = new Uint8Array(n + 1), choice = new Int32Array(n + 1); choice.fill(-2);
120
- for (let a = 0; a <= n; a++) {
121
- if (text.startsWith(marker, a)) {
122
- const end = a + marker.length;
123
- current[a] = matches[end] ? next[end + chunk.length] ?? 0 : 0;
124
- if (current[a] === 1) choice[a] = -1; // literal marker, never a hole
125
- } else if (a > 0 && pieces[i].length && chunk.length && barrier[a] > a) {
126
- const ways = sum[a + 1] - sum[barrier[a] + 1];
127
- current[a] = Math.min(2, ways);
128
- if (ways === 1) choice[a] = first[a + 1];
129
- }
235
+ return exact;
236
+ });
237
+ if (!matches[0][0]) throw invalid(piBase, museBase);
238
+ // Backward feasibility. A marker declares a nonempty single-line hole.
239
+ // Literal marker text is allowed inside a hole: when that loses identity,
240
+ // the evidence is ambiguous, never silently claimed exact or made fatal.
241
+ const layers: Uint8Array[] = [];
242
+ let next = new Uint8Array(n+1); if(onPrefix)next.fill(1);else next[n]=1;
243
+ const last=pieces[count],shortLast=onPrefix && last.endsWith("…") ? last.slice(0,-1) : undefined;
244
+ const shortMatches=shortLast===undefined ? undefined : starts(text,shortLast);
245
+ for(let i=count-1;i>=0;i--) {
246
+ const chunk=pieces[i+1], viable=new Uint8Array(n+1);
247
+ for(let end=0;end<=n;end++)
248
+ viable[end]=boundary(end) && ((end+chunk.length<=n && matches[i+1][end] && boundary(end+chunk.length) && next[end+chunk.length]) ||
249
+ (i===count-1 && shortLast!==undefined && end+shortLast.length<=n && shortMatches![end] && boundary(end+shortLast.length) && next[end+shortLast.length])) ? 1 : 0;
250
+ layers[i]=viable;
251
+ const current=new Uint8Array(n+1); let found=false;
252
+ for(let a=n;a>=0;a--) {
253
+ // CR is a line boundary too, not something a declared hole may hide.
254
+ if(text[a]==="\r") found=false;
255
+ current[a]=found?1:0;
256
+ if(viable[a]) found=true;
130
257
  }
131
- choices[i] = choice; next = current;
258
+ next=current;
132
259
  }
133
- let a = pieces[0].length, b = a;
134
- if (next[a] !== 1) throw invalid();
135
- const spans: Span[] = [];
136
- for (let i = 0; i < choices.length; i++) {
137
- const end = choices[i][a];
138
- if (end >= 0) spans.push({ piStart: a, piEnd: end, museStart: b });
139
- a = (end === -1 ? a + marker.length : end) + pieces[i + 1].length;
140
- b += marker.length + pieces[i + 1].length;
260
+ if(!next[pieces[0].length]) throw invalid(piBase, museBase);
261
+ // Forward reachable starts plus backward viable ends give all candidate
262
+ // boundaries without enumerating exponentially many complete parses.
263
+ let reachable=new Uint8Array(n+1);reachable[pieces[0].length]=1;
264
+ for(let i=0;i<count;i++) {
265
+ const viable=layers[i], chunk=pieces[i+1];
266
+ const candidateStarts:number[]=[], candidateEnds:number[]=[];
267
+ let lastEnd=-1;
268
+ for(let a=n;a>=0;a--) {
269
+ if(text[a]==="\r") lastEnd=-1;
270
+ if(reachable[a] && lastEnd>a) candidateStarts.push(a);
271
+ if(viable[a]) lastEnd=a;
272
+ }
273
+ candidateStarts.reverse();
274
+ let seen=false;
275
+ const following=new Uint8Array(n+1);let fullCut=false,shortCut=false;
276
+ for(let end=0;end<=n;end++) {
277
+ if(text[end-1]==="\r") seen=false;
278
+ if(end>0 && reachable[end-1] && text[end-1]!=="\r") seen=true;
279
+ if(seen && viable[end]) {
280
+ candidateEnds.push(end);
281
+ if(i===count-1 && onPrefix) {
282
+ if(end+chunk.length<=n && matches[i+1][end] && boundary(end+chunk.length) && !(end+chunk.length>0 && /[\uD800-\uDBFF]/.test(text[end+chunk.length-1]))) {following[end+chunk.length]=1;fullCut=true;}
283
+ if(shortLast!==undefined && end+shortLast.length<=n && shortMatches![end] && boundary(end+shortLast.length) && !(end+shortLast.length>0 && /[\uD800-\uDBFF]/.test(text[end+shortLast.length-1]))) {following[end+shortLast.length]=1;shortCut=true;}
284
+ } else following[end+chunk.length]=1;
285
+ }
286
+ }
287
+ const multiple=candidateStarts.length!==1 || candidateEnds.length!==1;
288
+ const start=candidateStarts[0], end=candidateEnds.at(-1)!;
289
+ const literal=!multiple && text.slice(start,end)===marker.repeat(widths[i]);
290
+ const literalIdentity=!literal && text.slice(start,end).includes(marker);
291
+ const ambiguous=multiple || literalIdentity;
292
+ if(!literal)record(piBase+start,piBase+end,museBase+positions[i],ambiguous?"ambiguous-vendor-redaction":"vendor-redaction",ambiguous?"ambiguous":"unique",
293
+ ambiguous?{starts:candidateStarts.map(a=>piBase+a),ends:candidateEnds.map(a=>piBase+a)}:undefined);
294
+ if(!literal && ambiguous)spans.at(-1)!.ambiguityReason=multiple?"multiple-alignments":"literal-marker-identity";
295
+ // A canonicalized Bearer prefix belongs to the same declared codec loss,
296
+ // with its own exact source range (not hidden in the redaction's hash).
297
+ const prior=pieces[i];
298
+ if(prior.endsWith("Bearer ")) {
299
+ for(const a of candidateStarts) {
300
+ const p=a-7;
301
+ if(text.slice(p,a)!=="Bearer ")record(piBase+p,piBase+a,museBase+positions[i]-7,"vendor-bearer-prefix",ambiguous?"ambiguous":"unique");
302
+ }
303
+ }
304
+ reachable=following;
305
+ if(i===count-1 && onPrefix) {
306
+ const cuts:number[]=[];
307
+ for(let cut=0;cut<=n;cut++)if(following[cut] && !(cut>0 && /[\uD800-\uDBFF]/.test(text[cut-1])))cuts.push(cut);
308
+ if(!cuts.length)throw invalid(piBase,museBase);
309
+ onPrefix({cuts,ellipsisIdentity:shortLast===undefined ? "not-present" : fullCut && shortCut ? "ambiguous" : shortCut ? "generated" : "ambiguous"});
310
+ }
141
311
  }
142
- return spans;
143
312
  }
144
- const piLines = pi.split("\n"), museLines = muse.split("\n");
145
- if (piLines.length !== museLines.length) throw invalid();
146
- const aligned: Span[] = []; let piBase = 0, museBase = 0;
147
- for (let i = 0; i < piLines.length; i++) {
148
- if (piLines[i] !== museLines[i]) for (const s of lineSpans(piLines[i], museLines[i]))
149
- aligned.push({ piStart: piBase + s.piStart, piEnd: piBase + s.piEnd, museStart: museBase + s.museStart });
150
- piBase += piLines[i].length + 1; museBase += museLines[i].length + 1;
313
+ const piLines=pi.split("\n"), museLines=muse.split("\n");
314
+ if(piLines.length!==museLines.length)throw invalid(0,0);
315
+ let piBase=0,museBase=0;
316
+ for(let i=0;i<piLines.length;i++) {
317
+ if(onPrefix || piLines[i]!==museLines[i])line(piLines[i],museLines[i],piBase,museBase);
318
+ piBase+=piLines[i].length+1;museBase+=museLines[i].length+1;
151
319
  }
152
- if (!aligned.length) throw invalid();
153
- const spans = aligned.map(s => ({
154
- piOffsetBytes: Buffer.byteLength(pi.slice(0, s.piStart)),
155
- museOffsetBytes: Buffer.byteLength(muse.slice(0, s.museStart)),
156
- piByteLen: Buffer.byteLength(pi.slice(s.piStart, s.piEnd)),
157
- sha256: createHash("sha256").update(pi.slice(s.piStart, s.piEnd)).digest("hex"),
158
- }));
159
- // Reconstruct only after proving every byte outside the declared holes. The
160
- // bridge's original journal hash remains exact; the separate ledger records
161
- // that the actual vendor receipt contained holes, never exact consumption.
320
+ if(!spans.length && !onPrefix)throw invalid(0,0);
162
321
  report?.(spans);
163
- return { content: [{type:"text",text:pi}], isError: observed.isError };
322
+ return {content:[{type:"text",text:pi}],isError:observed.isError};
164
323
  }
165
324
 
166
325
  export type OutputPage = { byteLen: number; content: string; encoding: string; eof: boolean; mediaType: string; offsetBytes: number };