Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

95.4 KB
Raw Blame
// Pixel Agent host ingress contract tests.
//
// Runs against the importable implementation (no server auto-start). Covers:
//   - unsafe token file/symlink/mode rejection
//   - exact route/methods
//   - request limit
//   - header stripping
//   - forced model
//   - stable hashed user
//   - sanitized errors
//   - fixed docker execFile (mocked)
//   - safe status projection
//   - UDS permissions/path refusal
//   - streaming/nonstream bounds

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import http from "node:http";
import net from "node:net";
import { createHash } from "node:crypto";
import {createSubagentDelivery} from '../plugin/subagent-delivery.mjs';

const {
  gatewayRuntimeFromConfig,
  readGatewayConfiguration,
  readGatewayToken,
  prepareSocketPath,
  createIngressServer,
  computeSessionUser,
  buildOutgoing,
  configFromEnv,
  validateConfig,
  dockerApps,
  dockerRuntime,
  dockerVllmRuntime,
  dockerRouterRuntime,
  writeStatus,
  start,
  gatewayFetch,
} = await import(process.env.PIXEL_INGRESS_MODULE ?? "../host/pixel_ingress.mjs");

const DIR = path.join(os.tmpdir(), `px-ing-${process.pid}-${Date.now()}`);
fs.mkdirSync(DIR, { recursive: true });
const SOCKET = path.join(DIR, "pixel-ingress.sock");
const TOKEN = "test-gateway-token-0123456789abcdef";
const TEST_RUN_ID = "chatcmpl_11111111-2222-4333-8444-555555555555";
const EUID = typeof process.geteuid === "function"
  ? process.geteuid()
  : (typeof process.getuid === "function" ? process.getuid() : 0);
let socketCounter = 0;

// A fake upstream gateway that records exactly what it receives and returns a
// canned completion. Used to assert forced model, header stripping, hashed
// user, and streaming/nonstream bounds.
function fakeGateway({
  onRequest,
  onVerificationRequest,
  onRecoveryRequest,
  onDecisionRequest,
  onDeliveryRequest,
  delivery,
  recovery = {schemaVersion:1,kind:'ods-extension-read-only-continuation',eligible:false},
  decisionProof = {schemaVersion:1,kind:'ods-extension-unfinished-decision',eligible:false},
  completionResponses,
  verification = { status: "none" },
  abortReplies = [true],
  completionText = "ok",
  completionStatus = 200,
} = {}) {
  let abortIndex = 0;
  let completionIndex = 0;
  const server = http.createServer((req, res) => {
    let body = "";
    req.on("data", (c) => (body += c));
    req.on("end", () => {
      if (req.url === '/health') {
        res.writeHead(200, {'Content-Type':'application/json'});
        res.end(JSON.stringify({ok:true}));
        return;
      }
      const captured = {
        method: req.method,
        url: req.url,
        headers: req.headers,
        body: body ? JSON.parse(body) : null,
      };
      if (req.url === "/pixel-ods/verification") {
        if (onVerificationRequest) onVerificationRequest(captured);
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify(verification));
        return;
      }
      if (req.url === '/pixel-ods/subagent-delivery') {
        onDeliveryRequest?.(captured);
        res.writeHead(200,{'Content-Type':'application/json'});
        res.end(JSON.stringify(typeof delivery==='function' ? delivery(captured) : delivery ??
          {schemaVersion:1,kind:'ods-subagent-delivery',runId:captured.body.runId,status:'not-delegated'}));
        return;
      }
      if (req.url === "/pixel-ods/read-only-extension-continuation") {
        onRecoveryRequest?.(captured);
        res.writeHead(200,{"Content-Type":"application/json"});
        res.end(JSON.stringify(recovery));
        return;
      }
      if (req.url === "/pixel-ods/unfinished-extension-decision") {
        onDecisionRequest?.(captured);
        res.writeHead(200,{"Content-Type":"application/json"});
        res.end(JSON.stringify(decisionProof));
        return;
      }
      if (onRequest) onRequest(captured);
      if (req.url === "/pixel-ods/abort") {
        res.writeHead(200, { "Content-Type": "application/json" });
        const aborted = abortReplies[Math.min(abortIndex, abortReplies.length - 1)];
        abortIndex += 1;
        res.end(JSON.stringify({ aborted }));
        return;
      }
      if (req.headers.accept === "text/event-stream") {
        res.writeHead(200, { "Content-Type": "text/event-stream" });
        res.write(`data: ${JSON.stringify({ id: TEST_RUN_ID, model: "openclaw/default", created: 1, choices: [{ delta: { content: "a" } }] })}\n\n`);
        res.end("data: [DONE]\n\n");
        return;
      }
      res.writeHead(completionStatus, { "Content-Type": "application/json" });
      res.end(JSON.stringify(completionResponses?.[completionIndex++] ??
        { id: TEST_RUN_ID, choices: [{ message: { content: completionText } }] }));
    });
  });
  return new Promise((resolve) => {
    server.listen(0, "127.0.0.1", () => {
      resolve({ server, port: server.address().port });
    });
  });
}

function startIngress({ token = TOKEN, gatewayPort, socket, deps } = {}) {
  socket ||= path.join(DIR, `ingress-${++socketCounter}.sock`);
  prepareSocketPath(socket);
  const server = createIngressServer({
    token,
    gatewayPort,
    deps,
  });
  return new Promise((resolve, reject) => {
    server.once("listening", () => resolve(server));
    server.once("error", reject);
    server.listen(socket);
  });
}

for (const stream of [false, true]) {
  for (const status of [429, 500]) {
    test(`sanitizes upstream ${status} while preserving rate-limit identity (stream=${stream})`, async () => {
      let submissions = 0;
      const gw = await fakeGateway({completionStatus:status, completionText:'private-provider-secret', onRequest:()=>submissions++});
      const srv = await startIngress({gatewayPort:gw.port});
      try {
        const result = await request(srv, 'POST', '/v1/chat/completions', {
          body:JSON.stringify({messages:[{role:'user',content:'Continue editing'}],stream}),
          headers:{'Content-Type':'application/json'},
        });
        assert.equal(result.status, stream ? 200 : status === 429 ? 429 : 502);
        assert.equal(result.body.includes('provider_rate_limited'), status === 429);
        assert.ok(!result.body.includes('private-provider-secret'));
        assert.equal(submissions, 1, 'never replay work after a provider failure');
        if (stream) assert.ok(result.body.endsWith('data: [DONE]\n\n'));
      } finally {
        await new Promise(resolve=>srv.close(resolve));
        await new Promise(resolve=>gw.server.close(resolve));
      }
    });
  }
}

test('re-reads a briefly unavailable final receipt without resubmitting work', async()=>{
  let submissions=0, reads=0;
  const verification={status:'unavailable'};
  const gw=await fakeGateway({verification,onRequest:()=>submissions++,onVerificationRequest:()=>{
    reads++;
    if(reads===2)verification.status='none';
  }});
  const srv=await startIngress({gatewayPort:gw.port});
  try {
    const response=await request(srv,'POST','/v1/chat/completions',{
      body:JSON.stringify({messages:[{role:'user',content:'Do the work'}],stream:true}),headers:{'Content-Type':'application/json'},
    });
    assert.equal(response.status,200);
    assert.ok(response.body.includes('"pixel_outcome":{"schemaVersion":1,"status":"none"}'));
    assert.equal(submissions,1);assert.equal(reads,2);
  } finally {
    await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));
  }
});

for (const stream of [false,true]) {
  test(`yield waits for scoped consolidated delivery without replay (stream=${stream})`,async()=>{
    let reads=0,submissions=0;const owners=[];
    const gw=await fakeGateway({completionText:'Waiting for child review',onRequest:value=>{if(value.url==='/v1/chat/completions')submissions++;},
      onDeliveryRequest:captured=>owners.push(captured.body),delivery:captured=>{
        reads++;
        return {schemaVersion:1,kind:'ods-subagent-delivery',runId:captured.body.runId,
          ...(reads===1?{status:'waiting'}:{status:'ready',text:'Both reviews consolidated and verified',verification:{status:'passed'}})};
      }});
    const srv=await startIngress({gatewayPort:gw.port});
    try {
      const response=await request(srv,'POST','/v1/chat/completions',{
        body:JSON.stringify({user:'delegated-owner',messages:[{role:'user',content:'Ask reviewers then consolidate'}],stream}),
        headers:{'Content-Type':'application/json'},
      });
      assert.equal(response.status,200);assert.match(response.body,/Both reviews consolidated and verified/);
      assert.ok(!response.body.includes('Waiting for child review'));
      assert.equal(submissions,1);assert.equal(reads,2);
      assert.deepEqual(owners[0],owners[1]);assert.match(owners[0].user,/^ods-[a-f0-9]{64}$/);
      assert.equal(owners[0].runId,TEST_RUN_ID);
      if(stream)assert.equal(response.body.match(/data: \[DONE\]/g).length,1);
    } finally {await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));}
  });
  test(`lost or mismatched continuation receipt cannot deliver introduction (stream=${stream})`,async()=>{
    for(const result of [{status:'interrupted',message:'fixed interruption'},{status:'ready',text:'Foreign answer',verification:{status:'none'},runId:'foreign'}]) {
      let submissions=0;
      const gw=await fakeGateway({completionText:'Waiting for child review',onRequest:value=>{if(value.url==='/v1/chat/completions')submissions++;},
        delivery:{schemaVersion:1,kind:'ods-subagent-delivery',runId:TEST_RUN_ID,...result}});
      const srv=await startIngress({gatewayPort:gw.port});
      try {
        const response=await request(srv,'POST','/v1/chat/completions',{
          body:JSON.stringify({user:'delegated-owner',messages:[{role:'user',content:'Delegate review'}],stream}),headers:{'Content-Type':'application/json'},
        });
        assert.equal(response.status,stream?200:502);assert.match(response.body,/error/);
        assert.ok(!response.body.includes('Waiting for child review'));assert.ok(!response.body.includes('Foreign answer'));
        assert.equal(submissions,1);
      } finally {await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));}
    }
  });
}

test('anonymous chat retains ephemeral sessions with distinct internal delivery custody',async()=>{
  const requests=[],reads=[];
  const gw=await fakeGateway({onRequest:value=>{if(value.url==='/v1/chat/completions')requests.push(value.body);},onDeliveryRequest:value=>reads.push(value.body)});
  const srv=await startIngress({gatewayPort:gw.port});
  try {
    for(let i=0;i<2;i++) {
      const response=await request(srv,'POST','/v1/chat/completions',{
        body:JSON.stringify({messages:[{role:'user',content:'Hello'}]}),headers:{'Content-Type':'application/json'},
      });
      assert.equal(response.status,200);assert.match(response.body,/ok/);
    }
    assert.notEqual(requests[0].user,requests[1].user);
    for(let i=0;i<2;i++){assert.match(requests[i].user,/^ods-[a-f0-9]{64}$/);assert.equal(reads[i].user,requests[i].user);}
  } finally {await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));}
});

