"use strict";

const test = require("node:test");
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { createApp } = require("./server");

async function withServer(run, extra = {}) {
  const mail = [];
  const app = createApp({
    requestToken: "request-only-secret",
    ownerEmail: "owner@example.invalid",
    publicBaseUrl: "https://example.invalid/authz",
    targets: ["JD-FD-PRIMARY", "BS-GZ-006"],
    actions: { "server-login": ["read-navigation-map", "inspect-services"], "server-ops": ["read-navigation-map", "inspect-services"], "repo-push": ["read-navigation-map", "push-repository"] },
    stateFile: "",
    sendEmail: async (message) => { mail.push(message); return true; },
    ...extra,
  });
  await new Promise((resolve) => app.listen(0, "127.0.0.1", resolve));
  const base = `http://127.0.0.1:${app.address().port}`;
  try { await run({ base, mail }); } finally { await new Promise((resolve) => app.close(resolve)); }
}

test("work order sends an opaque approval link and can be claimed once", async () => {
  await withServer(async ({ base, mail }) => {
    const recipientFingerprint = crypto.createHash("sha256").update("owner@example.invalid").digest("hex");
    const requested = await fetch(`${base}/api/workorders`, {
      method: "POST",
      headers: { authorization: "Bearer request-only-secret", "content-type": "application/json" },
      body: JSON.stringify({ persona_id: "ICE-GL-ZY001", persona_name: "铸渊", target: "JD-FD-PRIMARY", scope: "server-login", action: "read-navigation-map", recipient_fingerprint: recipientFingerprint }),
    });
    assert.equal(requested.status, 201);
    const order = await requested.json();
    assert.equal(mail.length, 1);
    assert.equal(mail[0].to, "owner@example.invalid");
    assert.doesNotMatch(JSON.stringify(order), /approvalToken/i);

    const approvalPath = new URL(mail[0].approvalUrl).pathname.replace("/authz", "");
    const page = await fetch(`${base}${approvalPath}`);
    assert.equal(page.status, 200);
    assert.match(await page.text(), /JD-FD-PRIMARY/);

    const approved = await fetch(`${base}${approvalPath}`, { method: "POST" });
    assert.equal(approved.status, 200);
    const claimed = await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, {
      method: "POST",
      headers: { authorization: `Bearer ${order.claim_token}` },
    });
    assert.equal(claimed.status, 200);
    const session = await claimed.json();
    assert.equal(session.expires_in, 3 * 60 * 60);

    const secondClaim = await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } });
    assert.equal(secondClaim.status, 403);
  });
});

test("cross-device request is powerless until the owner asks for an email and approves it", async () => {
  await withServer(async ({ base, mail }) => {
    const capabilities = await (await fetch(`${base}/api/public/capabilities`)).json();
    assert.deepEqual(capabilities.required_fields, ["persona_id", "target", "scope", "action"]);
    assert.ok(capabilities.scopes["repo-push"].includes("push-repository"));
    assert.equal(capabilities.limits.create_per_network_per_hour, 24);
    assert.equal(capabilities.limits.email_per_network_per_hour, 12);
    assert.doesNotMatch(JSON.stringify(capabilities), /owner@example\.invalid/);
    const requested = await fetch(`${base}/api/public/workorders`, {
      method: "POST",
      headers: { "content-type": "application/json", "x-forwarded-for": "198.51.100.8" },
      body: JSON.stringify({ persona_id: "ICE-GL-ZY001", persona_name: "铸渊", target: "JD-FD-PRIMARY", scope: "repo-push", action: "push-repository", description: "mobile handoff" }),
    });
    assert.equal(requested.status, 201);
    const order = await requested.json();
    assert.equal(order.status, "waiting_for_owner_handoff");
    assert.equal(order.receipt.diagnostic_code, "owner_handoff_required");
    assert.equal(mail.length, 0);
    assert.match(order.request_url, /\/request\//);
    assert.doesNotMatch(JSON.stringify(order), /approve\//);

    const requestPath = new URL(order.request_url).pathname.replace("/authz", "");
    const handoffPage = await fetch(`${base}${requestPath}`);
    assert.equal(handoffPage.status, 200);
    assert.match(await handoffPage.text(), /无权限申请单/);

    const prematureClaim = await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } });
    assert.equal(prematureClaim.status, 202);

    const sendMail = await fetch(`${base}${requestPath}`, { method: "POST", headers: { "x-forwarded-for": "203.0.113.9" } });
    assert.equal(sendMail.status, 200);
    assert.equal(mail.length, 1);
    assert.match(await sendMail.text(), /请打开邮箱完成批准/);

    const approvalPath = new URL(mail[0].approvalUrl).pathname.replace("/authz", "");
    const approved = await fetch(`${base}${approvalPath}`, { method: "POST" });
    assert.equal(approved.status, 200);
    const claimed = await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } });
    assert.equal(claimed.status, 200);
    assert.equal((await claimed.json()).expires_in, 3 * 60 * 60);
  });
});

