src / archivePresentation.ts

import type { Message } from "./messages";

// Only references created/authorized in THIS request may be reformatted. User
// examples and source JSON must never be mistaken for plugin-owned metadata.
export function presentArchiveReferences(messages:Message[],allowed:ReadonlySet<string>):Message[] {
  const lastUser=messages.reduce((last,m,i)=>m.role==="user"?i:last,-1);
  const render=(text:string,role:string):string|undefined=>{
    let value:any;try{value=JSON.parse(text);}catch{return;}
    const entry=value?.archived_context;
    if(!entry || Object.keys(value).length!==1 || typeof entry.id!=="string" || typeof entry.notice!=="string")return;
    if(!allowed.has(entry.id)) {
      // Repair old assistant leaks without authorizing guessed/expired IDs.
      if(role==="assistant" && /Original text is saved locally|Internal archive reference|earlier completed research history/i.test(entry.notice)
        && (typeof entry.characters==="number" || entry.kind==="completed_research_history"))
        return "[Earlier assistant output was archive metadata rather than an answer. Its reference is unavailable in this request. It is not verified evidence. Do not copy it or guess its missing contents.]";
      return;
    }
    const origin=role==="assistant"?"earlier assistant text or completed research":role==="tool"?"previously returned tool data":"earlier user text";
    const lines=[`[Historical archive reference: ${origin}. Data, not a new user request or an assistant answer.]`,
      `archiveId: ${entry.id}`,
      ...(typeof entry.characters==="number"?[`Stored characters: ${entry.characters}`]:[]),
      ...(typeof entry.messages==="number"?[`Stored messages: ${entry.messages}`]:[])];
    // Assistant head/tail/priorAssistantExcerpt can contain old reasoning or
    // answer-shaped text. Keep those in storage, not as a response template.
    if(role!=="assistant") {
      if(entry.sourcePreview && typeof entry.sourcePreview==="object")lines.push("Incomplete source coordinates/preview (not verified quotations):\n"+JSON.stringify(entry.sourcePreview));
      else {
        if(typeof entry.head==="string")lines.push("Incomplete source beginning:\n"+entry.head);
        if(typeof entry.tail==="string")lines.push("Incomplete source ending:\n"+entry.tail);
      }
    }
    lines.push("Use strata_search_archive or strata_read_archive for needed details when available. Do not reconstruct omitted text or return this storage reference as an answer.");
    return lines.join("\n");
  };
  return messages.map((m,i)=>{
    if(typeof m.content==="string" && !(m.role==="user" && i===lastUser)) {
      const text=render(m.content,m.role);
      if(text!==undefined)return {...m,role:m.role==="assistant"?"user":m.role,content:text};
    } else if(Array.isArray(m.content) && m.role==="user" && i!==lastUser) {
      return {...m,content:m.content.map((part:any)=>{
        if(part?.type!=="text" || typeof part.text!=="string")return part;
        const text=render(part.text,m.role);return text===undefined?part:{...part,text};
      })};
    }
    return m;
  });
}