for(const stream of [false,true])for(const outcome of ['ready','overflow'])
test(`accepted spawn without yield keeps actual ingress open until ${outcome} (stream=${stream})`,async()=>{
  let submissions=0,reads=0,registry,owner;
  const child='agent:pixel:subagent:22222222-2222-4333-8444-555555555555';
  const childRun='33333333-2222-4333-8444-555555555555';
  const gw=await fakeGateway({completionText:'I am waiting for the review.',onRequest:captured=>{
    if(captured.url!=='/v1/chat/completions')return;
    submissions++;
    owner={agentId:'pixel',runId:TEST_RUN_ID,sessionId:'native-owner',
      sessionKey:'agent:pixel:openai-user:'+captured.body.user,trigger:'user'};
    registry=createSubagentDelivery({resolveOwnerSession:()=>({sessionId:owner.sessionId}),
      finalText:message=>message.content.filter(block=>block.type==='text').map(block=>block.text).join('\n')});
    registry.observe({},owner);
    const ctx={...owner,toolName:'sessions_spawn',toolCallId:'actual-spawn'};
    registry.before({params:{runtime:'subagent',mode:'run'}},ctx);
    registry.nativeSpawn({runId:childRun,childSessionKey:child},
      {runId:childRun,childSessionKey:child,requesterSessionKey:owner.sessionKey});
    registry.after({result:{details:{status:'accepted',runId:childRun,childSessionKey:child}}},ctx);
    registry.end({success:true,messages:[{role:'assistant',stopReason:'stop',content:[
      {type:'text',text:'I am waiting for the review.'}]}]},owner);
  },delivery:captured=>{
    reads++;
    if(reads===2) {
      const ctx={...owner,runId:`announce:v1:${child}:${childRun}`,
        inputProvenance:{kind:'inter_session',sourceTool:'subagent_announce',sourceSessionKey:child}};
      registry.observe({prompt:'Actual registered child result'},ctx);
      const text=outcome==='ready'?'The verified review is complete.':'Context overflow: prompt too large for the model.';
      if(outcome==='ready')registry.finalize({lastAssistantMessage:text},ctx);
      registry.end({success:true,messages:[{role:'assistant',stopReason:outcome==='ready'?'stop':'error',
        content:[{type:'text',text}]}]},ctx);
    }
    return registry.read(captured.body.user,captured.body.runId);
  }});
  const srv=await startIngress({gatewayPort:gw.port});
  try {
    const response=await request(srv,'POST','/v1/chat/completions',{
      body:JSON.stringify({user:'native-no-yield',messages:[{role:'user',content:'Delegate one review and return findings.'}],stream}),
      headers:{'Content-Type':'application/json'},
    });
    assert.equal(response.status,outcome==='ready'||stream?200:502);
    assert.equal(reads,2,'accepted native work must not publish the original introduction');
    assert.equal(submissions,1,'delivery never replays the owner request');
    assert.ok(!response.body.includes('I am waiting for the review.'));
    if(outcome==='ready')assert.match(response.body,/The verified review is complete/);
    else {assert.match(response.body,/error/);assert.ok(!response.body.includes('Context overflow'));}
  } finally {await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));}
});

test('explicit Stop interrupts a held delegated response without exposing the introduction',async()=>{
  let began;const observed=new Promise(resolve=>began=resolve);let reads=0;
  const gw=await fakeGateway({completionText:'Waiting for children',delivery:captured=>{
    reads++;began();return {schemaVersion:1,kind:'ods-subagent-delivery',runId:captured.body.runId,status:'waiting'};
  }});
  const srv=await startIngress({gatewayPort:gw.port});
  try {
    const pending=request(srv,'POST','/v1/chat/completions',{
      body:JSON.stringify({user:'stop-owner',messages:[{role:'user',content:'Review'}],stream:true}),headers:{'Content-Type':'application/json'},
    });
    await observed;
    const cancelled=await request(srv,'POST','/v1/chat/cancel',{
      body:JSON.stringify({user:'stop-owner'}),headers:{'Content-Type':'application/json'},
    });
    assert.equal(cancelled.status,200);
    const response=await pending;assert.match(response.body,/error/);assert.ok(!response.body.includes('Waiting for children'));
    const settledReads=reads;await new Promise(resolve=>setTimeout(resolve,700));assert.equal(reads,settledReads);
  } finally {await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));}
});

test('empty response continues once only after a matching read-only extension proof',async()=>{
  const first={id:TEST_RUN_ID,choices:[{message:{role:'assistant',content:
    "⚠️ Agent couldn't generate a response. Please try again."},finish_reason:'stop'}]};
  const second={id:'chatcmpl_aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',choices:[{
    message:{role:'assistant',content:'Verified continuation.'},finish_reason:'stop'}]};
  const observed=[], recoveryCalls=[];
  const gw=await fakeGateway({completionResponses:[first,second],
    recovery:{schemaVersion:1,kind:'ods-extension-read-only-continuation',eligible:true,
      chatId:'chat',requestId:'turn'},onRequest:value=>observed.push(value),
    onRecoveryRequest:value=>recoveryCalls.push(value)});
  const srv=await startIngress({gatewayPort:gw.port});
  try {
    const response=await request(srv,'POST','/v1/chat/completions',{
      body:JSON.stringify({user:'chat',messages:[{role:'user',content:'/extensions install https://github.com/example/project'}],stream:true}),
      headers:{'Content-Type':'application/json'},
    });
    assert.equal(response.status,200);
    assert.match(response.body,/Verified continuation/);
    assert.equal(observed.length,2);
    assert.equal(recoveryCalls.length,1);
    assert.deepEqual(recoveryCalls[0].body,{runId:TEST_RUN_ID});
    assert.equal(observed[0].body.user,observed[1].body.user);
    assert.notDeepEqual(observed[0].body.messages,observed[1].body.messages);
    assert.match(observed[1].body.messages[0].content,/ODS internal continuation/);
    assert.doesNotMatch(observed[1].body.messages[0].content,/github.com\/example/);
  } finally {
    await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));
  }
});

test('empty response does not continue from a mismatched or absent proof',async()=>{
  const first={id:TEST_RUN_ID,choices:[{message:{role:'assistant',content:
    "⚠️ Agent couldn't generate a response. Please try again."},finish_reason:'stop'}]};
  for(const recovery of [
    {schemaVersion:1,kind:'ods-extension-read-only-continuation',eligible:false},
    {schemaVersion:1,kind:'ods-extension-read-only-continuation',eligible:true,chatId:'other',requestId:'turn'},
  ]) {
    const observed=[];
    const gw=await fakeGateway({completionResponses:[first],recovery,onRequest:value=>observed.push(value)});
    const srv=await startIngress({gatewayPort:gw.port});
    try {
      const response=await request(srv,'POST','/v1/chat/completions',{
        body:JSON.stringify({user:'chat',messages:[{role:'user',content:'continue'}],stream:true}),
        headers:{'Content-Type':'application/json'},
      });
      assert.equal(response.status,200);
      assert.equal(observed.length,1);
      assert.doesNotMatch(response.body,/Verified continuation/);
    } finally {
      await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));
    }
  }
});

test('unfinished extension decision continues once only from matching durable proof',async()=>{
  const first={id:TEST_RUN_ID,choices:[{message:{role:'assistant',content:'I will propose the install next.'},finish_reason:'stop'}]};
  const second={id:'chatcmpl_aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',choices:[{
    message:{role:'assistant',content:'Verified proposal receipt.'},finish_reason:'stop'}]};
  const observed=[], decisionCalls=[];
  const gw=await fakeGateway({completionResponses:[first,second],
    decisionProof:{schemaVersion:1,kind:'ods-extension-unfinished-decision',eligible:true,
      chatId:'chat',requestId:'turn',repository:'https://github.com/example/project'},
    onRequest:value=>observed.push(value),onDecisionRequest:value=>decisionCalls.push(value)});
  const srv=await startIngress({gatewayPort:gw.port});
  try {
    const response=await request(srv,'POST','/v1/chat/completions',{
      body:JSON.stringify({user:'chat',messages:[{role:'user',content:'/extensions https://github.com/example/project install'}]}),
      headers:{'Content-Type':'application/json'},
    });
    assert.equal(response.status,200);
    assert.match(response.body,/Verified proposal receipt/);
    assert.doesNotMatch(response.body,/I will propose/);
    assert.equal(observed.length,2);
    assert.equal(decisionCalls.length,1);
    assert.deepEqual(decisionCalls[0].body,{runId:TEST_RUN_ID});
    assert.equal(observed[0].body.user,observed[1].body.user);
    assert.match(observed[1].body.messages[0].content,
      /^\/extensions https:\/\/github\.com\/example\/project ODS internal continuation/);
    assert.match(observed[1].body.messages[0].content,/saved request turn/);
  } finally {
    await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));
  }
});

test('unfinished extension decision does not continue from absent or mismatched proof',async()=>{
  const first={id:TEST_RUN_ID,choices:[{message:{role:'assistant',content:'I will propose next.'},finish_reason:'stop'}]};
  for(const decisionProof of [
    {schemaVersion:1,kind:'ods-extension-unfinished-decision',eligible:false},
    {schemaVersion:1,kind:'ods-extension-unfinished-decision',eligible:true,chatId:'other',requestId:'turn',repository:'https://github.com/example/project'},
    {schemaVersion:1,kind:'ods-extension-unfinished-decision',eligible:true,chatId:'chat',requestId:'turn',repository:'https://github.com/example/project',extra:true},
  ]) {
    const observed=[];
    const gw=await fakeGateway({completionResponses:[first],decisionProof,onRequest:value=>observed.push(value)});
    const srv=await startIngress({gatewayPort:gw.port});
    try {
      const response=await request(srv,'POST','/v1/chat/completions',{
        body:JSON.stringify({user:'chat',messages:[{role:'user',content:'continue'}]}),
        headers:{'Content-Type':'application/json'},
      });
      assert.equal(response.status,200);
      assert.equal(observed.length,1);
      assert.match(response.body,/I will propose next/);
    } finally {
      await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));
    }
  }
});

function request(server, method, pathname, opts = {}) {
  return new Promise((resolve, reject) => {
    const req = http.request(
      {
        socketPath: server.address(),
        method,
        path: pathname,
        headers: opts.headers || {},
      },
      (res) => {
        let data = "";
        res.on("data", (c) => (data += c));
        res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: data }));
      }
    );
    req.on("error", reject);
    if (opts.body !== undefined) req.write(opts.body);
    req.end();
  });
}

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