test("declared Work/mobile instance can notify the registered owner without a local credential", async () => {
  await withServer(async ({ base, mail }) => {
    const requested = await fetch(`${base}/api/public/workorders`, {
      method: "POST", headers: { "content-type": "application/json" },
      body: JSON.stringify({ system_entry: "光湖语言人格系统当前实例", origin_software: "Work", origin_model: "语言模型", origin_instance: "mobile-1", owner_notify: true, persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-ops", action: "dispatch-approved-deployment", resource: `GLS-0239-DEPLOY@${"a".repeat(40)}` }),
    });
    assert.equal(requested.status, 201);
    const order = await requested.json();
    assert.equal(order.status, "waiting_for_owner");
    assert.equal(order.email_status, "sent");
    assert.equal(mail.length, 1);
    assert.match(mail[0].approvalUrl, /\/approve\//);
  }, { actions: { "server-ops": ["read-navigation-map", "dispatch-approved-deployment"] } });
});

test("cross-device request creation is rate limited without revealing owner identity", async () => {
  await withServer(async ({ base, mail }) => {
    const payload = { persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login", action: "read-navigation-map" };
    for (let i = 0; i < 3; i += 1) {
      const response = await fetch(`${base}/api/public/workorders`, { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "spoofed, 198.51.100.20" }, body: JSON.stringify(payload) });
      assert.equal(response.status, 201);
      assert.doesNotMatch(await response.text(), /owner@example\.invalid/);
    }
    const blocked = await fetch(`${base}/api/public/workorders`, { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "different-spoof, 198.51.100.20" }, body: JSON.stringify(payload) });
    assert.equal(blocked.status, 429);
    assert.equal(mail.length, 0);
  }, { publicCreateLimit: 1, publicCreateGlobalLimit: 10 });
});

test("one server-ops approval exposes the full registered three-hour operation scope", async () => {
  const app = createApp({
    requestToken: "request-only-secret",
    ownerEmail: "owner@example.invalid",
    publicBaseUrl: "https://example.invalid/authz",
    stateFile: "",
    sendEmail: async () => true,
  });
  await new Promise(resolve => app.listen(0, "127.0.0.1", resolve));
  try {
    const base = `http://127.0.0.1:${app.address().port}`;
    const capabilities = await (await fetch(`${base}/api/public/capabilities`)).json();
    assert.deepEqual(capabilities.scopes["server-ops"], [
      "read-navigation-map",
      "inspect-services",
      "pull-registered-repo",
      "deploy-registered-service",
      "restart-registered-service",
      "health-check",
      "rollback-registered-service",
      "provision-approved-architecture",
      "push-repository",
      "restore-owner-password-login",
      "restore-code-channel-owner-login",
      "dispatch-approved-deployment",
    ]);
  } finally {
    await new Promise(resolve => app.close(resolve));
  }
});

test("mail handoff allows at least three requests per network and refresh does not consume quota", async () => {
  await withServer(async ({ base, mail }) => {
    const source = { "x-forwarded-for": "198.51.100.42" };
    for (let i = 0; i < 3; i += 1) {
      const requested = await fetch(`${base}/api/public/workorders`, {
        method: "POST", headers: { "content-type": "application/json" },
        body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "repo-push", action: "push-repository" }),
      });
      const order = await requested.json();
      const requestPath = new URL(order.request_url).pathname.replace("/authz", "");
      assert.equal((await fetch(`${base}${requestPath}`, { method: "POST", headers: source })).status, 200);
      assert.equal((await fetch(`${base}${requestPath}`, { method: "POST", headers: source })).status, 200);
    }
    assert.equal(mail.length, 3);
    const fourth = await fetch(`${base}/api/public/workorders`, {
      method: "POST", headers: { "content-type": "application/json" },
      body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "repo-push", action: "push-repository" }),
    });
    const fourthOrder = await fourth.json();
    const fourthPath = new URL(fourthOrder.request_url).pathname.replace("/authz", "");
    assert.equal((await fetch(`${base}${fourthPath}`, { method: "POST", headers: source })).status, 429);
  }, { publicMailLimit: 1 });
});

