/** Exact two-file code research owner. Disposable mechanism evidence only;
 * corpus, labels, admissions, final gates and publication remain trusted owners. */
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { createHash, randomUUID } from 'node:crypto';
import { createRequire } from 'node:module';
import { spawn, spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import type { EmailCardFixture, RenderedCard } from './triage-card-paired.ts';

export const CODE_TARGETS = ['lib/triage-core/brief-composer.js', 'lib/triage-core/card-claim-grounding.js'] as const;
// Actual read-only composer closure. SQL/provider entrypoints are not available
// in this evaluation carrier; a new dependency requires explicit owner review.
export const CODE_CLOSURE: readonly string[] = [
  ...CODE_TARGETS, 'lib/triage-core/account-obligation.js', 'lib/triage-core/account-obligation.ts',
  'lib/triage-core/source-fact-envelope.ts', 'lib/triage-core/producers/conversation-facts-producer.js',
  'lib/triage-core/canonical-domain-schema.js', 'lib/triage-core/producers/sql-helpers.js',
  'lib/triage-core/producers/canonical-history.js', 'lib/episode-source-authority.js',
  'lib/triage-core/desktop-authority.js', 'lib/desktop-db-path.js', 'lib/test-real-home-guard.js',
  'lib/triage-core/producers/addresses.js', 'lib/triage-core/producers/episode-producer.js',
  'lib/episode-source-revisions.js', 'lib/email-account-scope.js',
  'lib/triage-core/producers/temporal-expressions.js', 'lib/triage-core/producers/keyphrases.js',
  'lib/triage-core/producers/context-extractors.js', 'lib/triage-core/producers/context-extraction.js',
  'daemon/lib/grounded-reply-context.js',
];
type Target = typeof CODE_TARGETS[number];
export interface CodeWorkspace { root: string; token: string; base: string }
export interface CodeCandidate { schema: 'TriageCodeCandidate@1'; base: string; changes: { path: Target; beforeSha256: string; after: string }[] }
const hash = (bytes: string | Buffer) => createHash('sha256').update(bytes).digest('hex');
const digest = (value: unknown) => hash(JSON.stringify(value));
const worker = fileURLToPath(new URL('./triage-card-code-worker.cjs', import.meta.url));
const HEX = /^[a-f0-9]{64}$/;
// A function declaration, not a const arrow: TypeScript only treats a call as
// an assertion (narrowing what follows, e.g. `if(!reader)fail(...)`) when the
// callee's `never` return type is explicitly declared on the entity itself.
function fail(code: string): never { throw Error('TRIAGE_CODE_' + code); }
function exact(value: unknown, keys: string[]) {
  return value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).sort().join() === keys.sort().join();
}
function git(root: string, args: string[], env = process.env) {
  const r = spawnSync('git', args, { cwd: root, env, encoding: 'utf8', timeout: 15000, maxBuffer: 4 * 1024 * 1024 });
  if (r.error || r.status !== 0) fail('GIT_FAILED'); return r.stdout.trim();
}
function read(file: string, privateFile = false) {
  const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
  try {
    const s = fs.fstatSync(fd);
    if (!s.isFile() || s.nlink !== 1 || s.size > 4 * 1024 * 1024 || (privateFile && (s.uid !== process.getuid?.() || (s.mode & 0o077)))) fail('FILE_UNSAFE');
    const bytes = fs.readFileSync(fd), after = fs.lstatSync(file);
    if (s.ino !== after.ino || s.dev !== after.dev || s.size !== bytes.length || s.mtimeMs !== after.mtimeMs) fail('FILE_CHANGED');
    return bytes;
  } finally { fs.closeSync(fd); }
}
function writePrivate(file: string, value: unknown) {
  const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
  try { fs.writeFileSync(fd, JSON.stringify(value)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
}
function executableHash(file:string) {
  const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
  try{const before=fs.fstatSync(fd);if(!before.isFile()||before.size>256*1024*1024)fail('EXECUTABLE_UNSAFE');
    const h=createHash('sha256'),chunk=Buffer.alloc(64*1024);let count=0,n;
    while((n=fs.readSync(fd,chunk,0,chunk.length,null))>0){h.update(chunk.subarray(0,n));count+=n;}
    const after=fs.lstatSync(file);if(before.dev!==after.dev||before.ino!==after.ino||before.mtimeMs!==after.mtimeMs||count!==before.size)fail('EXECUTABLE_CHANGED');return h.digest('hex');
  }finally{fs.closeSync(fd);}
}
function supervisedPid(file:string,pgid:number) {
  const p=JSON.parse(read(file,true).toString());
  if(!exact(p,['schema','pid','pgid'])||p.schema!=='TriageCodeSupervisor@1'||!Number.isSafeInteger(p.pid)||p.pid<2||p.pgid!==pgid)fail('SUPERVISOR_INVALID');
  return p.pid as number;
}
function owned(w: CodeWorkspace, base = true) {
  if (!/^[a-f0-9]{40}$/.test(w.base) || fs.realpathSync(w.root) !== w.root || !fs.lstatSync(path.join(w.root, '.git')).isDirectory()) fail('OWNER_INVALID');
  const record = JSON.parse(read(path.join(w.root, '.git/triage-owner.json'), true).toString());
  if (record.schema !== 'TriageCandidateWorkspace@1' || record.token !== w.token || record.base !== w.base || typeof record.source !== 'string') fail('OWNER_CHANGED');
  if (base && git(w.root, ['rev-parse', 'HEAD']) !== w.base) fail('HEAD_CHANGED');
  return record;
}
function targetFile(w: CodeWorkspace, p: string) {
  if (!CODE_TARGETS.includes(p as Target)) fail('PATH_INVALID');
  const file = path.join(w.root, p); if (fs.realpathSync(file) !== file) fail('PATH_UNSAFE'); return file;
}
export function validateCodeCandidate(value: unknown, w: CodeWorkspace): CodeCandidate {
  owned(w); const p = value as CodeCandidate;
  if (!exact(p, ['schema', 'base', 'changes']) || p.schema !== 'TriageCodeCandidate@1' || p.base !== w.base || !Array.isArray(p.changes) || p.changes.length < 1 || p.changes.length > 2) fail('PROPOSAL_INVALID');
  const seen = new Set();
  const changes = p.changes.map(c => {
    if (!exact(c, ['path', 'beforeSha256', 'after']) || seen.has(c.path) || !HEX.test(c.beforeSha256) || typeof c.after !== 'string' || c.after.includes('\0') || Buffer.byteLength(c.after) > 256 * 1024 || !c.after.trim()) fail('PROPOSAL_INVALID');
    seen.add(c.path); const before = read(targetFile(w, c.path)).toString();
    if (hash(before) !== c.beforeSha256 || before === c.after || git(w.root, ['diff', 'HEAD', '--', c.path])) fail('PREIMAGE_CHANGED');
    return { path: c.path, beforeSha256: c.beforeSha256, after: c.after };
  }).sort((a,b) => a.path < b.path ? -1 : 1);
  return { schema: p.schema, base: p.base, changes };
}
export function codeCandidateDigest(w: CodeWorkspace, candidate?: CodeCandidate) {
  owned(w); return digest({ base: w.base, targets: CODE_TARGETS.map(p => ({ path:p, hash:hash(read(targetFile(w,p))) })), candidate: candidate ?? null });
}
function admittedTargets(w:CodeWorkspace) {
  const file=path.join(w.root,'.git/triage-code-pending.json'),r=fs.existsSync(file)?pending(w):null;
  for(const p of CODE_TARGETS){const c=r?.changes.find(c=>c.path===p),actual=read(targetFile(w,p));
    const base=spawnSync('git',['show',w.base+':'+p],{cwd:w.root,maxBuffer:4*1024*1024});
    if(base.status!==0||(!c&&hash(actual)!==hash(base.stdout))||(c&&(c.before!==base.stdout.toString()||actual.toString()!==c.after)))fail('CANDIDATE_NOT_ADMITTED');
  }
}
export function prepareCodeCandidate(w: CodeWorkspace, value: unknown) {
  const proposal = validateCodeCandidate(value,w), file = path.join(w.root,'.git/triage-code-pending.json');
  const changes = proposal.changes.map(c => ({ ...c, before:read(targetFile(w,c.path)).toString() }));
  writePrivate(file,{ schema:'TriageCodeEdit@1',token:w.token,base:w.base,changes });
  for(const c of changes) fs.writeFileSync(targetFile(w,c.path),c.after);
  return { digest:codeCandidateDigest(w),changes:changes.map(c=>({path:c.path,before:c.beforeSha256,after:hash(c.after)})) };
}
function pending(w:CodeWorkspace) {
  const r=JSON.parse(read(path.join(w.root,'.git/triage-code-pending.json'),true).toString());
  if(r.schema!=='TriageCodeEdit@1'||r.token!==w.token||r.base!==w.base||!Array.isArray(r.changes)||r.changes.length<1||r.changes.length>2||new Set(r.changes.map((c:{path:string})=>c.path)).size!==r.changes.length)fail('PENDING_CHANGED');
  for(const c of r.changes){targetFile(w,c.path);if(hash(c.before)!==c.beforeSha256||typeof c.after!=='string')fail('PENDING_CHANGED');}
  return r as {changes:{path:Target;before:string;after:string;beforeSha256:string}[]};
}
export function settleCodeCandidate(w:CodeWorkspace, disposition:'keep'|'discard', message:string) {
  owned(w);const r=pending(w), paths=r.changes.map(c=>c.path);
  for(const c of r.changes){const bytes=read(targetFile(w,c.path)).toString();if(bytes!==c.after&&!(disposition==='discard'&&bytes===c.before))fail('FOREIGN_EDIT');}
  if(disposition==='discard'){for(const c of r.changes)fs.writeFileSync(targetFile(w,c.path),c.before);fs.unlinkSync(path.join(w.root,'.git/triage-code-pending.json'));return {disposition,commit:null};}
  if(disposition!=='keep'||!message.trim()||message.length>2000)fail('DISPOSITION_INVALID');
  const index=path.join(w.root,'.git/triage-code-index-'+randomUUID()),env={...process.env,GIT_INDEX_FILE:index};
  try{
    git(w.root,['read-tree',w.base],env);git(w.root,['add','--',...paths],env);const tree=git(w.root,['write-tree'],env);
    const intent={token:w.token,base:w.base,tree,message,targets:r.changes.map(c=>({path:c.path,after:hash(c.after)}))};
    writePrivate(path.join(w.root,'.git/triage-code-intent.json'),intent);owned(w);
    for(const c of r.changes)if(read(targetFile(w,c.path)).toString()!==c.after)fail('FOREIGN_EDIT');
    git(w.root,['commit','-m',message,'--',...paths],env);
    if(git(w.root,['rev-parse','HEAD^'])!==w.base||git(w.root,['rev-parse','HEAD^{tree}'])!==tree)fail('COMMIT_CHANGED');
    fs.unlinkSync(path.join(w.root,'.git/triage-code-pending.json'));return {disposition,commit:git(w.root,['rev-parse','HEAD'])};
  }finally{if(fs.existsSync(index))fs.unlinkSync(index);}
}
export function recoverCodeCandidate(w:CodeWorkspace) {
  owned(w,false);if(git(w.root,['rev-parse','HEAD'])===w.base)return settleCodeCandidate(w,'discard','');
  const r=pending(w),i=JSON.parse(read(path.join(w.root,'.git/triage-code-intent.json'),true).toString());
  if(i.token!==w.token||i.base!==w.base||git(w.root,['rev-parse','HEAD^'])!==w.base||git(w.root,['rev-parse','HEAD^{tree}'])!==i.tree||git(w.root,['show','-s','--format=%B','HEAD'])!==i.message.trim()||digest(i.targets)!==digest(r.changes.map(c=>({path:c.path,after:hash(c.after)}))))fail('RECOVERY_CONFLICT');
  for(const c of r.changes)if(read(targetFile(w,c.path)).toString()!==c.after)fail('FOREIGN_EDIT');
  const result={disposition:'retained_commit_unverified',commit:git(w.root,['rev-parse','HEAD'])};writePrivate(path.join(w.root,'.git/triage-code-recovery.json'),result);fs.unlinkSync(path.join(w.root,'.git/triage-code-pending.json'));return result;
}

export interface CodeRenderOptions {
  parameters:{temperature:number;numPredict:number};model:{name:string;digest:string;url:string};
  assertCurrent:()=>void;beforeGenerate:()=>void|Promise<void>;
  /** Trusted test-only provider seam. Public orchestration must never expose it. */
  broker?:(request:Record<string,unknown>)=>Promise<{model:string;response:string}>;
  fastPath?:boolean;limits?:{wallMs?:number;rssMiB?:number;outputBytes?:number};
}
function limits(o:CodeRenderOptions) {
  const value={wallMs:45000,rssMiB:256,outputBytes:256*1024,...o.limits};
  if(!Number.isSafeInteger(value.wallMs)||value.wallMs<100||value.wallMs>45000||!Number.isSafeInteger(value.rssMiB)||value.rssMiB<64||value.rssMiB>256||!Number.isSafeInteger(value.outputBytes)||value.outputBytes<1024||value.outputBytes>256*1024)fail('RESOURCE_BUDGET');return value;
}
function binding(o:CodeRenderOptions) {
  const p=o.parameters,u=new URL(o.model.url);
  if(!HEX.test(o.model.digest)||!o.model.name||o.model.name.length>128||u.protocol!=='http:'||!['127.0.0.1','localhost','[::1]'].includes(u.hostname)||u.pathname!=='/'||u.search||u.hash||u.username||u.password||!Number.isFinite(p.temperature)||p.temperature<0||p.temperature>1||!Number.isSafeInteger(p.numPredict)||p.numPredict<128||p.numPredict>1024)fail('MODEL_BINDING');
}
function supported() {
  // Only the actually probed OS/runtime is supported. A different platform is
  // an explicit refusal, never an unsandboxed fallback.
  if(process.platform!=='darwin'||process.arch!=='arm64'||process.versions.node!=='22.22.3'||!fs.existsSync('/usr/bin/sandbox-exec'))fail('ISOLATION_UNSUPPORTED');
}
function copyClosure(w:CodeWorkspace,root:string) {
  const manifest:Record<string,string>={};
  for(const p of CODE_CLOSURE){
    const file=path.join(w.root,p);if(fs.realpathSync(file)!==file)fail('DEPENDENCY_UNSAFE');
    const bytes=read(file);if(!CODE_TARGETS.includes(p as Target)&&hash(bytes)!==hash(spawnSync('git',['show',w.base+':'+p],{cwd:w.root,maxBuffer:4*1024*1024}).stdout))fail('DEPENDENCY_CHANGED');
    const dest=path.join(root,p);fs.mkdirSync(path.dirname(dest),{recursive:true,mode:0o700});fs.writeFileSync(dest,bytes,{mode:0o600});manifest[p]=hash(bytes);
  }
  // Dependencies belong to the trusted installed evaluator, never the clone's
  // package/config or an ambient NODE_PATH supplied by a candidate.
  const req=createRequire(import.meta.url),entry=req.resolve('jiti');
  let pkg=path.dirname(entry);while(!fs.existsSync(path.join(pkg,'package.json'))){const parent=path.dirname(pkg);if(parent===pkg)fail('JITI_UNAVAILABLE');pkg=parent;}
  for(const p of ['package.json','lib/jiti.cjs','dist/jiti.cjs','dist/babel.cjs']){
    const bytes=read(path.join(pkg,p)),dest=path.join(root,'node_modules/jiti',p);fs.mkdirSync(path.dirname(dest),{recursive:true,mode:0o700});fs.writeFileSync(dest,bytes,{mode:0o600});manifest['node_modules/jiti/'+p]=hash(bytes);
  }
  fs.writeFileSync(path.join(root,'worker.cjs'),read(worker),{mode:0o600});manifest['worker.cjs']=hash(read(worker));return manifest;
}
function profile(root:string,node:string,input:string,output:string) {
  const ancestors=new Set<string>();for(const file of [node,root,input,output]){let p=path.dirname(file);for(;;){ancestors.add(p);if(path.dirname(p)===p)break;p=path.dirname(p);}}
  const literal=(s:string)=>'(literal '+JSON.stringify(s)+')';
  return ['(version 1)','(deny default)','(deny network*)','(deny process-fork)',`(allow process-exec ${literal(node)})`,
    '(allow sysctl-read)','(allow process-info* (target self))','(allow file-read* (literal "/"))',
    '(allow file-read-metadata '+[...ancestors].map(literal).join(' ')+')',
    `(allow file-read* (subpath "/System") (subpath "/usr/lib") (literal "/dev/null") (literal "/dev/urandom") ${literal(node)} (subpath ${JSON.stringify(root)}))`,
    `(allow file-write-data ${literal(output)})`].join('\n');
}
async function execute(w:CodeWorkspace,o:CodeRenderOptions,input:unknown) {
  supported();owned(w);admittedTargets(w);binding(o);o.assertCurrent();const budget=limits(o),before=codeCandidateDigest(w);
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'triage-code-jail-')));fs.chmodSync(root,0o700);
  const canaryRoot=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'triage-code-canary-')));fs.chmodSync(canaryRoot,0o700);
  const canary=path.join(canaryRoot,'private.synthetic');fs.writeFileSync(canary,randomUUID(),{mode:0o600});const canaryHash=hash(read(canary,true));
  const active=new AbortController();let stop:()=>void=()=>{};
  try{
    const manifest=copyClosure(w,root),node=fs.realpathSync(process.execPath),nodeHash=executableHash(node),source=path.join(root,'input.json'),output=path.join(root,'result.json'),policy=path.join(root,'profile.sb'),custody=path.join(root,'custody.json');
    const bytes=JSON.stringify({...input as Record<string,unknown>,isolationCanary:canary});if(Buffer.byteLength(bytes)>1024*1024)fail('INPUT_LIMIT');
    fs.writeFileSync(source,bytes,{mode:0o600});fs.writeFileSync(output,'',{mode:0o600});writePrivate(custody,{});fs.writeFileSync(policy,profile(root,node,source,output),{mode:0o600});
    let observedGenerations=0;
    const result=await new Promise<unknown>((resolve,reject)=>{
      // Kernel RLIMIT_FSIZE is set by a fixed trusted launcher before the jail;
      // untrusted code cannot spawn or broaden any permitted filesystem path.
      const child=spawn(node,[path.join(root,'worker.cjs'),'--supervise',policy,source,output,custody],{
        cwd:root,env:{HOME:root,LANG:'C',TZ:'UTC',JITI_FS_CACHE:'0',JITI_MODULE_CACHE:'0'},detached:true,stdio:['pipe','pipe','pipe','pipe','pipe'],
      });
      let failure:string|null=null,total=0,wire='',calls=0,lastId=0,busy=false,trustedFailure:unknown,jailPid=0;
      const kill=(reason:string)=>{failure??=reason;active.abort();try{process.kill(-child.pid!,'SIGKILL');}catch{child.kill('SIGKILL');}};stop=()=>kill('CLEANUP');
      const timer=setTimeout(()=>kill('TIMEOUT'),budget.wallMs);
      const sample=setInterval(()=>{
        if(!jailPid){try{jailPid=supervisedPid(custody,child.pid!);}catch{return;}}const r=spawnSync('/bin/ps',['-o','rss=','-p',String(jailPid)],{encoding:'utf8',timeout:1000});
        const rss=Number(r.stdout.trim());if(r.status===0&&Number.isFinite(rss)&&rss>budget.rssMiB*1024)kill('RSS_LIMIT');
      },50);
      const take=(chunk:Buffer)=>{total+=chunk.length;if(total>budget.outputBytes)kill('OUTPUT_LIMIT');};
      child.stdout.on('data',take);child.stderr.on('data',take);
      child.stdin.on('error',()=>{});
      // This pipe has no application writes. Only its lifetime is admitted;
      // keep it open while this trusted parent owns the isolated child.
      (child.stdio[4] as NodeJS.WritableStream).on('error',()=>kill('LIFELINE_FAILED'));
      (child.stdio[4] as NodeJS.ReadableStream).on('data',()=>kill('LIFELINE_FAILED'));
      (child.stdio[3] as NodeJS.ReadableStream).on('data',(chunk:Buffer)=>{
        take(chunk);if(failure)return;wire+=chunk.toString();if(Buffer.byteLength(wire)>budget.outputBytes){kill('OUTPUT_LIMIT');return;}
        const index=wire.indexOf('\n');if(index<0)return;const line=wire.slice(0,index);wire=wire.slice(index+1);
        let row: {kind:string;id:number;url:string;request:Record<string,unknown>};
        try{row=JSON.parse(line);}catch{kill('PROTOCOL_INVALID');return;}
        if(busy||wire||!exact(row,['kind','id','url','request'])||row.kind!=='generate'||row.url!==new URL('/api/generate',o.model.url).href||row.id!==lastId+1||++calls>2||!exact(row.request,['model','prompt','stream','format','think','keep_alive','options'])||row.request.model!==o.model.name||typeof row.request.prompt!=='string'||Buffer.byteLength(row.request.prompt)>128*1024||row.request.stream!==false||row.request.format!=='json'||row.request.think!==false||row.request.keep_alive!=='10m'||!exact(row.request.options,['temperature','num_predict','num_ctx'])||digest(row.request.options)!==digest({temperature:o.parameters.temperature,num_predict:o.parameters.numPredict,num_ctx:40960})){kill('BROKER_REFUSED');return;}
        busy=true;lastId=row.id;
        void (async()=>{
          try{
            o.assertCurrent();await o.beforeGenerate();o.assertCurrent();
            const payload=o.broker?await o.broker(row.request):await generate(o,row.request,active.signal);
            if(payload.model!==o.model.name||typeof payload.response!=='string'||Buffer.byteLength(JSON.stringify(payload))>budget.outputBytes)fail('MODEL_OUTPUT_UNQUALIFIED');
            o.assertCurrent();observedGenerations++;if(!failure)child.stdin.write(JSON.stringify({id:row.id,payload:{model:payload.model,response:payload.response}})+'\n');
          }catch(error){trustedFailure=error;kill('BROKER_FAILED');}finally{busy=false;}
        })();
      });
      child.on('error',()=>kill('ISOLATION_UNAVAILABLE'));
      child.on('close',(code,signal)=>{
        clearTimeout(timer);clearInterval(sample);active.abort();
        if(wire||busy)failure??='PROTOCOL_INVALID';
        try{jailPid=supervisedPid(custody,child.pid!);}catch{failure??='SUPERVISOR_INVALID';}
        if(failure||!jailPid||code!==0||signal){reject(Object.assign(Error('TRIAGE_CODE_'+(failure||'EXECUTION_FAILED'),{cause:trustedFailure}),{childPid:jailPid||child.pid,termination:{code,signal}}));return;}
        try{const bytes=read(output,true);if(bytes.length>budget.outputBytes)fail('OUTPUT_LIMIT');const value=JSON.parse(bytes.toString());if(!exact(value,['schema','result'])||value.schema!=='TriageCodeWorkerResult@1')fail('RESULT_INVALID');resolve(value.result);}catch(e){reject(e);}
      });
    });
    o.assertCurrent();admittedTargets(w);if(before!==codeCandidateDigest(w)||nodeHash!==executableHash(node))fail('SOURCE_CHANGED');
    for(const [p,h]of Object.entries(manifest))if(hash(read(path.join(root,p)))!==h)fail('ISOLATED_SOURCE_CHANGED');
    if(read(source).toString()!==bytes||hash(read(canary,true))!==canaryHash)fail('ISOLATED_INPUT_CHANGED');
    return {result,evidence:{schema:'TriageCodeExecution@1',candidate:before,closure:digest(manifest),worker:manifest['worker.cjs'],node:nodeHash,policy:hash(read(policy)),platform:process.platform,arch:process.arch,nodeVersion:process.versions.node,budget,observedGenerations}};
  }finally{active.abort();stop();fs.rmSync(root,{recursive:true,force:true});fs.rmSync(canaryRoot,{recursive:true,force:true});}
}
async function tags(o:CodeRenderOptions,signal:AbortSignal) {
  const r=await fetch(new URL('/api/tags',o.model.url),{signal,redirect:'error'});if(!r.ok)fail('MODEL_UNAVAILABLE');const p=await boundedJson(r);
  const rows=p.models?.filter((m:{name:string;digest:string})=>m.name===o.model.name);if(rows?.length!==1||rows[0].digest!==o.model.digest)fail('MODEL_CHANGED');
}
async function generate(o:CodeRenderOptions,request:Record<string,unknown>,signal:AbortSignal) {
  await tags(o,signal);o.assertCurrent();const r=await fetch(new URL('/api/generate',o.model.url),{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(request),signal,redirect:'error'});
  if(!r.ok)fail('MODEL_UNAVAILABLE');
  const payload=await boundedJson(r);await tags(o,signal);o.assertCurrent();return payload;
}
async function boundedJson(r:Response) {
  const reader=r.body?.getReader();if(!reader)fail('MODEL_UNAVAILABLE');let bytes=0;const chunks:Uint8Array[]=[];
  for(;;){const part=await reader.read();if(part.done)break;bytes+=part.value.length;if(bytes>256*1024){await reader.cancel();fail('MODEL_OUTPUT_LIMIT');}chunks.push(part.value);}
  return JSON.parse(Buffer.concat(chunks).toString());
}
export function createCodeRenderer(w:CodeWorkspace,o:CodeRenderOptions) {
  binding(o);return async(row:EmailCardFixture):Promise<RenderedCard>=>{
    // Explicit projection, never spread a corpus row or its labels into the jail.
    const facts={subject:row.subject,senderAddress:row.sender_email,senderName:row.sender_name,bodyExcerpt:row.text,sourceBody:row.text};
    const {result,evidence}=await execute(w,o,{mode:'render',facts,options:{...o.parameters,numCtx:40960,model:o.model.name,url:o.model.url.replace(/\/$/,''),timeoutMs:45000,fastPath:o.fastPath===true}});
    if(!result||typeof result!=='object'||typeof (result as RenderedCard).bluf!=='string')fail('RESULT_INVALID');
    const card=result as RenderedCard & {composer?:string;reason?:string};
    if(!o.fastPath&&((evidence.observedGenerations===0&&!(card.composer==='degraded'&&card.reason==='no_observed_facts'))||(evidence.observedGenerations>0&&card.composer!=='local-model:'+o.model.name)))fail('MODEL_OUTPUT_UNQUALIFIED');
    return card;
  };
}
export async function runCodeSmokeChecks(w:CodeWorkspace) {
  const {result,evidence}=await execute(w,{parameters:{temperature:0.2,numPredict:400},model:{name:'checks-only',digest:'0'.repeat(64),url:'http://127.0.0.1:11434'},assertCurrent(){},beforeGenerate(){fail('CHECK_NETWORK_REFUSED');}}, {mode:'checks'});
  const r=result as {amount:{state?:string};negation:{state?:string};sparse:{composer?:string}};
  if(!r||r.amount?.state!=='rejected'||r.negation?.state!=='rejected'||r.sparse?.composer!=='degraded')fail('FROZEN_CHECK_FAILED');
  return {identity:evidence,resultDigest:digest(result),checks:3};
}