test("configFromEnv applies defaults and overrides", () => {
  const d = configFromEnv({});
  assert.equal(d.socketPath, "/run/ods-pixel/pixel-ingress.sock");
  assert.equal(d.gatewayPort, 18789);
  assert.equal(d.gatewayTokenFile, "/etc/pixel/openclaw.json");
  assert.equal(d.statusIntervalMs, 30000);
  assert.equal(d.ingressGid, null);
  assert.equal(d.odsVersion, "unknown");
  assert.equal(d.appPorts.n8n, 5678);
  assert.equal(d.appPorts.whisper, 9000);
  const o = configFromEnv({
    PIXEL_INGRESS_SOCKET: "/x.sock",
    PIXEL_GATEWAY_PORT: "19000",
    PIXEL_INGRESS_GID: "1234",
    PIXEL_STATUS_INTERVAL_MS: "5000",
    PIXEL_GATEWAY_TOKEN_FILE: "/custom.json",
    PIXEL_ODS_VERSION: "2.6.0-beta.1",
    PIXEL_ODS_N8N_PORT: "15678",
    PIXEL_ODS_WHISPER_PORT: "19000",
  });
  assert.equal(o.socketPath, "/x.sock");
  assert.equal(o.gatewayPort, 19000);
  assert.equal(o.ingressGid, 1234);
  assert.equal(o.statusIntervalMs, 5000);
  assert.equal(o.odsVersion, "2.6.0-beta.1");
  assert.equal(o.appPorts.n8n, 15678);
  assert.equal(o.appPorts.whisper, 19000);
});

test("config rejects invalid ports, intervals, gids, and relative paths", () => {
  const base = configFromEnv({});
  for (const gatewayPort of [0, 65536, 1.5, NaN]) {
    assert.throws(() => validateConfig({ ...base, gatewayPort }), /gateway port/);
  }
  for (const statusIntervalMs of [0, -1, 86400001, 1.5]) {
    assert.throws(() => validateConfig({ ...base, statusIntervalMs }), /status interval/);
  }
  assert.throws(() => validateConfig({ ...base, ingressGid: -1 }), /ingress gid/);
  assert.throws(() => validateConfig({ ...base, odsVersion: "2.6.0\nSECRET=x" }), /ODS version/);
  assert.throws(
    () => validateConfig({ ...base, appPorts: { ...base.appPorts, n8n: 0 } }),
    /application port/
  );
  assert.throws(() => validateConfig({ ...base, socketPath: "relative.sock" }), /socket path/);
});

// ---------------------------------------------------------------------------
// Token file rejection
// ---------------------------------------------------------------------------

test("readGatewayToken refuses symlink token file", () => {
  const target = path.join(DIR, "real.env");
  fs.writeFileSync(target, `PIXEL_GATEWAY_TOKEN=${TOKEN}\n`, { mode: 0o600 });
  const link = path.join(DIR, "link.env");
  try {
    fs.unlinkSync(link);
  } catch {}
  fs.symlinkSync(target, link);
  assert.throws(() => readGatewayToken(link, EUID), /symlink/);
});

test("readGatewayToken refuses non-regular file", () => {
  const dir = path.join(DIR, "tokendir");
  fs.mkdirSync(dir, { recursive: true });
  assert.throws(() => readGatewayToken(dir, EUID), /not a regular file/);
});

test("readGatewayToken refuses group/world-readable modes", () => {
  const f = path.join(DIR, "groupread.env");
  fs.writeFileSync(f, `PIXEL_GATEWAY_TOKEN=${TOKEN}\n`, { mode: 0o640 });
  fs.chmodSync(f, 0o640);
  assert.throws(() => readGatewayToken(f, EUID), /group\/world readable/);
  const w = path.join(DIR, "worldread.env");
  fs.writeFileSync(w, `PIXEL_GATEWAY_TOKEN=${TOKEN}\n`, { mode: 0o604 });
  fs.chmodSync(w, 0o604);
  assert.throws(() => readGatewayToken(w, EUID), /group\/world readable/);
});

test("readGatewayToken refuses owner mismatch", () => {
  const f = path.join(DIR, "otherowner.env");
  fs.writeFileSync(f, `PIXEL_GATEWAY_TOKEN=${TOKEN}\n`, { mode: 0o600 });
  const other = EUID === 0 ? 12345 : 0;
  assert.throws(() => readGatewayToken(f, other), /owner mismatch/);
});

test("readGatewayToken parses only PIXEL_GATEWAY_TOKEN, rejects empty", () => {
  const good = path.join(DIR, "good.env");
  fs.writeFileSync(
    good,
    `OTHER=ignored\nPIXEL_GATEWAY_TOKEN=${TOKEN}\nPIXEL_GATEWAY_TOKEN_SECOND=zz\n`,
    { mode: 0o600 }
  );
  assert.equal(readGatewayToken(good, EUID), TOKEN);
  const empty = path.join(DIR, "empty.env");
  fs.writeFileSync(empty, "PIXEL_GATEWAY_TOKEN=\n", { mode: 0o600 });
  assert.throws(() => readGatewayToken(empty, EUID), /missing or empty/);
});

test("readGatewayToken reads the owner-private OpenClaw gateway token", () => {
  const config = path.join(DIR, "openclaw.json");
  fs.writeFileSync(config, `${JSON.stringify({ gateway: { auth: { token: TOKEN } } })}\n`, { mode: 0o600 });
  assert.equal(readGatewayToken(config, EUID), TOKEN);
  fs.writeFileSync(config, `${JSON.stringify({ gateway: { auth: {} } })}\n`, { mode: 0o600 });
  assert.throws(() => readGatewayToken(config, EUID), /missing or empty/);
});

test("secure OpenClaw configuration projects the concrete selected Pixel runtime", () => {
  const config = path.join(DIR, "openclaw-runtime.json");
  const value = {
    gateway: { auth: { token: TOKEN } },
    agents: { list: [{ id: "pixel", model: "ods-gateway/ods/current" }] },
    models: {
      providers: {
        "ods-gateway": {
          models: [{
            id: "ods/current",
            name: "ODS Current (org/model:variant)",
            contextWindow: 2_000_000,
            maxTokens: 32768,
            reasoning: true,
          }],
        },
      },
    },
  };
  fs.writeFileSync(config, `${JSON.stringify(value)}\n`, { mode: 0o600 });
  assert.deepEqual(gatewayRuntimeFromConfig(value), {
    model: "org/model:variant",
    context_length: 2_000_000,
  });
  assert.deepEqual(readGatewayConfiguration(config, EUID), {
    token: TOKEN,
    runtime: { model: "org/model:variant", context_length: 2_000_000 },
    runtimeAuthoritative: true,
  });
  value.models.providers["ods-gateway"].models[0].name = "unbound different-model";
  assert.equal(gatewayRuntimeFromConfig(value), null);
});

// ---------------------------------------------------------------------------
// Socket path refusal
// ---------------------------------------------------------------------------

test("prepareSocketPath refuses non-socket path", () => {
  const f = path.join(DIR, "notasocket");
  fs.writeFileSync(f, "x");
  assert.throws(() => prepareSocketPath(f), /non-socket path/);
});

test("prepareSocketPath removes only a socket at its own path", () => {
  const s = path.join(DIR, "existing.sock");
  const srv = net.createServer();
  return new Promise((resolve, reject) => {
    srv.listen(s, () => {
      try {
        prepareSocketPath(s);
        assert.equal(fs.existsSync(s), false);
        srv.close();
        resolve();
      } catch (e) {
        srv.close();
        reject(e);
      }
    });
  });
});

// ---------------------------------------------------------------------------
// Route/method behavior
// ---------------------------------------------------------------------------