test("navigation map acknowledgement is mandatory before other registered actions", async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-server-map-"));
  const mapsDir = path.join(dir, "maps"); fs.mkdirSync(mapsDir);
  fs.writeFileSync(path.join(mapsDir, "JD-FD-PRIMARY.json"), JSON.stringify({ node_id: "JD-FD-PRIMARY", modules: [{ code: "JD-GTW-01" }] }));
  try {
    await withServer(async ({ base, mail }) => {
      const fingerprint = crypto.createHash("sha256").update("owner@example.invalid").digest("hex");
      const requested = await fetch(`${base}/api/workorders`, { method: "POST", headers: { authorization: "Bearer request-only-secret", "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login", action: "read-navigation-map", recipient_fingerprint: fingerprint }) });
      const order = await requested.json();
      const approvalPath = new URL(mail[0].approvalUrl).pathname.replace("/authz", "");
      await fetch(`${base}${approvalPath}`, { method: "POST" });
      const claimed = await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } });
      const session = await claimed.json();
      const common = { persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login" };
      const locked = await fetch(`${base}/api/session/verify`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, action: "inspect-services" }) });
      assert.equal(locked.status, 423);
      const mapResponse = await fetch(`${base}/api/navigation-map/read`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify(common) });
      const map = await mapResponse.json();
      const ack = await fetch(`${base}/api/navigation-map/ack`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, map_hash: map.map_hash }) });
      assert.equal(ack.status, 200);
      const unlocked = await fetch(`${base}/api/session/verify`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, action: "inspect-services" }) });
      assert.equal(unlocked.status, 200);
    }, { mapsDir, mapStateFile: path.join(dir, "acks.json") });
  } finally { fs.rmSync(dir, { recursive: true, force: true }); }
});

test("active session renewal preserves target and scope and extends the map acknowledgement", async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-renew-"));
  const mapsDir = path.join(dir, "maps"); fs.mkdirSync(mapsDir);
  fs.writeFileSync(path.join(mapsDir, "JD-FD-PRIMARY.json"), JSON.stringify({ node_id: "JD-FD-PRIMARY" }));
  try {
    await withServer(async ({ base, mail }) => {
      const requested = await fetch(`${base}/api/public/workorders`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login", action: "read-navigation-map" }) });
      const order = await requested.json();
      await fetch(`${base}${new URL(order.request_url).pathname.replace("/authz", "")}`, { method: "POST" });
      await fetch(`${base}${new URL(mail[0].approvalUrl).pathname.replace("/authz", "")}`, { method: "POST" });
      const session = await (await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } })).json();
      const common = { persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login" };
      const map = await (await fetch(`${base}/api/navigation-map/read`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify(common) })).json();
      await fetch(`${base}/api/navigation-map/ack`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, map_hash: map.map_hash }) });
      const expanded = await fetch(`${base}/api/session/renew`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, action: "health-check" }) });
      assert.equal(expanded.status, 400);
      const renewed = await fetch(`${base}/api/session/renew`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify(common) });
      assert.equal(renewed.status, 200);
      assert.equal((await renewed.json()).authority_expanded, false);
    }, { mapsDir, mapStateFile: path.join(dir, "acks.json"), sessionTtl: 100, maxSessionLifetime: 500 });
  } finally { fs.rmSync(dir, { recursive: true, force: true }); }
});

test("registered action bridge executes only after session and map checks", async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-action-"));
  const mapsDir = path.join(dir, "maps"); fs.mkdirSync(mapsDir);
  fs.writeFileSync(path.join(mapsDir, "JD-FD-PRIMARY.json"), JSON.stringify({ node_id: "JD-FD-PRIMARY" }));
  const calls = [];
  try {
    await withServer(async ({ base, mail }) => {
      const requested = await fetch(`${base}/api/public/workorders`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login", action: "read-navigation-map" }) });
      const order = await requested.json();
      const requestPath = new URL(order.request_url).pathname.replace("/authz", "");
      await fetch(`${base}${requestPath}`, { method: "POST" });
      const approvalPath = new URL(mail[0].approvalUrl).pathname.replace("/authz", "");
      await fetch(`${base}${approvalPath}`, { method: "POST" });
      const claimed = await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } });
      const session = await claimed.json();
      const initialStatus = await fetch(`${base}/api/session/status`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login" }) });
      assert.equal((await initialStatus.json()).state, "map_ack_required");
      const common = { persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login", action: "inspect-services" };
      const beforeAck = await fetch(`${base}/api/actions/execute`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify(common) });
      assert.equal(beforeAck.status, 423);
      const map = await (await fetch(`${base}/api/navigation-map/read`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify(common) })).json();
      await fetch(`${base}/api/navigation-map/ack`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, map_hash: map.map_hash }) });
      const forbidden = await fetch(`${base}/api/actions/execute`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, cmd: "id" }) });
      assert.equal(forbidden.status, 400);
      const executed = await fetch(`${base}/api/actions/execute`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify(common) });
      assert.equal(executed.status, 200);
      assert.equal((await executed.clone().json()).receipt.state, "succeeded");
      const finalStatus = await fetch(`${base}/api/session/status`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login" }) });
      const finalPayload = await finalStatus.json();
      assert.equal(finalPayload.state, "ready_to_execute");
      assert.equal(finalPayload.last_receipt.diagnostic_code, "action_succeeded");
      assert.deepEqual(calls, [{ action: "inspect-services", target: "JD-FD-PRIMARY" }]);
    }, { mapsDir, mapStateFile: path.join(dir, "acks.json"), executeAction: async request => { calls.push(request); return { ok: true, stdout: "healthy" }; } });
  } finally { fs.rmSync(dir, { recursive: true, force: true }); }
});

