pi-muse-tether 0.1.1 → 0.2.1

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.
@@ -27,13 +27,27 @@ function imageDeclarations(sent: BridgeResult): UnverifiableImage[] {
27
27
  export function assertToolResultVerifiable(sent: BridgeResult): void {
28
28
  imageDeclarations(sent);
29
29
  }
30
- export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string, onRedactions?: (spans: VendorRedaction[]) => void, onImages?: (images: UnverifiableImage[]) => void): BridgeResult {
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 {
31
39
  const images = imageDeclarations(sent);
32
40
  if (images.length && !onImages) throw new Error("Muse image receipt requires declared-unverifiable reporting");
33
41
  if (typeof item.visibleOutput !== "string") throw new Error("Muse tool result missing visibleOutput");
34
- 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");
35
49
  const output = stored ?? item.visibleOutput;
36
- if (stored !== undefined && (item.truncated ? !stored.startsWith(item.visibleOutput) : stored !== item.visibleOutput))
50
+ if (stored !== undefined && (item.truncated ? viewPrefixes(item.visibleOutput,stored).length === 0 : stored !== item.visibleOutput))
37
51
  throw new Error("Muse stored tool output differs from visibleOutput");
38
52
  let actual = output;
39
53
  if (sent.isError === true) {
@@ -48,11 +62,15 @@ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string
48
62
  // placeholder-shaped strings: literal tool text and leading LF remain bytes.
49
63
  let expected = "";
50
64
  const protectedImages: { start: number; end: number }[] = [];
65
+ const textSources: {partIndex:number; start:number; end:number}[] = [];
51
66
  for (const [index, part] of sent.content.entries()) {
52
67
  if (part.type === "text") {
53
68
  // Native string folding ignores leading empty chunks but preserves a
54
69
  // separator before an empty chunk after nonempty output (captured live).
55
- expected += (expected ? "\n" : "") + part.text;
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)});
56
74
  } else {
57
75
  // The official client's failed MCP path projects text only. Images were
58
76
  // delivered to MCP, NOT exposed to the model; declare that known loss.
@@ -69,17 +87,74 @@ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string
69
87
  if (sent.isError === true) {
70
88
  expected = sent.content.filter(part => part.type === "text").map(part => (part as {text:string}).text).join("\n");
71
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
+ }
72
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
+ }
73
144
  const projected: BridgeResult = { content: [{ type: "text", text: expected }], isError: sent.isError === true };
74
145
  let redactions: VendorRedaction[] = [];
75
146
  const observed = reconcileVendorRedactions(projected, { content: [{ type: "text", text: actual }], isError: sent.isError === true }, spans => { redactions = spans; });
76
- if ((observed.content[0] as { text: string }).text !== expected)
77
- throw new Error("Muse tool result text projection mismatch (image placeholder differs or text changed)");
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
+ }
78
152
  for (const span of redactions) {
79
153
  if (protectedImages.some(range => span.piOffsetBytes < Buffer.byteLength(expected.slice(0, range.end)) &&
80
154
  span.piOffsetBytes + span.piByteLen > Buffer.byteLength(expected.slice(0, range.start))))
81
155
  throw new Error("Muse image placeholder differs: redaction cannot hide image metadata");
82
156
  }
157
+ locateSources(redactions);
83
158
  if (redactions.length) onRedactions?.(redactions);
84
159
  if (images.length) onImages?.(images);
85
160
  // modelVisibleContent may contain image derivatives or metadata. It is useful
@@ -87,25 +162,37 @@ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string
87
162
  return sent;
88
163
  }
89
164
 
90
- /** Byte offsets address the constructed native Pi-parts projection and the
91
- * actual Muse receipt. Image metadata occupies protected positions in this
92
- * projection; no declared loss may cover those positions.
93
- * Never include removed text in metadata. This is declared vendor loss, NOT
94
- * proof that the model consumed the original bytes. */
95
- 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
+ };
96
176
  const marker = "[REDACTED]";
97
- 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 {
98
179
  const pi = (sent.content[0] as {text:string}).text;
99
180
  const muse = (observed.content[0] as {text:string}).text;
100
- if (pi === muse || !muse.includes(marker)) return observed;
101
- // DECLARED LOSSY TRANSPORT ACCEPTANCE, not verification of removed bytes.
102
- // The pinned binary exposes the marker and token prefixes, but not a complete
103
- // provable runtime pattern set. Conservative fallback: unique alignment,
104
- // nonempty single-line removed spans with unique positional alignment, including line edges.
105
- // Literal Pi markers must match literally and may never be swallowed by a gap.
106
- type Span = { piStart: number; piEnd: number; museStart: number };
107
- const invalid = () => new Error("Muse tool result mismatch: invalid or ambiguous vendor redaction");
108
- // 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.
109
196
  function starts(text: string, chunk: string): Uint8Array {
110
197
  const found = new Uint8Array(text.length + 1);
111
198
  if (!chunk.length) { found.fill(1); return found; }
@@ -122,99 +209,117 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
122
209
  }
123
210
  return found;
124
211
  }