const RPC_NAMES:Record<string,string[]>={
 composer:['briefInputContract','resolveBriefModelIdentity','emailOnlyCard','attachRelatedSourceContext','composeCardBrief','degradedBrief','exactFactBrief','extractAnchors','ensureConcreteNextStep','isSubjectEcho','assembleBlufBrief','stripConversationalFiller'],
 grounding:['GROUNDING_VERSION','groundCardClaims','buildSourceFactPrompt','exactSourceFact','cardRecomposeReason','briefTransientFailure','sourceAskText','parseAmounts','resolveDates','statedObligations','requestsToYou','sourceStatementBullets','replyWaived'],
 conversation:['extractCommitments','extractQuestions'],
};
/** Trusted frozen-test adapter only. The original assertions execute outside
 * the jail; every target function executes inside it. No candidate import in
 * this process. Synthetic HTTP server authority comes from the test call. */
export function createCodeTestBridge(w:CodeWorkspace) {
  supported();owned(w);admittedTargets(w);const basis=codeCandidateDigest(w);
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'triage-code-rpc-')));fs.chmodSync(root,0o700);
  const canaryRoot=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'triage-code-canary-')));fs.chmodSync(canaryRoot,0o700);
  const canary=path.join(canaryRoot,'private.synthetic');fs.writeFileSync(canary,'synthetic private isolation sentinel',{mode:0o600});
  const manifest=copyClosure(w,root),source=path.join(root,'input.json'),request=path.join(root,'request.json'),result=path.join(root,'result.json'),policy=path.join(root,'profile.sb'),custody=path.join(root,'custody.json'),node=fs.realpathSync(process.execPath);
  writePrivate(source,{mode:'adapter',isolationCanary:canary,requestFile:request});writePrivate(request,{id:-1});writePrivate(custody,{});fs.writeFileSync(result,'',{mode:0o600});fs.writeFileSync(policy,profile(root,node,source,result),{mode:0o600});
  const child=spawn(node,[path.join(root,'worker.cjs'),'--supervise',policy,source,result,custody],{cwd:root,env:{HOME:root,LANG:'C',TZ:'UTC',JITI_FS_CACHE:'0',JITI_MODULE_CACHE:'0'},detached:true,stdio:['pipe','pipe','pipe','pipe','pipe']});
  let failure:string|null=null,closed=false,id=0,outputBytes=0,wire='',generations=0;
  let lastSample=Date.now();
  let context:{options:Record<string,unknown>;controller:AbortController}|null=null;
  const aborts=new Map<number,AbortController>();
  const kill=(reason:string)=>{failure??=reason;for(const c of aborts.values())c.abort();try{process.kill(-child.pid!,'SIGKILL');}catch{child.kill('SIGKILL');}};
  (child.stdio[4] as NodeJS.WritableStream).on('error',()=>kill('LIFELINE_FAILED'));
  (child.stdio[4] as NodeJS.ReadableStream).on('data',()=>kill('LIFELINE_FAILED'));
  const take=(b:Buffer)=>{outputBytes+=b.length;if(outputBytes>256*1024)kill('OUTPUT_LIMIT');};
  child.stdout.on('data',take);child.stderr.on('data',take);child.stdin.on('error',()=>{});child.on('error',()=>kill('ISOLATION_UNAVAILABLE'));child.on('close',()=>{closed=true;});
  const check=()=>{
    if(failure||closed)fail(failure??'RPC_CLOSED');
    const r=spawnSync('/bin/ps',['-o','rss=','-p',String(supervisedPid(custody,child.pid!))],{encoding:'utf8',timeout:1000});if(r.status!==0){kill('RPC_CLOSED');fail('RPC_CLOSED');}
    if(Number(r.stdout.trim())>256*1024){kill('RSS_LIMIT');fail('RSS_LIMIT');}
  };
  (child.stdio[3] as NodeJS.ReadableStream).on('data',(chunk:Buffer)=>{
    take(chunk);wire+=chunk.toString();if(wire.length>256*1024){kill('OUTPUT_LIMIT');return;}
    for(;;){const end=wire.indexOf('\n');if(end<0)break;const line=wire.slice(0,end);wire=wire.slice(end+1);
      let row:{kind:string;id:number;url:string;request:Record<string,unknown>};try{row=JSON.parse(line);}catch{kill('PROTOCOL_INVALID');return;}
      if(row.kind==='cancel'&&exact(row,['kind','id'])){aborts.get(row.id)?.abort();continue;}
      const opts=context?.options,p=opts?.temperature??0.2,n=opts?.numPredict??400,ctx=opts?.numCtx??12288;
      let url:URL;try{url=new URL(String(opts?.url));}catch{kill('BROKER_REFUSED');return;}
      if(!context||!exact(row,['kind','id','url','request'])||row.kind!=='generate'||++generations>2||url.protocol!=='http:'||url.hostname!=='127.0.0.1'||url.pathname!=='/'||!url.port||url.username||url.password||row.url!==new URL('/api/generate',url).href||!exact(row.request,['model','prompt','stream','format','think','keep_alive','options'])||row.request.model!==(opts!.model??'qwen3:8b')||typeof row.request.prompt!=='string'||Buffer.byteLength(row.request.prompt)>128*1024||row.request.stream!==false||row.request.format!=='json'||row.request.think!==false||row.request.keep_alive!=='10m'||digest(row.request.options)!==digest({temperature:p,num_predict:n,num_ctx:ctx})){kill('BROKER_REFUSED');return;}
      const controller=new AbortController();aborts.set(row.id,controller);
      void(async()=>{try{
        const response=await fetch(row.url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(row.request),signal:controller.signal,redirect:'error'});const payload=await boundedJson(response);
        if(!closed&&!failure)child.stdin.write(JSON.stringify({id:row.id,status:response.status,payload})+'\n');
      }catch{if(!controller.signal.aborted&&!closed&&!failure)child.stdin.write(JSON.stringify({id:row.id,error:'FIXTURE_HTTP_FAILED'})+'\n');}finally{aborts.delete(row.id);}})();
    }
  });
  const readResult=(wanted:number)=>{try{const r=JSON.parse(read(result,true).toString());return r.id===wanted?r:null;}catch{return null;}};
  const waitSync=(wanted:number,budget=10000)=>{
    const start=Date.now();let sampled=start;
    for(;;){const r=readResult(wanted);if(r){if(!r.ok)fail('RPC_CALL_FAILED');return r.value;}
      const now=Date.now();if(now-start>budget){kill('TIMEOUT');fail('TIMEOUT');}if(now-sampled>100){check();sampled=now;}Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,0.2);
    }
  };
  try{waitSync(0);}catch(e){kill('INITIALIZATION_FAILED');fs.rmSync(root,{recursive:true,force:true});fs.rmSync(canaryRoot,{recursive:true,force:true});throw e;}
  const invoke=(module:string,name:string,args:unknown[])=>{
    if(!RPC_NAMES[module]?.includes(name)||context)fail('RPC_REFUSED');
    const call={id:++id,module,name,args};const bytes=JSON.stringify(call);if(Buffer.byteLength(bytes)>1024*1024)fail('INPUT_LIMIT');fs.writeFileSync(request,bytes);return id;
  };
  const callSync=(module:string,name:string,args:unknown[])=>waitSync(invoke(module,name,args));
  const callAsync=async(module:string,name:string,args:unknown[])=>{
    const wanted=invoke(module,name,args),options=(args[1]??{})as Record<string,unknown>;context={options,controller:new AbortController()};generations=0;
    const start=Date.now();try{for(;;){const r=readResult(wanted);if(r){if(!r.ok)fail('RPC_CALL_FAILED');return r.value;}const now=Date.now();if(now-start>45000){kill('TIMEOUT');fail('TIMEOUT');}if(now-lastSample>=50){check();lastSample=now;}await new Promise(resolve=>setTimeout(resolve,1));}}
    finally{for(const c of aborts.values())c.abort();context=null;}
  };
  const modules=Object.fromEntries(Object.entries(RPC_NAMES).map(([name,keys])=>[name,Object.fromEntries(keys.map(key=>[key,key==='GROUNDING_VERSION'?callSync(name,key,[]):(...args:unknown[])=>key==='composeCardBrief'?callAsync(name,key,args):callSync(name,key,args)]))]));
  const close=()=>{
    if(closed)return;kill('CLOSED');closed=true;
    if(codeCandidateDigest(w)!==basis)fail('SOURCE_CHANGED');for(const[p,h]of Object.entries(manifest))if(hash(read(path.join(root,p)))!==h)fail('ISOLATED_SOURCE_CHANGED');
    fs.rmSync(root,{recursive:true,force:true});fs.rmSync(canaryRoot,{recursive:true,force:true});
  };
  return {modules,close,identity:{candidate:basis,closure:digest(manifest),worker:manifest['worker.cjs'],instrument:'unchanged-frozen-assertions-via-jailed-RPC'}};
}