test("failed server actions return a durable diagnosis instead of making a persona guess", async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-action-failure-"));
  const mapsDir = path.join(dir, "maps"); fs.mkdirSync(mapsDir);
  fs.writeFileSync(path.join(mapsDir, "JD-FD-PRIMARY.json"), JSON.stringify({ node_id: "JD-FD-PRIMARY" }));
  try {
    await withServer(async ({ base, mail }) => {
      const requested = await fetch(`${base}/api/public/workorders`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login", action: "read-navigation-map" }) });
      const order = await requested.json();
      await fetch(`${base}${new URL(order.request_url).pathname.replace("/authz", "")}`, { method: "POST" });
      await fetch(`${base}${new URL(mail[0].approvalUrl).pathname.replace("/authz", "")}`, { method: "POST" });
      const session = await (await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } })).json();
      const common = { persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login" };
      const map = await (await fetch(`${base}/api/navigation-map/read`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify(common) })).json();
      await fetch(`${base}/api/navigation-map/ack`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, map_hash: map.map_hash }) });
      const failed = await fetch(`${base}/api/actions/execute`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, action: "inspect-services" }) });
      assert.equal(failed.status, 502);
      const payload = await failed.json();
      assert.equal(payload.receipt.state, "failed");
      assert.equal(payload.receipt.diagnostic_code, "agent_socket_unavailable");
      assert.match(payload.receipt.next_step, /diagnostic_code/);
    }, { mapsDir, mapStateFile: path.join(dir, "acks.json"), executeAction: async () => ({ ok: false, error: "agent_socket_unavailable", stderr: "socket offline" }) });
  } finally { fs.rmSync(dir, { recursive: true, force: true }); }
});

test("deployment is dispatched only by an explicit approved second signal", async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-deploy-dispatch-"));
  const mapsDir = path.join(dir, "maps"); fs.mkdirSync(mapsDir);
  fs.writeFileSync(path.join(mapsDir, "JD-FD-PRIMARY.json"), JSON.stringify({ node_id: "JD-FD-PRIMARY" }));
  const sha = "a".repeat(40), resource = `GLS-0239-DEPLOY@${sha}`;
  try {
    await withServer(async ({ base, mail }) => {
      const requested = await fetch(`${base}/api/public/workorders`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-ops", action: "dispatch-approved-deployment", resource }) });
      const order = await requested.json();
      await fetch(`${base}${new URL(order.request_url).pathname.replace("/authz", "")}`, { method: "POST" });
      await fetch(`${base}${new URL(mail[0].approvalUrl).pathname.replace("/authz", "")}`, { method: "POST" });
      const session = await (await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } })).json();
      const common = { persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-ops" };
      const map = await (await fetch(`${base}/api/navigation-map/read`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify(common) })).json();
      await fetch(`${base}/api/navigation-map/ack`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, map_hash: map.map_hash }) });
      const dispatch = await fetch(`${base}/api/deployment/dispatch`, { method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" }, body: JSON.stringify({ ...common, repo: "bingshuo/guanghu-ice-heart", branch: "main", commit_sha: sha, resource, manifest: "deployment/requests/GLS-0239.json" }) });
      assert.equal(dispatch.status, 202);
      assert.equal((await dispatch.json()).receipt.state, "queued");
      assert.equal(fs.readdirSync(path.join(dir, "queue")).length, 1);
    }, {
      mapsDir,
      mapStateFile: path.join(dir, "acks.json"),
      deploymentQueueDir: path.join(dir, "queue"),
      deploymentRepositories: {
        "bingshuo/guanghu-ice-heart": {
          repo_url: "https://example.invalid/guanghu-ice-heart.git",
        },
      },
      actions: { "server-ops": ["read-navigation-map", "dispatch-approved-deployment"] },
    });
  } finally { fs.rmSync(dir, { recursive: true, force: true }); }
});