125
- function lineSpans(text: string, visible: string, groupAdjacent = true): Span[] {
126
- // Adjacent vendor markers declare one combined loss region. Their internal
127
- // split is unknowable; the combined nonempty region still aligns uniquely.
128
- const pieces: string[] = [], widths: number[] = [];
212
+ function line(text: string, visible: string, piBase: number, museBase: number) {
213
+ const pieces: string[] = [], widths: number[] = [], positions: number[] = [];
129
214
  let cursor = 0, at: number;
130
215
  while ((at = visible.indexOf(marker, cursor)) !== -1) {
131
- pieces.push(visible.slice(cursor, at));
132
- cursor = at;
216
+ pieces.push(visible.slice(cursor, at)); positions.push(at); cursor = at;
133
217
  let width = 0;
134
- while (visible.startsWith(marker, cursor)) {
135
- width++; cursor += marker.length;
136
- if (!groupAdjacent) break;
137
- }
218
+ while (visible.startsWith(marker, cursor)) { width++; cursor += marker.length; }
138
219
  widths.push(width);
139
220
  }
140
221
  pieces.push(visible.slice(cursor));
141
- const n = text.length;
142
- if (pieces.length === 1 || !text.startsWith(pieces[0])) throw invalid();
143
- // Each backward layer counts complete parses after one marker. Range sums
144
- // make a variable-length hole O(1) per position: O(n * markerCount), not
145
- // quadratic suffix rescanning for a single gap. 2 means ambiguous, not a cap.
146
- const barrier = new Int32Array(n + 1); barrier[n] = n;
147
- for (let a = n - 1; a >= 0; a--)
148
- barrier[a] = text[a] === "\r" || text.startsWith(marker, a) ? a : barrier[a + 1];
149
- let next = new Uint8Array(n + 1); next[n] = 1;
150
- const choices: Int32Array[] = [];
151
- for (let i = pieces.length - 2; i >= 0; i--) {
152
- const chunk = pieces[i + 1], matches = starts(text, chunk);
153
- const sum = new Float64Array(n + 2), first = new Int32Array(n + 2); first.fill(-1);
154
- for (let a = n; a >= 0; a--) {
155
- const ways = matches[a] ? next[a + chunk.length] ?? 0 : 0;
156
- sum[a] = sum[a + 1] + ways;
157
- first[a] = ways ? a : first[a + 1];
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;
158
234
  }
159
- const current = new Uint8Array(n + 1), choice = new Int32Array(n + 1); choice.fill(-2);
160
- for (let a = 0; a <= n; a++) {
161
- if (text.startsWith(marker, a)) {
162
- const end = a + marker.length * widths[i];
163
- if (!text.startsWith(marker.repeat(widths[i]), a)) continue;
164
- current[a] = matches[end] ? next[end + chunk.length] ?? 0 : 0;
165
- if (current[a] === 1) choice[a] = -1; // literal marker, never a hole
166
- } else if (barrier[a] > a) {
167
- const minimumEnd = a + 1;
168
- if (minimumEnd > barrier[a]) continue;
169
- const ways = sum[minimumEnd] - sum[barrier[a] + 1];
170
- current[a] = Math.min(2, ways);
171
- if (ways === 1) choice[a] = first[minimumEnd];
172
- }
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;
173
257
  }
174
- choices[i] = choice; next = current;
175
- }
176
- let a = pieces[0].length, b = a;
177
- if (next[a] !== 1) throw invalid();
178
- const spans: Span[] = [];
179
- for (let i = 0; i < choices.length; i++) {
180
- const end = choices[i][a];
181
- if (end >= 0) spans.push({ piStart: a, piEnd: end, museStart: b });
182
- a = (end === -1 ? a + marker.length * widths[i] : end) + pieces[i + 1].length;
183
- b += marker.length * widths[i] + pieces[i + 1].length;
258
+ next=current;
184
259
  }
185
- return spans;
186
- }
187
- const piLines = pi.split("\n"), museLines = muse.split("\n");
188
- if (piLines.length !== museLines.length) throw invalid();
189
- const aligned: Span[] = []; let piBase = 0, museBase = 0;
190
- for (let i = 0; i < piLines.length; i++) {
191
- if (piLines[i] !== museLines[i]) {
192
- let spans: Span[];
193
- try { spans = lineSpans(piLines[i], museLines[i]); }
194
- catch (error) {
195
- // A contiguous visible marker run may mix exact literal Pi markers
196
- // with a redaction beside them. Retry individual tokens only when Pi
197
- // actually contains a literal; require the same unique alignment.
198
- if (!piLines[i].includes(marker)) throw error;
199
- spans = lineSpans(piLines[i], museLines[i], false);
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"});
200
310
  }
201
- for (const s of spans)
202
- aligned.push({ piStart: piBase + s.piStart, piEnd: piBase + s.piEnd, museStart: museBase + s.museStart });
203
311
  }
204
- piBase += piLines[i].length + 1; museBase += museLines[i].length + 1;
205
312
  }
206
- if (!aligned.length) throw invalid();
207
- const spans = aligned.map(s => ({
208
- piOffsetBytes: Buffer.byteLength(pi.slice(0, s.piStart)),
209
- museOffsetBytes: Buffer.byteLength(muse.slice(0, s.museStart)),
210
- piByteLen: Buffer.byteLength(pi.slice(s.piStart, s.piEnd)),
211
- sha256: createHash("sha256").update(pi.slice(s.piStart, s.piEnd)).digest("hex"),
212
- }));
213
- // Reconstruct only after proving every byte outside the declared holes. The
214
- // bridge's original journal hash remains exact; the separate ledger records
215
- // that the actual vendor receipt contained holes, never exact consumption.
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;
319
+ }
320
+ if(!spans.length && !onPrefix)throw invalid(0,0);
216
321
  report?.(spans);
217
- return { content: [{type:"text",text:pi}], isError: observed.isError };
322
+ return {content:[{type:"text",text:pi}],isError:observed.isError};
218
323
  }
219
324
 
220
325
  export type OutputPage = { byteLen: number; content: string; encoding: string; eof: boolean; mediaType: string; offsetBytes: number };