/** No candidate configuration/plugin is executed by static admission. */
export function checkCodeDependencies(w:CodeWorkspace) {
  owned(w);admittedTargets(w);const req=createRequire(import.meta.url),ts:typeof import('typescript')=req('typescript');const imports:{path:string;specifier:string}[]=[];
  for(const p of CODE_TARGETS){const bytes=read(targetFile(w,p)).toString(),ast=ts.createSourceFile(p,bytes,ts.ScriptTarget.Latest,true,ts.ScriptKind.JS);
    const parsed=ts.transpileModule(bytes,{fileName:p,reportDiagnostics:true,compilerOptions:{allowJs:true,target:ts.ScriptTarget.ES2022}});
    if(parsed.diagnostics?.some(d=>d.category===ts.DiagnosticCategory.Error))fail('SYNTAX_INVALID');
    const visit=(n:import('typescript').Node)=>{
      if(ts.isCallExpression(n)&&ts.isIdentifier(n.expression)&&n.expression.text==='require'){
        const arg=n.arguments[0];if(n.arguments.length!==1||!ts.isStringLiteral(arg))fail('DYNAMIC_DEPENDENCY_REFUSED');const s=(arg as import('typescript').StringLiteral).text;imports.push({path:p,specifier:s});
        if(s.startsWith('.')){const base=path.posix.normalize(path.posix.join(path.posix.dirname(p),s));if(!CODE_CLOSURE.some(c=>c===base||c===base+'.js'||c===base+'.ts'))fail('DEPENDENCY_REFUSED');}
        else if(s!=='jiti'&&!s.startsWith('node:'))fail('DEPENDENCY_REFUSED');
      }
      ts.forEachChild(n,visit);
    };visit(ast);
  }
  return {schema:'TriageCodeStaticAdmission@1',source:codeCandidateDigest(w),importsDigest:digest(imports),imports:imports.length};
}