test("request endpoint rejects direct email target switching and unknown actions", async () => {
  await withServer(async ({ base }) => {
    const common = { method: "POST", headers: { authorization: "Bearer request-only-secret", "content-type": "application/json" } };
    const directEmail = await fetch(`${base}/api/workorders`, { ...common, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login", action: "read-navigation-map", email: "attacker@example.invalid" }) });
    assert.equal(directEmail.status, 400);
    const unknown = await fetch(`${base}/api/workorders`, { ...common, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-login", action: "shell" }) });
    assert.equal(unknown.status, 400);
  });
});

test("architecture provision request is bound to one immutable manifest and commit", async () => {
  const actions = { "server-ops": ["read-navigation-map", "provision-approved-architecture"] };
  const resource = `GLS-0231-JD-LAN-01-INITIAL-PROVISION-20260720@${"a".repeat(40)}`;
  await withServer(async ({ base, mail }) => {
    const missing = await fetch(`${base}/api/public/workorders`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-ops", action: "provision-approved-architecture" }) });
    assert.equal(missing.status, 400);
    assert.equal((await missing.json()).error, "immutable_architecture_resource_required");
    const requested = await fetch(`${base}/api/public/workorders`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-ops", action: "provision-approved-architecture", resource }) });
    const order = await requested.json();
    await fetch(`${base}${new URL(order.request_url).pathname.replace("/authz", "")}`, { method: "POST" });
    assert.equal(mail[0].order.resource, resource);
    const approvalPath = new URL(mail[0].approvalUrl).pathname.replace("/authz", "");
    assert.match(await (await fetch(`${base}${approvalPath}`)).text(), new RegExp(resource));
    await fetch(`${base}${approvalPath}`, { method: "POST" });
    const session = await (await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } })).json();
    assert.equal(session.resource, resource);
  }, { actions });
});

test("session verification rejects switching servers without new approval", async () => {
  await withServer(async ({ base, mail }) => {
    const fingerprint = crypto.createHash("sha256").update("owner@example.invalid").digest("hex");
    const requested = await fetch(`${base}/api/workorders`, {
      method: "POST", headers: { authorization: "Bearer request-only-secret", "content-type": "application/json" },
      body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "BS-GZ-006", scope: "server-ops", action: "read-navigation-map", recipient_fingerprint: fingerprint }),
    });
    const order = await requested.json();
    const approvalPath = new URL(mail[0].approvalUrl).pathname.replace("/authz", "");
    await fetch(`${base}${approvalPath}`, { method: "POST" });
    const claimed = await fetch(`${base}/api/workorders/${order.workorder_id}/claim`, { method: "POST", headers: { authorization: `Bearer ${order.claim_token}` } });
    const session = await claimed.json();
    const switched = await fetch(`${base}/api/session/verify`, {
      method: "POST", headers: { authorization: `Bearer ${session.session_token}`, "content-type": "application/json" },
      body: JSON.stringify({ persona_id: "ICE-GL-ZY001", target: "JD-FD-PRIMARY", scope: "server-ops", action: "read-navigation-map" }),
    });
    assert.equal(switched.status, 403);
    assert.equal((await switched.json()).error, "target_mismatch");
  });
});

test("server policy selects a member mailbox by persona target and scope", async () => {
  await withServer(async ({ base, mail }) => {
    const requested = await fetch(`${base}/api/public/workorders`, {
      method: "POST", headers: { "content-type": "application/json" },
      body: JSON.stringify({ persona_id: "AWEN-TECH", target: "JD-FD-PRIMARY", scope: "server-ops", action: "read-navigation-map" }),
    });
    const order = await requested.json();
    const requestPath = new URL(order.request_url).pathname.replace("/authz", "");
    assert.equal((await fetch(`${base}${requestPath}`, { method: "POST" })).status, 200);
    assert.equal(mail[0].to, "awen@example.invalid");
  }, { approvers: [
    { id: "owner", email: "owner@example.invalid", default: true, persona_ids: ["ICE-GL-ZY001"], targets: ["*"], scopes: ["*"] },
    { id: "awen", email: "awen@example.invalid", default: false, persona_ids: ["AWEN-TECH"], targets: ["JD-FD-PRIMARY"], scopes: ["server-ops"] },
  ] });
});