test("exact routes and methods: health, chat, and cancel work; others 404/405", async () => {
  const gw = await fakeGateway();
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const health = await request(srv, "GET", "/health");
      assert.equal(health.status, 200);
      assert.equal(JSON.parse(health.body).status, "ok");

      const chat = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ model: "anything", messages: [{ role: "user", content: "hi" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(chat.status, 200);

      const cancel = await request(srv, "POST", "/v1/chat/cancel", {
        body: JSON.stringify({ user: "conversation-42" }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(cancel.status, 200);
      assert.deepEqual(JSON.parse(cancel.body), { aborted: true });

      const badMethod = await request(srv, "DELETE", "/health");
      assert.equal(badMethod.status, 405);

      const badCancelMethod = await request(srv, "GET", "/v1/chat/cancel");
      assert.equal(badCancelMethod.status, 405);

      const unknown = await request(srv, "GET", "/v1/models");
      assert.equal(unknown.status, 404);
    } finally {
      await new Promise((r) => srv.close(r));
    }
  } finally {
    await new Promise((r) => gw.server.close(r));
  }
});

test("cancel validates the raw chat id and forwards only its opaque digest", async () => {
  const captured = [];
  const gw = await fakeGateway({ onRequest: (value) => captured.push(value) });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const chatId = "conversation-99";
      const response = await request(srv, "POST", "/v1/chat/cancel", {
        body: JSON.stringify({ user: chatId }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      assert.deepEqual(JSON.parse(response.body), { aborted: true });
      const digest = createHash("sha256").update(chatId).digest("hex");
      assert.equal(captured.length, 1);
      assert.equal(captured[0].url, "/pixel-ods/abort");
      assert.equal(captured[0].headers.authorization, `Bearer ${TOKEN}`);
      assert.deepEqual(captured[0].body, { user: `ods-${digest}` });

      for (const body of [
        {},
        { user: "../../escape" },
        { user: "safe", extra: true },
        { user: 7 },
      ]) {
        const invalid = await request(srv, "POST", "/v1/chat/cancel", {
          body: JSON.stringify(body),
          headers: { "Content-Type": "application/json" },
        });
        assert.equal(invalid.status, 400);
      }
      assert.equal(captured.length, 1);
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("cancel survives the bounded OpenClaw run-mapping startup race", async () => {
  const captured = [];
  const gw = await fakeGateway({
    onRequest: (value) => captured.push(value),
    abortReplies: [false, false, true],
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/cancel", {
        body: JSON.stringify({ user: "early-stop-chat" }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      assert.deepEqual(JSON.parse(response.body), { aborted: true });
      assert.equal(captured.length, 3);
      assert.ok(captured.every((call) => call.url === "/pixel-ods/abort"));
      assert.deepEqual(
        new Set(captured.map((call) => call.body.user)).size,
        1,
        "every retry must retain the exact opaque user mapping"
      );
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("successful explicit cancel closes only the matching gateway transport", async () => {
  const upstreamClosed = new Map();
  const upstreamObserved = new Map();
  const upstream = http.createServer((req, res) => {
    let body = "";
    req.on("data", (chunk) => (body += chunk));
    req.on("end", () => {
      const parsed = body ? JSON.parse(body) : {};
      if (req.url === "/pixel-ods/abort") {
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ aborted: true }));
        return;
      }
      const user = parsed.user;
      res.writeHead(200, { "Content-Type": "application/json" });
      res.flushHeaders();
      upstreamObserved.get(user)?.();
      res.on("close", () => upstreamClosed.get(user)?.(!res.writableEnded));
      // Keep both provider transports open until cancellation or test cleanup.
    });
  });
  await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve));
  const ingress = await startIngress({ gatewayPort: upstream.address().port });
  const clients = [];
  const openChat = (rawUser) => {
    const opaqueUser = computeSessionUser({ user: rawUser });
    const observed = new Promise((resolve) => upstreamObserved.set(opaqueUser, resolve));
    const closed = new Promise((resolve) => upstreamClosed.set(opaqueUser, resolve));
    const response = new Promise((resolve, reject) => {
      const client = http.request(
        {
          socketPath: ingress.address(),
          method: "POST",
          path: "/v1/chat/completions",
          headers: { "Content-Type": "application/json" },
        },
        (res) => {
          res.once("error", () => {});
          clients.push(res);
          resolve(res);
        }
      );
      client.once("error", reject);
      clients.push(client);
      client.end(JSON.stringify({
        user: rawUser,
        stream: true,
        messages: [{ role: "user", content: "keep generating" }],
      }));
    });
    return { opaqueUser, observed, closed, response };
  };

  try {
    const cancelled = openChat("cancel-this-chat");
    const retained = openChat("leave-this-chat-running");
    await Promise.all([
      cancelled.observed,
      retained.observed,
      cancelled.response,
      retained.response,
    ]);

    const cancel = await request(ingress, "POST", "/v1/chat/cancel", {
      body: JSON.stringify({ user: "cancel-this-chat" }),
      headers: { "Content-Type": "application/json" },
    });
    assert.equal(cancel.status, 200);
    assert.deepEqual(JSON.parse(cancel.body), { aborted: true });
    assert.equal(
      await Promise.race([
        cancelled.closed,
        new Promise((resolve) => setTimeout(() => resolve(false), 2000)),
      ]),
      true
    );
    assert.equal(
      await Promise.race([
        retained.closed,
        new Promise((resolve) => setTimeout(() => resolve("still-open"), 100)),
      ]),
      "still-open",
      "cancelling one opaque user must not close another user's provider transport"
    );
  } finally {
    for (const client of clients) client.destroy?.();
    await new Promise((resolve) => ingress.close(resolve));
    await new Promise((resolve) => upstream.close(resolve));
  }
});

test('cancel waits for harness drain plus managed project cleanup', async () => {
  // Scale both clocks equally: 4 s harness + 10 s project cleanup.
  const deps = {
    setTimeout: (fn, ms) => setTimeout(fn, ms / 100), clearTimeout,
    fetch: async (_url, {signal}) => {
      await new Promise((resolve, reject) => {
        const timer = setTimeout(resolve, 140);
        signal.addEventListener('abort', () => {
          clearTimeout(timer); reject(new Error('deadline'));
        }, {once:true});
      });
      return new Response(JSON.stringify({aborted:true}), {
        headers:{'Content-Type':'application/json'},
      });
    },
  };
  const srv = await startIngress({gatewayPort:18789, deps});
  try {
    const response = await request(srv, 'POST', '/v1/chat/cancel', {
      body:JSON.stringify({user:'managed-project-stop'}),
      headers:{'Content-Type':'application/json'},
    });
    assert.equal(response.status, 200);
    assert.deepEqual(JSON.parse(response.body), {aborted:true});
  } finally { await new Promise(resolve => srv.close(resolve)); }
});

test("health fails closed when the Pixel gateway is unreachable", async () => {
  const deps = {
    fetch: async () => { throw new Error("offline"); },
    setTimeout,
    clearTimeout,
  };
  const srv = await startIngress({ gatewayPort: 18789, deps });
  try {
    const health = await request(srv, "GET", "/health");
    assert.equal(health.status, 503);
    assert.deepEqual(JSON.parse(health.body), { status: "unavailable" });
  } finally {
    await new Promise((resolve) => srv.close(resolve));
  }
});

// ---------------------------------------------------------------------------
// Request limit
// ---------------------------------------------------------------------------

test("rejects oversized request body with 413", async () => {
  const gw = await fakeGateway();
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const big = "x".repeat(2 * 1024 * 1024 + 10);
      const res = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ content: big }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(res.status, 413);
      // sanitized: does not echo body
      assert.ok(!res.body.includes("x".repeat(100)));
    } finally {
      await new Promise((r) => srv.close(r));
    }
  } finally {
    await new Promise((r) => gw.server.close(r));
  }
});

// ---------------------------------------------------------------------------
// Header stripping + forced model + hashed user + unknown field dropping
// ---------------------------------------------------------------------------

test("strips forbidden headers, forces model, hashes user, drops unknown fields", async () => {
  let captured = null;
  const gw = await fakeGateway({ onRequest: (c) => (captured = c) });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const chatId = "conversation-42";
      const res = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({
          model: "evil-model",
          messages: [{ role: "user", content: "hi" }],
          temperature: 0.7,
          top_p: 1,
          max_tokens: 100,
          stream: false,
          stop: ["\n"],
          tools: [{ type: "function", function: { name: "f" } }],
          tool_choice: "auto",
          response_format: { type: "json_object" },
          unknown_field: "SHOULD_NOT_APPEAR",
          metadata: { chat_id: chatId },
        }),
        headers: {
          Authorization: "Bearer inbound-token",
          Cookie: "session=secret",
          "X-Forwarded-For": "1.2.3.4",
          "x-openclaw-user": "evil",
          "Content-Type": "application/json",
        },
      });
      assert.equal(res.status, 200);
      assert.ok(captured, "gateway should have received a request");

      // Header stripping
      assert.equal(captured.headers.authorization, `Bearer ${TOKEN}`);
      assert.ok(!("cookie" in captured.headers), "cookie must be stripped");
      assert.ok(!("x-forwarded-for" in captured.headers), "x-forwarded-for stripped");
      assert.ok(!("x-openclaw-user" in captured.headers), "x-openclaw-user stripped");
      assert.ok(!("x-forwarded-proto" in captured.headers));

      // Forced model + dropped unknown field
      assert.equal(captured.body.model, "openclaw/default");
      assert.ok(!("unknown_field" in captured.body), "unknown field must be dropped");

      // Hashed user
      const digest = createHash("sha256").update(chatId).digest("hex");
      assert.equal(captured.body.user, `ods-${digest}`);
    } finally {
      await new Promise((r) => srv.close(r));
    }
  } finally {
    await new Promise((r) => gw.server.close(r));
  }
});

test("omits user when no session identifier supplied", () => {
  const out = buildOutgoing(
    { messages: [{ role: "user", content: "x" }], metadata: { unrelated: 1 } },
    computeSessionUser({ messages: [{ role: "user", content: "x" }] })
  );
  assert.ok(!("user" in out), "no user field when no session identifier");
});

test("rejects invalid body (bad types)", () => {
  assert.throws(() => buildOutgoing({ messages: "nope" }, null), /invalid/);
  assert.throws(() => buildOutgoing({ max_tokens: -1 }, null), /invalid/);
  assert.throws(() => buildOutgoing({ stream: "yes" }, null), /invalid/);
});

// ---------------------------------------------------------------------------
// Sanitized errors
// ---------------------------------------------------------------------------

test("returns sanitized JSON error for invalid JSON, never reflects upstream body", async () => {
  const gw = await fakeGateway();
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const res = await request(srv, "POST", "/v1/chat/completions", {
        body: "{not json",
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(res.status, 400);
      const parsed = JSON.parse(res.body);
      assert.ok(parsed.error && parsed.error.message);
    } finally {
      await new Promise((r) => srv.close(r));
    }
  } finally {
    await new Promise((r) => gw.server.close(r));
  }
});

// ---------------------------------------------------------------------------
// Streaming bounds
// ---------------------------------------------------------------------------

test("streaming client receives terminal SSE from a non-stream gateway completion", async () => {
  let captured = null;
  const gw = await fakeGateway({ onRequest: (c) => (captured = c) });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const res = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ stream: true, messages: [{ role: "user", content: "hi" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(res.status, 200);
      assert.equal(captured.headers.accept, "application/json");
      assert.equal(captured.body.stream, false);
      assert.ok(res.body.includes('"content":"ok"'));
      assert.ok(res.body.includes("[DONE]"));
    } finally {
      await new Promise((r) => srv.close(r));
    }
  } finally {
    await new Promise((r) => gw.server.close(r));
  }
});

test("non-stream response replaces a false success with host verification truth", async () => {
  let verificationRequest;
  const safeText = "Pixel could not complete this task because verification failed.";
  const gw = await fakeGateway({
    verification: { status: "failed", text: safeText },
    onVerificationRequest: (value) => (verificationRequest = value),
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "claim success" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      const completion = JSON.parse(response.body);
      assert.equal(completion.id, TEST_RUN_ID);
      assert.equal(completion.choices[0].message.content, safeText);
      assert.equal(completion.choices[0].finish_reason, "stop");
      assert.deepEqual(verificationRequest.body, { runId: TEST_RUN_ID });
      assert.equal(verificationRequest.headers.authorization, `Bearer ${TOKEN}`);
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("non-stream response releases authoritative text from passed Operations verification", async () => {
  const verifiedText =
    "Pixel verified these ODS host facts through structurally matched terminal Operations Broker receipts.";
  const gw = await fakeGateway({
    verification: { status: "passed", text: verifiedText },
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "report host facts" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      const completion = JSON.parse(response.body);
      assert.equal(completion.id, TEST_RUN_ID);
      assert.equal(completion.choices[0].message.content, verifiedText);
      assert.equal(completion.choices[0].finish_reason, "stop");
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("native JSON and SSE preserve task prose with explicitly scoped successful evidence", async () => {
  const prose = "The UTF-8 note was written and read back. The host observation is separate.";
  const evidence = "Verified hostname: test-host.";
  for (const stream of [false, true]) {
    let verificationRequest;
    const gw = await fakeGateway({ completionText: prose,
      verification: { status: "passed", text: evidence, deliveryMode: "append" },
      onVerificationRequest: value => { verificationRequest = value; } });
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ stream, messages: [{ role: "user", content: "complete the file and host work" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      const text = stream
        ? response.body.split("\n").filter(line => line.startsWith("data: ") && line !== "data: [DONE]")
          .map(line => JSON.parse(line.slice(6)).choices?.[0]?.delta?.content ?? "").join("")
        : JSON.parse(response.body).choices[0].message.content;
      assert.ok(text.startsWith(prose));
      assert.ok(text.includes(evidence));
      assert.match(text, /does not establish completion of other requested work/);
      assert.equal(text.split(evidence).length, 2);
      assert.deepEqual(verificationRequest.body, { runId: TEST_RUN_ID });
      if (stream) assert.ok(response.body.endsWith("data: [DONE]\n\n"));
    } finally {
      await new Promise(resolve => srv.close(resolve));
      await new Promise(resolve => gw.server.close(resolve));
    }
  }
});

test("append delivery metadata cannot weaken failed, pending, malformed or oversized verification", async () => {
  for (const verification of [
    { status: "failed", text: "Failed.", deliveryMode: "append" },
    { status: "pending", text: "Pending.", deliveryMode: "append" },
    { status: "none", deliveryMode: "append" },
    { status: "passed", deliveryMode: "append" },
    { status: "passed", text: "Evidence.", deliveryMode: "unverified" },
    { status: "passed", text: "x".repeat(32 * 1024 + 1), deliveryMode: "append" },
  ]) {
    const gw = await fakeGateway({ verification, completionText: "Everything succeeded." });
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "inspect host" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 502);
      assert.doesNotMatch(response.body, /Everything succeeded/);
    } finally {
      await new Promise(resolve => srv.close(resolve));
      await new Promise(resolve => gw.server.close(resolve));
    }
  }
});

test("native evidence composition avoids duplicate receipts and handles an empty model reply", async () => {
  const evidence = "Verified hostname: test-host.";
  const scoped = `${evidence}\nReceipt scope: the Operations evidence above does not establish completion of other requested work.`;
  for (const prose of ["", `Workspace work completed.\n\n${scoped}`]) {
    const gw = await fakeGateway({ completionText: prose,
      verification: { status: "passed", text: evidence, deliveryMode: "append" } });
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "inspect host" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      assert.equal(JSON.parse(response.body).choices[0].message.content, prose || evidence);
    } finally {
      await new Promise(resolve => srv.close(resolve));
      await new Promise(resolve => gw.server.close(resolve));
    }
  }
});

test("non-stream response removes only a guard-confirmed superseded wrapped exec warning", async () => {
  const staleWarning =
    "recovery_probe=passed\n\n⚠️ 🛠️ `/run/pixel-ods-control/cancellable-exec.sh " +
    "7a77c125fe1a5a4d…c26f647f11a8df9 " +
    "cHl0aG9uMyAtYyAncmFpc2UgU3lzdGVtRXhpdCg3KSc=` failed";
  const gw = await fakeGateway({
    verification: { status: "none", suppressStaleExecWarning: true },
    completionText: staleWarning,
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "recover" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      assert.equal(
        JSON.parse(response.body).choices[0].message.content,
        "recovery_probe=passed"
      );
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("superseded warning cleanup leaves near matches and unsignalled warnings intact", async () => {
  const warning =
    "still visible\n\n⚠️ 🛠️ `/run/pixel-ods-control/cancellable-exec.sh " +
    "7a77c125fe1a5a4d…c26f647f11a8df9 dHJ1ZQ==` failed";
  for (const variant of [
    { verification: { status: "none" }, completionText: warning },
    {
      verification: { status: "none", suppressStaleExecWarning: true },
      completionText: warning.replace("cancellable-exec.sh", "other-exec.sh"),
    },
  ]) {
    const gw = await fakeGateway(variant);
    try {
      const srv = await startIngress({ gatewayPort: gw.port });
      try {
        const response = await request(srv, "POST", "/v1/chat/completions", {
          body: JSON.stringify({ messages: [{ role: "user", content: "report" }] }),
          headers: { "Content-Type": "application/json" },
        });
        assert.equal(response.status, 200);
        assert.equal(
          JSON.parse(response.body).choices[0].message.content,
          variant.completionText
        );
      } finally {
        await new Promise((resolve) => srv.close(resolve));
      }
    } finally {
      await new Promise((resolve) => gw.server.close(resolve));
    }
  }
});

test("rejects stale exec warning suppression on a failed verification response", async () => {
  const gw = await fakeGateway({
    verification: {
      status: "failed",
      text: "Pixel could not verify the final command.",
      suppressStaleExecWarning: true,
    },
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "claim success" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 502);
      assert.equal(JSON.parse(response.body).error.message, "verification state unavailable");
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("streaming response releases a bounded broad Operations report above the legacy 2 KiB cap", async () => {
  const verifiedText = [
    "Pixel verified these ODS host facts through structurally matched terminal Operations Broker receipts.",
    "- Host evidence: " + "x".repeat(8 * 1024),
  ].join("\n");
  const gw = await fakeGateway({
    verification: { status: "passed", text: verifiedText },
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({
          stream: true,
          messages: [{ role: "user", content: "report broad host facts" }],
        }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      const frames = response.body
        .split(/\r?\n/)
        .filter((line) => line.startsWith("data: {") && line.endsWith("}"))
        .map((line) => JSON.parse(line.slice("data: ".length)));
      assert.equal(frames[1].choices[0].delta.content, verifiedText);
      assert.equal(response.body.includes('"content":"ok"'), false);
      assert.ok(response.body.includes("[DONE]"));
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("SSE releases content-free task observations only in the matching terminal frame", async () => {
  const task = {schemaVersion:1,runId:TEST_RUN_ID,startedAt:'2026-09-08T20:00:00.000Z',finishedAt:'2026-09-08T20:00:02.000Z',
    state:'completed',calls:1,failures:0,blocked:0,truncated:false,activities:[{kind:'read',calls:1,failures:0,blocked:0}]};
  for (const invalid of [false,true]) {
    const gw = await fakeGateway({verification:{status:'none',task:{...task,...(invalid ? {runId:TEST_RUN_ID.replace('11111111','aaaaaaaa')} : {})}}});
    const srv = await startIngress({gatewayPort:gw.port});
    try {
      const response = await request(srv,'POST','/v1/chat/completions',{body:JSON.stringify({stream:true,messages:[{role:'user',content:'test'}]}),headers:{'Content-Type':'application/json'}});
      if (invalid) { assert.match(response.body,/upstream stream failed/); assert.doesNotMatch(response.body,/pixel_task|activities|\"content\":\"ok\"/); }
      else {
        assert.equal(response.status,200);
        const frames = response.body.split('\n').filter(line=>line.startsWith('data: {')).map(line=>JSON.parse(line.slice(6)));
        assert.equal(frames.filter(frame=>frame.pixel_task).length,1);
        assert.deepEqual(frames.at(-1).pixel_task,task);
        assert.equal(frames.at(-1).choices[0].finish_reason,'stop');
      }
    } finally { await new Promise(resolve=>srv.close(resolve)); await new Promise(resolve=>gw.server.close(resolve)); }
  }
});

test('terminal SSE preserves v4 verified project associations without a web publication',async()=>{
  const stamp='2026-09-16T10:00:00.000Z';
  const project={schemaVersion:1,kind:'ods-workspace-project',relativeDirectory:'Playground/http-method-smoke',observedAt:stamp};
  const task={schemaVersion:4,runId:TEST_RUN_ID,startedAt:stamp,finishedAt:stamp,state:'completed',calls:0,failures:0,blocked:0,truncated:false,activities:[],events:[],context:null,goal:null,projects:[project]};
  const gw=await fakeGateway({verification:{status:'none',task}});
  const srv=await startIngress({gatewayPort:gw.port});
  try {
    const response=await request(srv,'POST','/v1/chat/completions',{body:JSON.stringify({stream:true,messages:[{role:'user',content:'test'}]}),headers:{'Content-Type':'application/json'}});
    assert.equal(response.status,200);
    const frames=response.body.split('\n').filter(line=>line.startsWith('data: {')).map(line=>JSON.parse(line.slice(6)));
    assert.equal(frames.filter(frame=>frame.pixel_task).length,1);
    assert.deepEqual(frames.at(-1).pixel_task,task);
    assert.equal(frames.at(-1).choices[0].finish_reason,'stop');
    assert.equal(frames.at(-1).pixel,undefined);
  } finally {await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));}
});

test('question cards come only from validated pending verification on the terminal frame', async () => {
  const questions=[{id:'style',question:'Qual estilo?',options:['Clean','Colorido']}];
  for (const verification of [
    {status:'pending',text:'Qual estilo?',questions},
    {status:'passed',text:'Qual estilo?',questions},
    {status:'pending',text:'Qual estilo?',questions:[{...questions[0],options:['Only']}]}]) {
    const valid=verification.status==='pending' && verification.questions===questions;
    const gw=await fakeGateway({verification,completionText:'I chose for you.'});
    const srv=await startIngress({gatewayPort:gw.port});
    try {
      const response=await request(srv,'POST','/v1/chat/completions',{body:JSON.stringify({stream:true,messages:[{role:'user',content:'Ask first'}]}),headers:{'Content-Type':'application/json'}});
      assert.doesNotMatch(response.body,/I chose for you/);
      if (!valid) { assert.match(response.body,/upstream stream failed/); assert.doesNotMatch(response.body,/pixel_questions/); }
      else {
        const frames=response.body.split('\n').filter(line=>line.startsWith('data: {')).map(line=>JSON.parse(line.slice(6)));
        assert.equal(frames.filter(frame=>frame.pixel_questions).length,1);
        assert.deepEqual(frames.at(-1).pixel_questions,{schemaVersion:1,questions});
        assert.equal(frames.at(-1).choices[0].finish_reason,'stop');
      }
    } finally { await new Promise(resolve=>srv.close(resolve)); await new Promise(resolve=>gw.server.close(resolve)); }
  }
});

test("Operations verification text above the bounded 32 KiB cap remains fail-closed", async () => {
  const gw = await fakeGateway({
    verification: { status: "passed", text: "x".repeat(32 * 1024 + 1) },
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "report host facts" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 502);
      assert.equal(JSON.parse(response.body).error.message, "verification state unavailable");
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("passed Operations verification remains fail-closed for extra fields", async () => {
  const gw = await fakeGateway({
    verification: {
      status: "passed",
      text: "Verified host facts.",
      untrusted: "must not cross the ingress boundary",
    },
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "report host facts" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 502);
      assert.deepEqual(JSON.parse(response.body), {
        error: {
          message: "verification state unavailable",
          type: "pixel_ingress_error",
        },
      });
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("streaming response is buffered and replaced before false content is released", async () => {
  const safeText = "Pixel stopped before verification reached a terminal result.";
  const gw = await fakeGateway({ verification: { status: "pending", text: safeText } });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ stream: true, messages: [{ role: "user", content: "hi" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      assert.equal(response.headers["content-type"], "text/event-stream");
      assert.ok(response.body.includes(safeText));
      assert.equal(response.body.includes('"content":"a"'), false);
      assert.ok(response.body.includes("[DONE]"));
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("streaming response exposes only the host-authoritative clean-context recovery marker", async () => {
  const safeText =
    "Pixel did not submit the requested host or Operations work through the isolated Operations Broker.";
  const gw = await fakeGateway({
    verification: {
      status: "failed",
      text: safeText,
      code: "operations-unavailable-zero-submissions",
    },
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({
          stream: true,
          messages: [{ role: "user", content: "inspect ODS" }],
        }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      assert.ok(response.body.includes(safeText));
      assert.ok(response.body.includes(
        '\"pixel\":{\"schemaVersion\":1,\"recovery\":\"clean-context\",\"reason\":\"operations-unavailable-zero-submissions\"}'
      ));
      assert.equal(response.body.includes('\"content\":\"ok\"'), false);
      assert.ok(response.body.includes("[DONE]"));
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("streaming response exposes only a strictly verified workspace preview marker", async () => {
  const sha256 = "a".repeat(64);
  const siteId = `site-${sha256.slice(0, 24)}`;
  const preview = {
    schemaVersion: 1,
    kind: "ods-pixel-workspace-preview",
    relativeDirectory: "demo-website",
    siteId,
    port: 9437,
    url: `http://${siteId}.localhost:9437/${siteId}/`,
    files: 3,
    bytes: 4096,
    sha256,
    entrySha256: "b".repeat(64),
  };
  const safeText = "Pixel published and independently read back the static website.";
  const gw = await fakeGateway({
    verification: { status: "passed", text: safeText, preview },
  });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({
          stream: true,
          messages: [{ role: "user", content: "build and show a website" }],
        }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 200);
      const frames = response.body
        .split(/\r?\n/)
        .filter((line) => line.startsWith("data: {") && line.endsWith("}"))
        .map((line) => JSON.parse(line.slice("data: ".length)));
      assert.equal(frames[1].choices[0].delta.content, safeText);
      assert.deepEqual(frames.at(-1).pixel, { schemaVersion: 1, preview });
      assert.equal(frames.at(-1).choices[0].finish_reason, "stop");
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test("workspace preview metadata fails closed for an unverified URL or extra field", async () => {
  const sha256 = "a".repeat(64);
  const siteId = `site-${sha256.slice(0, 24)}`;
  const base = {
    schemaVersion: 1,
    kind: "ods-pixel-workspace-preview",
    relativeDirectory: "demo-website",
    siteId,
    port: 9437,
    url: `http://${siteId}.localhost:9437/${siteId}/`,
    files: 3,
    bytes: 4096,
    sha256,
    entrySha256: "b".repeat(64),
  };
  for (const preview of [
    { ...base, url: "https://attacker.example/" },
    { ...base, modelClaim: true },
    { ...base, relativeDirectory: "../outside" },
    {
      ...base,
      siteId: "site-0123456789abcdef01234567",
      url: "http://site-0123456789abcdef01234567.localhost:9437/site-0123456789abcdef01234567/",
    },
  ]) {
    const gw = await fakeGateway({
      verification: { status: "passed", text: "untrusted", preview },
    });
    try {
      const srv = await startIngress({ gatewayPort: gw.port });
      try {
        const response = await request(srv, "POST", "/v1/chat/completions", {
          body: JSON.stringify({ messages: [{ role: "user", content: "show it" }] }),
          headers: { "Content-Type": "application/json" },
        });
        assert.equal(response.status, 502);
        assert.equal(JSON.parse(response.body).error.message, "verification state unavailable");
      } finally {
        await new Promise((resolve) => srv.close(resolve));
      }
    } finally {
      await new Promise((resolve) => gw.server.close(resolve));
    }
  }
  const gw = await fakeGateway({ verification: { status: "passed", preview: base } });
  try {
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "show it" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 502);
    } finally {
      await new Promise((resolve) => srv.close(resolve));
    }
  } finally {
    await new Promise((resolve) => gw.server.close(resolve));
  }
});

test('source snapshot receipt survives authenticated delivery and rejects foreign project metadata', async()=>{
  const sha256='a'.repeat(64),siteId='site-'+sha256.slice(0,24);
  const source={schemaVersion:1,sourceId:'source-'+'c'.repeat(24),sha256:'c'.repeat(64),relativeDirectory:'demo',files:2,bytes:80,omitted:{directories:1,files:0,sensitiveFiles:0}};
  const base={schemaVersion:1,kind:'ods-pixel-workspace-preview',relativeDirectory:'demo/dist',siteId,port:9437,url:`http://${siteId}.localhost:9437/${siteId}/`,files:2,bytes:100,sha256,entrySha256:'b'.repeat(64)};
  for(const candidate of [source,{...source,relativeDirectory:'foreign'},{...source,sourceId:'source-'+'d'.repeat(24)},{...source,omitted:{files:0}}]) {
    const gw=await fakeGateway({verification:{status:'passed',text:'Captured source and built preview.',preview:{...base,source:candidate}}});
    const srv=await startIngress({gatewayPort:gw.port});
    try {
      const response=await request(srv,'POST','/v1/chat/completions',{body:JSON.stringify({stream:true,messages:[{role:'user',content:'Build project'}]}),headers:{'Content-Type':'application/json'}});
      if(candidate===source){assert.equal(response.status,200);assert.match(response.body,/"sourceId":"source-cccc/);}
      else {assert.match(response.body,/upstream stream failed/);assert.doesNotMatch(response.body,/"sourceId"/);}
    }finally{await new Promise(resolve=>srv.close(resolve));await new Promise(resolve=>gw.server.close(resolve));}
  }
});

test("preview delivery preserves useful answers and retains stale snapshots without false success", async () => {
  const sha256 = "a".repeat(64), siteId = `site-${sha256.slice(0, 24)}`;
  const preview = { schemaVersion: 1, kind: "ods-pixel-workspace-preview", relativeDirectory: "orbit-garden",
    siteId, port: 9437, url: `http://${siteId}.localhost:9437/${siteId}/`, files: 4, bytes: 4096,
    sha256, entrySha256: "b".repeat(64) };
  const prose = "Click Export SVG to save the current scene.";
  const scope = "Publication scope: this receipt verifies the published snapshot, not functional behavior or completion of other requested work.";
  for (const stream of [false, true]) {
    for (const status of ["passed", "failed"]) {
      const text = status === "passed" ? "Your preview is ready." : "Your last published preview is available; current files are unverified.";
      for (const completionText of status === "passed" ? [prose, "", `${prose}\n\n${text}\n${scope}`] : ["All new changes were verified."]) {
        const verification = { status, text, preview, ...(status === "passed" ? { deliveryMode: "append" } : {}) };
        const gw = await fakeGateway({ verification, completionText });
        const srv = await startIngress({ gatewayPort: gw.port });
        try {
          const response = await request(srv, "POST", "/v1/chat/completions", {
            body: JSON.stringify({ stream, messages: [{ role: "user", content: "Open the app and explain export" }] }),
            headers: { "Content-Type": "application/json" },
          });
          assert.equal(response.status, 200);
          const frames = stream ? response.body.split("\n").filter(line => line.startsWith("data: {")).map(line => JSON.parse(line.slice(6))) : [];
          const delivered = stream ? frames.map(frame => frame.choices?.[0]?.delta?.content ?? "").join("") : JSON.parse(response.body).choices[0].message.content;
          assert.equal(delivered, status === "passed" && completionText ? `${prose}\n\n${text}\n${scope}` : text);
          if (stream) { assert.deepEqual(frames.at(-1).pixel, { schemaVersion: 1, preview }); assert.deepEqual(frames.at(-1).pixel_outcome, { schemaVersion: 1, status }); }
        } finally {
          await new Promise(resolve => srv.close(resolve));
          await new Promise(resolve => gw.server.close(resolve));
        }
      }
    }
  }
  for (const verification of [
    { status: "failed", text: "Stale.", preview: { ...preview, url: "https://attacker.example/" } },
    { status: "failed", text: "Stale.", preview, deliveryMode: "append" },
    { status: "failed", text: "Stale.", preview, code: "operations-unavailable-zero-submissions" },
    { status: "none", preview },
    { status: "pending", text: "Pending.", preview },
  ]) {
    const gw = await fakeGateway({ verification });
    const srv = await startIngress({ gatewayPort: gw.port });
    try {
      const response = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ messages: [{ role: "user", content: "show it" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(response.status, 502);
    } finally {
      await new Promise(resolve => srv.close(resolve));
      await new Promise(resolve => gw.server.close(resolve));
    }
  }
});

test("rejects recovery metadata outside the exact failed zero-submission contract", async () => {
  const invalid = [
    { status: "passed", code: "operations-unavailable-zero-submissions" },
    { status: "failed", text: "safe", code: "unknown" },
    {
      status: "failed",
      text: "safe",
      code: "operations-unavailable-zero-submissions",
      extra: true,
    },
  ];
  for (const verification of invalid) {
    const gw = await fakeGateway({ verification });
    try {
      const srv = await startIngress({ gatewayPort: gw.port });
      try {
        const response = await request(srv, "POST", "/v1/chat/completions", {
          body: JSON.stringify({ messages: [{ role: "user", content: "inspect ODS" }] }),
          headers: { "Content-Type": "application/json" },
        });
        assert.equal(response.status, 502);
        assert.equal(JSON.parse(response.body).error.message, "verification state unavailable");
      } finally {
        await new Promise((resolve) => srv.close(resolve));
      }
    } finally {
      await new Promise((resolve) => gw.server.close(resolve));
    }
  }
});

test("closing a silent downstream stream closes the active gateway transport", async () => {
  let markUpstreamClosed;
  const upstreamClosed = new Promise((resolve) => {
    markUpstreamClosed = resolve;
  });
  const upstream = http.createServer((req, res) => {
    req.resume();
    req.on("end", () => {
      res.writeHead(200, { "Content-Type": "application/json" });
      res.flushHeaders();
      res.on("close", () => markUpstreamClosed(!res.writableEnded));
    });
  });
  await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve));
  const ingress = await startIngress({ gatewayPort: upstream.address().port });
  try {
    await new Promise((resolve, reject) => {
      const client = http.request(
        {
          socketPath: ingress.address(),
          method: "POST",
          path: "/v1/chat/completions",
          headers: { "Content-Type": "application/json" },
        },
        (response) => {
          response.once("error", () => {});
          response.destroy();
          resolve();
        }
      );
      client.once("error", (error) => {
        if (error.code === "ECONNRESET") resolve();
        else reject(error);
      });
      client.end(JSON.stringify({
        stream: true,
        messages: [{ role: "user", content: "cancel me" }],
      }));
    });
    assert.equal(
      await Promise.race([
        upstreamClosed,
        new Promise((resolve) => setTimeout(() => resolve(false), 2000)),
      ]),
      true
    );
  } finally {
    await new Promise((resolve) => ingress.close(resolve));
    await new Promise((resolve) => upstream.close(resolve));
  }
});

test("stream headers expose cancellation before gateway response headers exist", async () => {
  let markUpstreamClosed;
  const upstreamClosed = new Promise((resolve) => {
    markUpstreamClosed = resolve;
  });
  const upstream = http.createServer((req, res) => {
    req.resume();
    res.on("close", () => markUpstreamClosed(!res.writableEnded));
    // Deliberately never send response headers. The downstream SSE response
    // must still become cancellable while OpenClaw is starting the model turn.
  });
  await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve));
  const ingress = await startIngress({ gatewayPort: upstream.address().port });
  try {
    await new Promise((resolve, reject) => {
      const client = http.request(
        {
          socketPath: ingress.address(),
          method: "POST",
          path: "/v1/chat/completions",
          headers: { "Content-Type": "application/json" },
        },
        (response) => {
          assert.equal(response.statusCode, 200);
          assert.match(String(response.headers["content-type"]), /^text\/event-stream/);
          response.once("error", () => {});
          response.destroy();
          resolve();
        }
      );
      client.once("error", (error) => {
        if (error.code === "ECONNRESET") resolve();
        else reject(error);
      });
      client.end(JSON.stringify({
        stream: true,
        messages: [{ role: "user", content: "cancel before headers" }],
      }));
    });
    assert.equal(
      await Promise.race([
        upstreamClosed,
        new Promise((resolve) => setTimeout(() => resolve(false), 2000)),
      ]),
      true
    );
  } finally {
    await new Promise((resolve) => ingress.close(resolve));
    await new Promise((resolve) => upstream.close(resolve));
  }
});

test("core gateway transport preserves a delayed response body", async () => {
  const server = http.createServer((_req, res) => {
    res.writeHead(200, { "Content-Type": "text/event-stream" });
    res.flushHeaders();
    res.write('data: {"choices":[{"delta":{"role":"assistant"}}]}\n\n');
    setTimeout(() => res.end("data: [DONE]\n\n"), 250);
  });
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  try {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 2000);
    try {
      const response = await gatewayFetch(
        `http://127.0.0.1:${server.address().port}/v1/chat/completions`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: "{}",
          signal: controller.signal,
        }
      );
      assert.equal(response.status, 200);
      assert.equal(response.headers.get("content-type"), "text/event-stream");
      const body = await new Response(response.body).text();
      assert.ok(body.includes("[DONE]"));
    } finally {
      clearTimeout(timer);
    }
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
});

test("chat waits for delayed gateway headers after the loopback connection succeeds", async () => {
  const armedTimeouts = [];
  const deps = {
    fetch: (url, options) =>
      new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
          if (url.endsWith('/pixel-ods/subagent-delivery')) {
            resolve(new Response(JSON.stringify({schemaVersion:1,kind:'ods-subagent-delivery',runId:TEST_RUN_ID,status:'not-delegated'}),
              {status:200,headers:{'Content-Type':'application/json'}}));return;
          }
          if (url.endsWith("/pixel-ods/verification")) {
            resolve(
              new Response(JSON.stringify({ status: "none" }), {
                status: 200,
                headers: { "Content-Type": "application/json" },
              })
            );
            return;
          }
          resolve(
            new Response(
              JSON.stringify({ id: TEST_RUN_ID, choices: [{ message: { content: "ok" } }] }),
              { status: 200, headers: { "Content-Type": "application/json" } }
            )
          );
        }, 40);
        options.signal.addEventListener("abort", () => {
          clearTimeout(timer);
          reject(new Error("aborted before delayed headers"));
        }, { once: true });
      }),
    setTimeout: (callback, milliseconds) => {
      armedTimeouts.push(milliseconds);
      if (milliseconds < 100000) return setTimeout(callback, 5);
      return { longBudget: true };
    },
    clearTimeout: (timer) => {
      if (timer && !timer.longBudget) clearTimeout(timer);
    },
  };
  const srv = await startIngress({ gatewayPort: 18789, deps });
  try {
    const response = await request(srv, "POST", "/v1/chat/completions", {
      body: JSON.stringify({ messages: [{ role: "user", content: "slow reply" }] }),
      headers: { "Content-Type": "application/json" },
    });
    assert.equal(response.status, 200);
    assert.deepEqual(armedTimeouts, [1920000]);
  } finally {
    await new Promise((resolve) => srv.close(resolve));
  }
});

test("non-stream response is bounded and sanitized on failure", async () => {
  // Gateway that returns a huge body => ingress caps at 2 MiB and returns
  // a generic 502 rather than reflecting it.
  const server = http.createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end("x".repeat(3 * 1024 * 1024));
  });
  await new Promise((r) => server.listen(0, "127.0.0.1", r));
  const gwPort = server.address().port;
  try {
    const srv = await startIngress({ gatewayPort: gwPort });
    try {
      const res = await request(srv, "POST", "/v1/chat/completions", {
        body: JSON.stringify({ stream: false, messages: [{ role: "user", content: "hi" }] }),
        headers: { "Content-Type": "application/json" },
      });
      assert.equal(res.status, 502);
      const parsed = JSON.parse(res.body);
      assert.ok(parsed.error && parsed.error.message, "sanitized generic error");
      assert.ok(!parsed.error.message.includes("xxxx"), "must not reflect upstream body");
    } finally {
      await new Promise((r) => srv.close(r));
    }
  } finally {
    await new Promise((r) => server.close(r));
  }
});

// ---------------------------------------------------------------------------
// UDS permissions
// ---------------------------------------------------------------------------

test("start creates a 0660 socket with the requested gid and closes without exiting", async () => {
  const gid = process.getgid();
  const tokenFile = path.join(DIR, "start-token.env");
  const socketPath = path.join(DIR, "permission.sock");
  const statusFile = path.join(DIR, "permission-status.json");
  fs.writeFileSync(tokenFile, `PIXEL_GATEWAY_TOKEN=${TOKEN}\n`, { mode: 0o600 });
  const deps = {
    fetch: async () => ({ status: 503, body: { cancel: async () => {} } }),
    execFile: (_command, _args, _options, callback) => callback(new Error("unavailable")),
  };
  const handle = await start({
    socketPath,
    gatewayTokenFile: tokenFile,
    gatewayPort: 18999,
    statusFile,
    statusIntervalMs: 60000,
    ingressGid: gid,
    odsVersion: "2.6.0",
  }, { deps, euid: EUID });
  const socketStat = fs.statSync(socketPath);
  assert.equal(socketStat.mode & 0o777, 0o660);
  assert.equal(socketStat.gid, gid);
  await handle.close();
  assert.equal(fs.existsSync(socketPath), false);
});

// ---------------------------------------------------------------------------
// Status projection: fixed docker execFile (mocked) + safe projection
// ---------------------------------------------------------------------------

test("status projection uses fixed docker execFile and allows only allowlisted names", async () => {
  const fakeDocker = (cmd, args, opts, callback) => {
    assert.equal(cmd, "docker");
    assert.deepEqual(args, ["ps", "--all", "--format", "{{json .}}"]);
    assert.ok(opts.timeout > 0, "must have explicit timeout");
    const lines = [
      { Names: "ods-pixel-edge", Status: "Up 5 minutes" },
      { Names: "/evil-container", Status: "Up 1 day (healthy)" },
      { Names: "ods-open-webui", Status: "Up (healthy)" },
      { Names: "ods-dashboard", Status: "Up (unhealthy)" },
      { Names: "ods-qdrant", Status: "Up (health: starting)" },
      { Names: "ods-n8n", Status: "Exited (0)" },
    ].map((x) => JSON.stringify(x));
    callback(null, lines.join("\n") + "\n", "");
  };
  const apps = await dockerApps({ execFile: fakeDocker });
  assert.deepEqual(apps, [
    { name: "ods-dashboard", status: "unhealthy" },
    { name: "ods-n8n", status: "stopped" },
    { name: "ods-open-webui", status: "healthy" },
    { name: "ods-pixel-edge", status: "running" },
    { name: "ods-qdrant", status: "starting" },
  ]);
  assert.equal(JSON.stringify(apps).includes("evil"), false);
  assert.equal(JSON.stringify(apps).includes("5 minutes"), false);
});

test("runtime projection uses a fixed inspect command and returns only model basename and context", async () => {
  const fakeDocker = (cmd, args, opts, callback) => {
    assert.equal(cmd, "docker");
    assert.deepEqual(args, [
      "inspect", "ods-llama-server", "--format", "{{json .Config.Cmd}}",
    ]);
    assert.ok(opts.timeout > 0, "must have explicit timeout");
    callback(
      null,
      JSON.stringify(["--model", "/models/Qwen3.5-9B-Q4_K_M.gguf", "--ctx-size", "32768"]),
      ""
    );
  };
  assert.deepEqual(await dockerRuntime({ execFile: fakeDocker }), {
    model: "Qwen3.5-9B-Q4_K_M.gguf",
    context_length: 32768,
  });
});

test("runtime projection rejects paths, malformed contexts, and non-JSON output", async () => {
  for (const command of [
    ["--model", "/private/model.gguf", "--ctx-size", "32768"],
    ["--model", "/models/../secret", "--ctx-size", "32768"],
    ["--model", "/models/model.gguf", "--ctx-size", "0"],
    "not-json",
  ]) {
    const fakeDocker = (_cmd, _args, _opts, callback) => {
      const output = command === "not-json" ? command : JSON.stringify(command);
      callback(null, output, "");
    };
    assert.equal(await dockerRuntime({ execFile: fakeDocker }), null);
  }
});

// LLM_BACKEND=vllm (docker-compose.vllm.yml): the command Compose builds
// for ods-vllm-server, catalog VLLM_ARGS included.
const VLLM_COMMAND = [
  "--model", "/model", "--served-model-name", "GLM-5.3-Flash-NVFP4", "--host", "0.0.0.0",
  "--port", "8000", "--gpu-memory-utilization", "0.90", "--max-model-len", "131072",
  "--kv-cache-dtype", "fp8", "--speculative-config.method=mtp",
];

test("vLLM runtime projection reads the served name and context from ods-vllm-server", async () => {
  const fakeDocker = (cmd, args, opts, callback) => {
    assert.equal(cmd, "docker");
    assert.deepEqual(args, ["inspect", "ods-vllm-server", "--format", "{{json .Config.Cmd}}"]);
    assert.ok(opts.timeout > 0, "must have explicit timeout");
    callback(null, JSON.stringify(VLLM_COMMAND), "");
  };
  assert.deepEqual(await dockerVllmRuntime({ execFile: fakeDocker }), {
    model: "GLM-5.3-Flash-NVFP4",
    context_length: 131072,
  });
  for (const command of [
    VLLM_COMMAND.filter((item) => item !== "--max-model-len" && item !== "131072"),
    VLLM_COMMAND.map((item) => (item === "131072" ? "2048" : item)),
    VLLM_COMMAND.map((item) => (item === "GLM-5.3-Flash-NVFP4" ? "../secret" : item)),
    ["--model", "/model", "--served-model-name=Joined-Name", "--max-model-len=65536"],
    "not-json",
  ]) {
    const reply = (_cmd, _args, _opts, callback) => {
      callback(null, command === "not-json" ? command : JSON.stringify(command), "");
    };
    const expected = Array.isArray(command) && command.includes("--max-model-len=65536")
      ? { model: "Joined-Name", context_length: 65536 }
      : null;
    assert.deepEqual(await dockerVllmRuntime({ execFile: reply }), expected);
  }
});

test("status on a vLLM install lists the engine and reads its runtime, not a stale llama-server", async () => {
  const statusFile = path.join(DIR, "vllm-runtime-status.json");
  const inspected = [];
  const fakeDocker = (_cmd, args, _opts, callback) => {
    if (args[0] === "ps") {
      callback(null, [
        JSON.stringify({ Names: "ods-vllm-server", Status: "Up 4 minutes (health: starting)" }),
        // An earlier llama-server install left its container behind, stopped.
        JSON.stringify({ Names: "ods-llama-server", State: "exited", Status: "Exited (0) 2 days ago" }),
        "",
      ].join("\n"), "");
      return;
    }
    if (args[0] === "exec") {
      callback(new Error("model-router state unavailable"));
      return;
    }
    inspected.push(args[1]);
    callback(null, JSON.stringify(args[1] === "ods-vllm-server" ? VLLM_COMMAND
      : ["--model", "/models/Stale.gguf", "--ctx-size", "32768"]), "");
  };
  const projection = await writeStatus(true, 18999, statusFile, "2.6.0", {
    fetch: async () => ({ status: 200, body: { cancel: async () => {} } }),
    execFile: fakeDocker,
    setTimeout,
    clearTimeout,
  });
  assert.deepEqual(projection.apps, [
    { name: "ods-llama-server", status: "stopped" },
    { name: "ods-vllm-server", status: "starting" },
  ]);
  assert.deepEqual(projection.runtime, { model: "GLM-5.3-Flash-NVFP4", context_length: 131072 });
  assert.deepEqual(inspected, ["ods-vllm-server"]);
});

test("router runtime projection returns the exact active stable-alias target", async () => {
  const fakeDocker = (cmd, args, opts, callback) => {
    assert.equal(cmd, "docker");
    assert.deepEqual(args, [
      "exec", "ods-model-router", "cat", "/state/model-state.json",
    ]);
    assert.ok(opts.timeout > 0, "must have explicit timeout");
    callback(null, JSON.stringify({
      schema: "ods.model-state.v1",
      active: {
        routeSeq: 4,
        runtimeModelId: "Qwen3.5-2B-Q4_K_M.gguf",
        publicModel: "ods/current",
        contextLength: 65536,
      },
    }), "");
  };
  assert.deepEqual(await dockerRouterRuntime({ execFile: fakeDocker }), {
    model: "Qwen3.5-2B-Q4_K_M.gguf",
    context_length: 65536,
  });
});

test("router runtime projection rejects malformed or inactive state", async () => {
  for (const state of [
    { schema: "wrong", active: {} },
    { schema: "ods.model-state.v1", active: null },
    { schema: "ods.model-state.v1", active: { routeSeq: 1, runtimeModelId: "../secret", publicModel: "ods/current", contextLength: 65536 } },
    { schema: "ods.model-state.v1", active: { routeSeq: 1, runtimeModelId: "model", publicModel: "other", contextLength: 65536 } },
    "not-json",
  ]) {
    const fakeDocker = (_cmd, _args, _opts, callback) => {
      callback(null, state === "not-json" ? state : JSON.stringify(state), "");
    };
    assert.equal(await dockerRouterRuntime({ execFile: fakeDocker }), null);
  }
});

test("status keeps app health when optional runtime inspection is unavailable", async () => {
  const statusFile = path.join(DIR, "runtime-unavailable-status.json");
  const fakeDocker = (_cmd, args, _opts, callback) => {
    if (args[0] === "ps") {
      callback(null, `${JSON.stringify({ Names: "ods-dashboard", Status: "Up (healthy)" })}\n`, "");
      return;
    }
    callback(new Error("runtime unavailable"));
  };
  const projection = await writeStatus(
    true,
    18999,
    statusFile,
    "2.6.0",
    {
      fetch: async () => ({ status: 503, body: { cancel: async () => {} } }),
      execFile: fakeDocker,
      setTimeout,
      clearTimeout,
    }
  );
  assert.equal(projection.schema_version, 2);
  assert.equal(projection.ods_version, "2.6.0");
  assert.equal(projection.docker, "ok");
  assert.equal(projection.online_apps, 1);
  assert.equal(projection.app_ports.n8n, 5678);
  assert.equal(projection.runtime, null);
  assert.deepEqual(projection.apps, [{ name: "ods-dashboard", status: "healthy" }]);
});

test("status prefers the selected Pixel runtime over the local Docker model", async () => {
  const statusFile = path.join(DIR, "configured-runtime-status.json");
  const fakeDocker = (_cmd, args, _opts, callback) => {
    if (args[0] === "ps") {
      callback(null, `${JSON.stringify({ Names: "ods-dashboard", Status: "Up (healthy)" })}\n`, "");
      return;
    }
    callback(
      null,
      JSON.stringify(["--model", "/models/local-model.gguf", "--ctx-size", "32768"]),
      ""
    );
  };
  const projection = await writeStatus(
    true,
    18999,
    statusFile,
    "2.6.0",
    {
      fetch: async () => ({ status: 200, body: { cancel: async () => {} } }),
      execFile: fakeDocker,
      setTimeout,
      clearTimeout,
    },
    configFromEnv({}).appPorts,
    { model: "org/model:variant", context_length: 2_000_000 }
  );
  assert.deepEqual(projection.runtime, {
    model: "org/model:variant",
    context_length: 2_000_000,
  });
});

test("status uses the active model-router target when authoritative Pixel metadata is unavailable", async () => {
  const statusFile = path.join(DIR, "router-runtime-status.json");
  const fakeDocker = (_cmd, args, _opts, callback) => {
    if (args[0] === "ps") {
      callback(null, `${JSON.stringify({ Names: "ods-dashboard", Status: "Up (healthy)" })}\n`, "");
      return;
    }
    if (args[0] === "exec") {
      callback(null, JSON.stringify({
        schema: "ods.model-state.v1",
        active: {
          routeSeq: 4,
          runtimeModelId: "Qwen3.5-2B-Q4_K_M.gguf",
          publicModel: "ods/current",
          contextLength: 65536,
        },
      }), "");
      return;
    }
    callback(new Error("unexpected fallback inspection"));
  };
  const projection = await writeStatus(
    true,
    18999,
    statusFile,
    "2.6.0",
    {
      fetch: async () => ({ status: 200, body: { cancel: async () => {} } }),
      execFile: fakeDocker,
      setTimeout,
      clearTimeout,
    },
    configFromEnv({}).appPorts
  );
  assert.deepEqual(projection.runtime, {
    model: "Qwen3.5-2B-Q4_K_M.gguf",
    context_length: 65536,
  });
});

test("status keeps the authoritative Pixel runtime during a transactional router-state lag", async () => {
  const statusFile = path.join(DIR, "transactional-runtime-status.json");
  const fakeDocker = (_cmd, args, _opts, callback) => {
    if (args[0] === "ps") {
      callback(null, `${JSON.stringify({ Names: "ods-dashboard", Status: "Up (healthy)" })}\n`, "");
      return;
    }
    if (args[0] === "exec") {
      callback(null, JSON.stringify({
        schema: "ods.model-state.v1",
        active: {
          routeSeq: 15,
          runtimeModelId: "Qwen3.5-9B-Q4_K_M.gguf",
          publicModel: "ods/current",
          contextLength: 32768,
        },
      }), "");
      return;
    }
    callback(new Error("authoritative Pixel metadata must avoid stale router inspection"));
  };
  const projection = await writeStatus(
    true,
    18999,
    statusFile,
    "2.6.0",
    {
      fetch: async () => ({ status: 200, body: { cancel: async () => {} } }),
      execFile: fakeDocker,
      setTimeout,
      clearTimeout,
    },
    configFromEnv({}).appPorts,
    { model: "Qwen3.5-2B-Q4_K_M.gguf", context_length: 8192 }
  );
  assert.deepEqual(projection.runtime, {
    model: "Qwen3.5-2B-Q4_K_M.gguf",
    context_length: 8192,
  });
});

test("start retains a selected remote runtime when Docker is unavailable", async () => {
  const configFile = path.join(DIR, "remote-start-openclaw.json");
  fs.writeFileSync(configFile, `${JSON.stringify({
    gateway: { auth: { token: TOKEN } },
    agents: { list: [{ id: "pixel", model: "ods-gateway/ods/current" }] },
    models: { providers: { "ods-gateway": { models: [{
      id: "ods/current", name: "ODS Current (remote/model)",
      contextWindow: 131072, maxTokens: 16384, reasoning: false,
    }] } } },
  })}\n`, { mode: 0o600 });
  const sock = path.join(DIR, "remote-start.sock");
  const statusFile = path.join(DIR, "remote-start-status.json");
  const h = await start({
    socketPath: sock,
    gatewayTokenFile: configFile,
    gatewayPort: 18999,
    statusFile,
    statusIntervalMs: 60000,
    ingressGid: null,
    odsVersion: "2.6.0",
  }, {
    deps: {
      fetch: async () => ({ status: 503, body: { cancel: async () => {} } }),
      execFile: (_command, _args, _options, callback) => callback(new Error("docker unavailable")),
    },
    euid: EUID,
  });
  try {
    const projection = JSON.parse(fs.readFileSync(statusFile, "utf8"));
    assert.equal(projection.docker, "unavailable");
    assert.deepEqual(projection.runtime, {
      model: "remote/model",
      context_length: 131072,
    });
  } finally {
    await h.close();
  }
});

test("start writes a safe status projection when docker is unavailable", async () => {
  const fakeEnvFile = path.join(DIR, "env.env");
  fs.writeFileSync(fakeEnvFile, `PIXEL_GATEWAY_TOKEN=${TOKEN}\n`, { mode: 0o600 });
  const sock = path.join(DIR, "start.sock");
  const statusFile = path.join(DIR, "start-status.json");
  const deps = {
    fetch: async () => ({ status: 503, body: { cancel: async () => {} } }),
    execFile: (_command, _args, _options, callback) => callback(new Error("docker unavailable")),
  };
  const h = await start({
    socketPath: sock,
    gatewayTokenFile: fakeEnvFile,
    gatewayPort: 18999,
    statusFile,
    statusIntervalMs: 60000,
    ingressGid: null,
    odsVersion: "2.6.0",
  }, { deps, euid: EUID });
  const proj = JSON.parse(fs.readFileSync(statusFile, "utf8"));
  assert.ok(proj.timestamp);
  assert.equal(proj.ingress_ready, true);
  assert.equal(proj.gateway_reachable, false);
  assert.equal(proj.docker, "unavailable");
  assert.equal(proj.schema_version, 2);
  assert.equal(proj.ods_version, "2.6.0");
  assert.equal(proj.online_apps, 0);
  assert.equal(proj.app_ports.n8n, 5678);
  assert.equal(proj.runtime, null);
  assert.deepEqual(proj.apps, []);
  assert.equal(fs.statSync(statusFile).mode & 0o777, 0o640);
  await h.close();
});

test("upstream error and wrong content type never reflect an upstream secret", async () => {
  for (const variant of ["error", "wrong-type"]) {
    const upstream = http.createServer((_req, res) => {
      if (variant === "error") res.writeHead(500, { "Content-Type": "application/json" });
      else res.writeHead(200, { "Content-Type": "text/plain" });
      res.end("secret-upstream-body-/private/token");
    });
    await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve));
    const ingress = await startIngress({ gatewayPort: upstream.address().port });
    try {
      const response = await request(ingress, "POST", "/v1/chat/completions", {
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }),
      });
      assert.equal(response.status, 502);
      assert.equal(response.body.includes("secret-upstream"), false);
      assert.equal(response.body.includes("private/token"), false);
    } finally {
      await new Promise((resolve) => ingress.close(resolve));
      await new Promise((resolve) => upstream.close(resolve));
    }
  }
});