export async function runCodeChecks(w:CodeWorkspace) {
  const smoke=await runCodeSmokeChecks(w),staticAdmission=checkCodeDependencies(w);
  // Full original hardening/grounding assertions are an explicit required gate;
  // the three carrier smoke probes never masquerade as those suites.
  return runFrozenAssertionChecks(w,smoke,staticAdmission);
}
async function runFrozenAssertionChecks(w:CodeWorkspace,smoke:Awaited<ReturnType<typeof runCodeSmokeChecks>>,staticAdmission:ReturnType<typeof checkCodeDependencies>) {
  const trustedRoot=path.resolve(path.dirname(worker),'../..'),tests=['lib/triage-core/__tests__/redblue-card-refinement-hardening.test.ts','lib/triage-core/__tests__/card-claim-grounding.test.js','extensions/pi-autoresearch/triage-card-paired.ts','extensions/pi-autoresearch/triage-card-synthetic.cjs'];
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'triage-code-assertions-')));fs.chmodSync(root,0o700);
  const req=createRequire(import.meta.url),identity:Record<string,string>={};
  try{
    for(const p of tests){const file=path.join(trustedRoot,p),bytes=read(file);const ref=spawnSync('git',['show','HEAD:'+p],{cwd:trustedRoot,maxBuffer:4*1024*1024});if(ref.status!==0||hash(ref.stdout)!==hash(bytes))fail('TEST_SOURCE_CHANGED');
      const dest=path.join(root,p);fs.mkdirSync(path.dirname(dest),{recursive:true,mode:0o700});fs.writeFileSync(dest,bytes,{mode:0o600});identity[p]=hash(bytes);
    }
    const carrier=path.join(root,'bridge.cjs'),module=fileURLToPath(import.meta.url),owner=path.join(root,'owner.json');writePrivate(owner,w);
    // Fixed source generated from this trusted owner, never from a candidate.
    fs.writeFileSync(carrier,`const fs=require('node:fs');const owner=JSON.parse(fs.readFileSync(${JSON.stringify(owner)},'utf8'));let bridge;exports.get=()=>bridge??=(require(${JSON.stringify(module)}).createCodeTestBridge(owner));exports.close=()=>{if(bridge){bridge.close();bridge=null;}};`,{mode:0o600});
    for(const[name,p]of [['composer',CODE_TARGETS[0]],['grounding',CODE_TARGETS[1]],['conversation','lib/triage-core/producers/conversation-facts-producer.js']]){
      const dest=path.join(root,p);fs.mkdirSync(path.dirname(dest),{recursive:true,mode:0o700});
      fs.writeFileSync(dest,`const bridge=require(${JSON.stringify(carrier)});\n`+RPC_NAMES[name].map(key=>`exports.${key}=bridge.get().modules.${name}.${key};`).join('\n'),{mode:0o600});
    }
    const vitestRoot=path.dirname(req.resolve('vitest/package.json')),vitest=path.join(vitestRoot,'vitest.mjs'),vitestExports=path.join(vitestRoot,'dist/index.js'),config=path.join(root,'vitest.config.mjs'),setup=path.join(root,'setup.mjs');
    fs.writeFileSync(setup,`import {afterAll} from ${JSON.stringify(vitestExports)};import bridge from ${JSON.stringify(carrier)};afterAll(()=>bridge.close());`,{mode:0o600});
    fs.writeFileSync(config,`export default ${JSON.stringify({resolve:{alias:{vitest:vitestExports}},test:{include:[tests[0]],environment:'node',pool:'forks',maxWorkers:1,minWorkers:1,isolate:false,setupFiles:[setup],testTimeout:15000,reporters:['json'],outputFile:path.join(root,'vitest-results.json')}})};`,{mode:0o600});
    const preload=path.join(root,'node-close.cjs');fs.writeFileSync(preload,`require('node:test').after(()=>require(${JSON.stringify(carrier)}).close());`,{mode:0o600});
    const env:NodeJS.ProcessEnv={...process.env,NODE_OPTIONS:'--experimental-strip-types',NODE_PATH:process.env.NODE_PATH??''};
    // These are independent native test runners, not recursive children of the
    // caller's node:test harness. Retain zero/empty detection in the readback.
    delete env.NODE_TEST_CONTEXT;
    const run=async(args:string[],name:string)=>{
      const file=path.join(root,name+'.log'),fd=fs.openSync(file,'wx',0o600);
      try{return await new Promise<number|null>((resolve,reject)=>{
        const child=spawn(process.execPath,args,{cwd:root,env,stdio:['ignore',fd,fd],detached:true});const timer=setTimeout(()=>{try{process.kill(-child.pid!,'SIGKILL');}catch{}reject(Error('TRIAGE_CODE_TEST_DEADLINE'));},120000);
        child.on('error',reject);child.on('close',code=>{clearTimeout(timer);resolve(code);});
      });}finally{fs.closeSync(fd);}
    };
    const hardeningStatus=await run([vitest,'run','--config',config],'hardening');
    let hardening;try{hardening=JSON.parse(read(path.join(root,'vitest-results.json')).toString());}catch{fail('HARDENING_REPORT_UNAVAILABLE');}
    const nativeStatus=await run(['--require',preload,'--test','--test-concurrency=1',tests[1]],'grounding');
    const native=read(path.join(root,'grounding.log')).toString(),count=(s:string)=>Number(native.match(new RegExp('^# '+s+' (\\d+)$','m'))?.[1]);
    const pairedClose=path.join(root,'paired-close.cjs');fs.writeFileSync(pairedClose,`process.on('exit',()=>require(${JSON.stringify(carrier)}).close());`,{mode:0o600});
    const pairedStatus=await run(['--require',pairedClose,'--experimental-strip-types',tests[2],'--dev','--json'],'paired');
    let paired;try{paired=JSON.parse(read(path.join(root,'paired.log')).toString());}catch{fail('PAIRED_REPORT_UNAVAILABLE');}
    const knipRoot=path.join(root,'static');fs.mkdirSync(knipRoot,{mode:0o700});copyClosure(w,knipRoot);
    const jitiPkg=JSON.parse(read(path.join(knipRoot,'node_modules/jiti/package.json')).toString());
    writePrivate(path.join(knipRoot,'package.json'),{name:'triage-code-static-admission',version:'0.0.0',dependencies:{jiti:jitiPkg.version}});
    writePrivate(path.join(knipRoot,'tsconfig.json'),{compilerOptions:{allowJs:true},include:[...CODE_TARGETS]});
    writePrivate(path.join(knipRoot,'knip.json'),{entry:[...CODE_TARGETS],project:[...CODE_TARGETS],ignore:CODE_CLOSURE.filter(p=>!CODE_TARGETS.includes(p as Target))});
    const knip=path.resolve(path.dirname(req.resolve('knip')),'../bin/knip.js'),knipStatus=await run([knip,'--directory',knipRoot,'--config',path.join(knipRoot,'knip.json'),'--tsConfig',path.join(knipRoot,'tsconfig.json'),'--no-progress','--reporter','json','--include','unresolved,unlisted'],'knip');
    let knipReport;try{knipReport=JSON.parse(read(path.join(root,'knip.log')).toString());}catch{fail('STATIC_REPORT_UNAVAILABLE');}
    const staticResult={...staticAdmission,knip:{status:knipStatus,reportDigest:digest(knipReport),scope:[...CODE_TARGETS],configurationDigest:hash(read(path.join(knipRoot,'knip.json')))}};
    const proof={hardening:{status:hardeningStatus,total:hardening.numTotalTests,passed:hardening.numPassedTests,failed:hardening.numFailedTests,pending:hardening.numPendingTests},grounding:{status:nativeStatus,total:count('tests'),passed:count('pass'),failed:count('fail'),skipped:count('skipped'),cancelled:count('cancelled')},paired:{status:pairedStatus,evaluated:paired.dev?.evaluated,defects:paired.dev?.defectsCount,verdict:paired.verdict,qualification:paired.qualification,latencyMs:paired.dev?.avgLatencyMs},static:staticResult,identity,digests:{hardening:hash(read(path.join(root,'hardening.log'))),grounding:hash(read(path.join(root,'grounding.log'))),paired:hash(read(path.join(root,'paired.log')))}};
    // Preserve each actual run privately for diagnosis, including RED. No mission
    // receipt or generic passing suite is manufactured from these counts.
    writePrivate(path.join(root,'proof.json'),proof);
    if(hardeningStatus!==0||hardening.numTotalTests!==30||hardening.numPassedTests!==30||hardening.numFailedTests!==0||hardening.numPendingTests!==0||nativeStatus!==0||count('tests')!==104||count('pass')!==104||count('fail')!==0||count('skipped')!==0||count('cancelled')!==0||pairedStatus!==0||paired.dev?.evaluated!==500||paired.dev?.defectsCount!==0||paired.verdict!=='PASS'||paired.qualification!=='UNQUALIFIED'||knipStatus!==0)throw Object.assign(Error('TRIAGE_CODE_FROZEN_ASSERTIONS_FAILED'),{evidenceDirectory:root});
    for(const[p,h]of Object.entries(identity))if(hash(read(path.join(trustedRoot,p)))!==h||hash(read(path.join(root,p)))!==h)fail('TEST_SOURCE_CHANGED');
    return {schema:'TriageCodeChecks@1' as const,candidateDigest:codeCandidateDigest(w),identity:{...smoke.identity,assertions:identity,instrument:'unchanged-frozen-assertions-via-jailed-RPC'},suites:{hardening:proof.hardening,native:proof.grounding,paired:proof.paired,static:proof.static},resultDigest:digest({smoke:smoke.resultDigest,proof}),checks:proof.hardening.total+proof.grounding.total+proof.paired.evaluated+smoke.checks,proofDirectory:root};
  }catch(e){throw e;}
}
