import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { constants as fsConstants } from "node:fs";
import { lstat, open, readdir, realpath, stat } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { runAcuity } from "./acuity-adapter.mjs";
import { assertProfile, permits } from "./profile-policy.mjs";

const MODE_MASK = 0o777;
const OWNER_ONLY_MODE = 0o600;
const execFileAsync = promisify(execFile);

// Keep the caller-visible parameter contract beside the execution metadata.
// The hosted bridge projects these schemas dynamically, while the executor
// below remains the final authority and repeats every path/range check.
const NO_PARAMETERS = Object.freeze({
  type: "object",
  properties: Object.freeze({}),
  required: Object.freeze([]),
  additionalProperties: false,
});
const EXACT_RELATIVE_PATH_PARAMETERS = Object.freeze({
  type: "object",
  properties: Object.freeze({
    relativePath: Object.freeze({ type: "string", minLength: 1, maxLength: 1000, description: "Exact non-traversing path relative to the paired workspace." }),
  }),
  required: Object.freeze(["relativePath"]),
  additionalProperties: false,
});
const TEXT_SEARCH_PARAMETERS = Object.freeze({
  type: "object",
  properties: Object.freeze({
    relativePath: Object.freeze({ type: "string", minLength: 1, maxLength: 1000, description: "Optional non-traversing search root relative to the paired workspace." }),
    query: Object.freeze({ type: "string", minLength: 1, maxLength: 200, description: "Literal text to find." }),
    maxResults: Object.freeze({ type: "integer", minimum: 1, maximum: 100 }),
  }),
  required: Object.freeze(["query"]),
  additionalProperties: false,
});
const DIRECTORY_INVENTORY_PARAMETERS = Object.freeze({
  type: "object",
  properties: Object.freeze({
    relativePath: Object.freeze({ type: "string", minLength: 1, maxLength: 1000, description: "Optional non-traversing directory relative to the paired workspace." }),
    maxEntries: Object.freeze({ type: "integer", minimum: 1, maximum: 500 }),
  }),
  required: Object.freeze([]),
  additionalProperties: false,
});

/**
 * Capability metadata is the hosted bridge's authority ceiling. The executor
 * independently enforces the local path and consent invariants below; callers
 * must not infer write authority merely from a similarly named capability.
 */
export const CAPABILITY_REGISTRY = Object.freeze({
  npm_supply_chain_assessment: Object.freeze({
    id: "npm_supply_chain_assessment",
    techniqueId: "acuity.npm-supply-chain/chaindrop-indicator-assessment/v1",
    kind: "assessment",
    riskTier: "default_safe",
    allowedProfiles: Object.freeze(["monitoring_only", "monitoring_and_probes", "active_security", "adversarial_probing"]),
    title: "npm supply-chain assessment",
    mode: "read_only",
    requiresConsent: false,
    readOnly: true,
    destructive: false,
    sourceLane: "acuity_known_probe",
    consequences: Object.freeze(["Reads local npm dependency metadata and known-indicator evidence without changing files."]),
    requiresPairing: ["workspaceRoot", "homeRoot", "npmFeedFile"],
    parameters: Object.freeze([]),
    inputSchema: NO_PARAMETERS,
  }),
  sensitive_file_mode_assessment: Object.freeze({
    id: "sensitive_file_mode_assessment",
    techniqueId: "acuity.local-file/sensitive-mode-assessment/v1",
    kind: "assessment",
    riskTier: "default_safe",
    allowedProfiles: Object.freeze(["monitoring_only", "monitoring_and_probes", "active_security", "adversarial_probing"]),
    title: "sensitive file mode assessment",
    mode: "read_only",
    requiresConsent: false,
    readOnly: true,
    destructive: false,
    sourceLane: "acuity_known_probe",
    consequences: Object.freeze(["Reads the mode and ownership metadata of one exact local file without changing it."]),
    requiresPairing: ["workspaceRoot"],
    parameters: Object.freeze(["relativePath"]),
    inputSchema: EXACT_RELATIVE_PATH_PARAMETERS,
  }),
  workspace_file_inspection: Object.freeze({
    id: "workspace_file_inspection",
    techniqueId: "talons.local-files/text-inspection/v1",
    kind: "assessment",
    riskTier: "default_safe",
    allowedProfiles: Object.freeze(["monitoring_only", "monitoring_and_probes", "active_security", "adversarial_probing"]),
    title: "workspace text file inspection",
    mode: "read_only",
    requiresConsent: false,
    readOnly: true,
    destructive: false,
    sourceLane: "talons_defensive_discovery",
    consequences: Object.freeze(["Reads at most 256 KiB from one exact regular text file within the paired workspace."]),
    requiresPairing: ["workspaceRoot"],
    parameters: Object.freeze(["relativePath"]),
    inputSchema: EXACT_RELATIVE_PATH_PARAMETERS,
  }),
  workspace_text_search: Object.freeze({
    id: "workspace_text_search",
    techniqueId: "talons.local-files/bounded-text-search/v1",
    kind: "assessment",
    riskTier: "default_safe",
    allowedProfiles: Object.freeze(["monitoring_only", "monitoring_and_probes", "active_security", "adversarial_probing"]),
    title: "bounded workspace text search",
    mode: "read_only",
    requiresConsent: false,
    readOnly: true,
    destructive: false,
    sourceLane: "talons_defensive_discovery",
    consequences: Object.freeze(["Searches bounded regular text files within the paired workspace without following symlinks or changing files."]),
    requiresPairing: ["workspaceRoot"],
    parameters: Object.freeze(["relativePath", "query", "maxResults"]),
    inputSchema: TEXT_SEARCH_PARAMETERS,
  }),
  workspace_directory_inventory: Object.freeze({
    id: "workspace_directory_inventory",
    techniqueId: "talons.local-files/bounded-directory-inventory/v1",
    kind: "assessment",
    riskTier: "default_safe",
    allowedProfiles: Object.freeze(["monitoring_only", "monitoring_and_probes", "active_security", "adversarial_probing"]),
    title: "bounded directory inventory",
    mode: "read_only",
    requiresConsent: false,
    readOnly: true,
    destructive: false,
    sourceLane: "talons_defensive_discovery",
    consequences: Object.freeze(["Lists bounded file metadata in one directory under the paired home root without reading file contents or following symlinks."]),
    requiresPairing: ["workspaceRoot"],
    parameters: Object.freeze(["relativePath", "maxEntries"]),
    inputSchema: DIRECTORY_INVENTORY_PARAMETERS,
  }),
  macos_security_posture: Object.freeze({
    id: "macos_security_posture",
    techniqueId: "talons.macos/security-posture/v1",
    kind: "assessment",
    riskTier: "default_safe",
    allowedProfiles: Object.freeze(["monitoring_only", "monitoring_and_probes", "active_security", "adversarial_probing"]),
    title: "macOS security posture",
    mode: "read_only",
    requiresConsent: false,
    readOnly: true,
    destructive: false,
    sourceLane: "talons_defensive_discovery",
    consequences: Object.freeze(["Queries fixed macOS security controls including FileVault, SIP, Gatekeeper, and the application firewall without changing settings."]),
    requiresPairing: [],
    parameters: Object.freeze([]),
    inputSchema: NO_PARAMETERS,
  }),
  macos_network_listeners: Object.freeze({
    id: "macos_network_listeners",
    techniqueId: "talons.macos/network-listener-inventory/v1",
    kind: "assessment",
    riskTier: "default_safe",
    allowedProfiles: Object.freeze(["monitoring_only", "monitoring_and_probes", "active_security", "adversarial_probing"]),
    title: "macOS network listener inventory",
    mode: "read_only",
    requiresConsent: false,
    readOnly: true,
    destructive: false,
    sourceLane: "talons_defensive_discovery",
    consequences: Object.freeze(["Lists bounded local TCP listening endpoints and owning processes using a fixed read-only system command."]),
    requiresPairing: [],
    parameters: Object.freeze([]),
    inputSchema: NO_PARAMETERS,
  }),
  macos_persistence_inventory: Object.freeze({
    id: "macos_persistence_inventory",
    techniqueId: "talons.macos/launch-item-inventory/v1",
    kind: "assessment",
    riskTier: "default_safe",
    allowedProfiles: Object.freeze(["monitoring_only", "monitoring_and_probes", "active_security", "adversarial_probing"]),
    title: "macOS persistence inventory",
    mode: "read_only",
    requiresConsent: false,
    readOnly: true,
    destructive: false,
    sourceLane: "talons_defensive_discovery",
    consequences: Object.freeze(["Lists bounded launch-agent and launch-daemon filenames from fixed macOS persistence locations without reading their contents."]),
    requiresPairing: ["homeRoot"],
    parameters: Object.freeze([]),
    inputSchema: NO_PARAMETERS,
  }),
  file_mode_owner_only: Object.freeze({
    id: "file_mode_owner_only",
    techniqueId: "talons.local-file/owner-only-mode/v1",
    kind: "remediation",
    riskTier: "explicit_consent",
    allowedProfiles: Object.freeze(["active_security", "adversarial_probing"]),
    title: "restrict file mode to owner only",
    mode: "remediation",
    requiresConsent: true,
    readOnly: false,
    destructive: false,
    sourceLane: "talons_bounded_response",
    consequences: Object.freeze([
      "Changes one exact regular file to mode 0600.",
      "Other local users and processes may lose access until the recorded prior mode is restored.",
    ]),
    requiresPairing: ["workspaceRoot"],
    parameters: Object.freeze(["relativePath"]),
    inputSchema: EXACT_RELATIVE_PATH_PARAMETERS,
  }),
});

function stableValue(value) {
  if (Array.isArray(value)) return value.map(stableValue);
  if (!value || typeof value !== "object") return value;
  return Object.fromEntries(
    Object.keys(value)
      .sort()
      .map((key) => [key, stableValue(value[key])]),
  );
}

function digestJson(value) {
  return createHash("sha256")
    .update(JSON.stringify(stableValue(value)))
    .digest("hex");
}

function requiredString(value, label) {
  const text = String(value || "").trim();
  if (!text) throw new Error(`${label} is required.`);
  return text;
}

function assertParameters(parameters, allowed) {
  if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
    throw new Error("parameters must be an object.");
  }
  const unexpected = Object.keys(parameters).filter((key) => !allowed.includes(key));
  if (unexpected.length) throw new Error(`Unsupported capability parameters: ${unexpected.join(", ")}.`);
}

function assertNotAborted(signal) {
  if (signal?.aborted) throw signal.reason || new Error("Capability execution was aborted.");
}

function assertSecureDeviceProfile(capability, pairing) {
  const profile = assertProfile(pairing?.profile || "monitoring_only");
  if (!permits(profile, capability) || !capability.allowedProfiles.includes(profile)) {
    throw new Error(`${capability.id} is not admitted for pairing profile ${profile}.`);
  }
}

function withAbort(promise, signal) {
  assertNotAborted(signal);
  if (!signal) return promise;
  return Promise.race([
    promise,
    new Promise((_, reject) => {
      signal.addEventListener("abort", () => {
        reject(signal.reason || new Error("Capability execution was aborted."));
      }, { once: true });
    }),
  ]);
}

async function regularDirectory(value, label) {
  const requested = path.resolve(requiredString(value, label));
  const resolved = await realpath(requested);
  const metadata = await stat(resolved);
  if (!metadata.isDirectory()) throw new Error(`${label} must be a directory.`);
  return resolved;
}

function exactRelativePath(value) {
  const relativePath = requiredString(value, "parameters.relativePath");
  const normalized = relativePath.replaceAll("\\", "/");
  if (
    path.posix.isAbsolute(normalized)
    || normalized === "."
    || normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")
  ) {
    throw new Error("parameters.relativePath must be an exact non-traversing relative path.");
  }
  return normalized;
}

async function resolveRegularWorkspaceFile(workspaceRoot, relativePath) {
  const workspace = await regularDirectory(workspaceRoot, "pairing.workspaceRoot");
  const requestedPath = path.resolve(workspace, relativePath);
  if (!requestedPath.startsWith(`${workspace}${path.sep}`)) {
    throw new Error("parameters.relativePath escapes pairing.workspaceRoot.");
  }

  // Resolve the parent separately. A final-file lstat alone would still permit
  // an ancestor symlink to redirect an otherwise regular file outside the pair.
  const parent = await realpath(path.dirname(requestedPath));
  if (parent !== workspace && !parent.startsWith(`${workspace}${path.sep}`)) {
    throw new Error("parameters.relativePath resolves through a workspace-external parent.");
  }
  const metadata = await lstat(requestedPath);
  if (!metadata.isFile() || metadata.isSymbolicLink()) {
    throw new Error("Capability requires a regular non-symlink file.");
  }
  return { workspace, requestedPath, relativePath, metadata };
}

function modeOctal(metadata) {
  return `0${(metadata.mode & MODE_MASK).toString(8).padStart(3, "0")}`;
}

function modeAssessment(relativePath, metadata) {
  const mode = metadata.mode & MODE_MASK;
  return {
    relativePath,
    mode: modeOctal(metadata),
    uid: metadata.uid,
    gid: metadata.gid,
    ownerOnly: (mode & 0o077) === 0,
  };
}

async function npmSupplyChainAssessment({ pairing, parameters, signal }) {
  assertParameters(parameters, []);
  assertNotAborted(signal);
  const raw = await withAbort(runAcuity({ capability: "npm_supply_chain_assessment", pairing, signal }), signal);
  assertNotAborted(signal);
  return raw;
}

async function sensitiveFileModeAssessment({ pairing, parameters }) {
  assertParameters(parameters, ["relativePath"]);
  const relativePath = exactRelativePath(parameters.relativePath);
  return runAcuity({ capability: "sensitive_file_mode_assessment", pairing: { ...pairing, relativePath } });
}

async function workspaceFileInspection({ pairing, parameters }) {
  assertParameters(parameters, ["relativePath"]);
  const relativePath = exactRelativePath(parameters.relativePath);
  const file = await resolveRegularWorkspaceFile(pairing?.workspaceRoot, relativePath);
  const handle = await open(file.requestedPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
  try {
    const metadata = await handle.stat();
    if (metadata.size > 256 * 1024) throw new Error("workspace_file_inspection is limited to 256 KiB text files.");
    const bytes = await handle.readFile();
    if (bytes.includes(0)) throw new Error("workspace_file_inspection requires a text file.");
    const report = {
      type: "talons.workspace-file-inspection.v1",
      capabilityId: "workspace_file_inspection",
      relativePath,
      sizeBytes: bytes.length,
      content: bytes.toString("utf8"),
      contentSha256: createHash("sha256").update(bytes).digest("hex"),
    };
    return { ...report, reportDigest: digestJson(report) };
  } finally { await handle.close(); }
}

async function workspaceTextSearch({ pairing, parameters, signal }) {
  assertParameters(parameters, ["relativePath", "query", "maxResults"]);
  const workspace = await regularDirectory(pairing?.workspaceRoot, "pairing.workspaceRoot");
  const relativeRoot = parameters.relativePath ? exactRelativePath(parameters.relativePath) : "";
  const query = requiredString(parameters.query, "parameters.query");
  if (query.length > 200 || /[\u0000-\u001f\u007f]/u.test(query)) throw new Error("parameters.query is invalid.");
  const maxResults = Number(parameters.maxResults ?? 50);
  if (!Number.isSafeInteger(maxResults) || maxResults < 1 || maxResults > 100) throw new Error("parameters.maxResults must be between 1 and 100.");
  const start = relativeRoot ? path.resolve(workspace, relativeRoot) : workspace;
  const startMetadata = await lstat(start);
  if (startMetadata.isSymbolicLink()) throw new Error("workspace_text_search does not follow symlinks.");
  const queue = startMetadata.isDirectory() ? [relativeRoot] : [];
  const files = startMetadata.isFile() ? [relativeRoot] : [];
  let entriesScanned = 0;
  while (queue.length && files.length < 2_000) {
    assertNotAborted(signal);
    const directoryRelative = queue.shift();
    const directory = directoryRelative ? path.resolve(workspace, directoryRelative) : workspace;
    const resolvedDirectory = await realpath(directory);
    if (resolvedDirectory !== workspace && !resolvedDirectory.startsWith(`${workspace}${path.sep}`)) throw new Error("workspace_text_search escaped the paired workspace.");
    for (const entry of await readdir(resolvedDirectory, { withFileTypes: true })) {
      entriesScanned += 1;
      if (entriesScanned > 4_000) break;
      if (entry.isSymbolicLink()) continue;
      const child = directoryRelative ? `${directoryRelative}/${entry.name}` : entry.name;
      if (entry.isDirectory()) queue.push(child);
      else if (entry.isFile() && files.length < 2_000) files.push(child);
    }
    if (entriesScanned > 4_000) break;
  }
  const matches = [];
  let bytesScanned = 0;
  for (const relativePath of files) {
    assertNotAborted(signal);
    if (matches.length >= maxResults || bytesScanned >= 8 * 1024 * 1024) break;
    let file;
    try { file = await resolveRegularWorkspaceFile(workspace, relativePath); } catch { continue; }
    if (file.metadata.size > 256 * 1024) continue;
    const handle = await open(file.requestedPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
    try {
      const bytes = await handle.readFile();
      bytesScanned += bytes.length;
      if (bytes.includes(0)) continue;
      const lines = bytes.toString("utf8").split("\n");
      for (let index = 0; index < lines.length && matches.length < maxResults; index += 1) {
        if (lines[index].includes(query)) matches.push({ relativePath, line: index + 1, text: lines[index].slice(0, 300) });
      }
    } finally { await handle.close(); }
  }
  const report = {
    type: "talons.workspace-text-search.v1",
    capabilityId: "workspace_text_search",
    querySha256: createHash("sha256").update(query).digest("hex"),
    relativeRoot: relativeRoot || ".",
    matches,
    limits: { maxResults, maxFiles: 2_000, maxFileBytes: 256 * 1024, maxTotalBytes: 8 * 1024 * 1024 },
    observed: { entriesScanned, filesConsidered: files.length, bytesScanned },
  };
  return { ...report, reportDigest: digestJson(report) };
}

async function workspaceDirectoryInventory({ pairing, parameters }) {
  assertParameters(parameters, ["relativePath", "maxEntries"]);
  const workspace = await regularDirectory(pairing?.workspaceRoot, "pairing.workspaceRoot");
  const relativeRoot = parameters.relativePath ? exactRelativePath(parameters.relativePath) : "";
  const maxEntries = Number(parameters.maxEntries ?? 200);
  if (!Number.isSafeInteger(maxEntries) || maxEntries < 1 || maxEntries > 500) {
    throw new Error("parameters.maxEntries must be between 1 and 500.");
  }
  const requested = relativeRoot ? path.resolve(workspace, relativeRoot) : workspace;
  const resolved = await realpath(requested);
  if (resolved !== workspace && !resolved.startsWith(`${workspace}${path.sep}`)) {
    throw new Error("workspace_directory_inventory escaped the paired workspace.");
  }
  const directoryMetadata = await lstat(requested);
  if (!directoryMetadata.isDirectory() || directoryMetadata.isSymbolicLink()) {
    throw new Error("workspace_directory_inventory requires a regular directory.");
  }
  const entries = [];
  for (const entry of (await readdir(resolved, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
    if (entries.length >= maxEntries) break;
    const metadata = await lstat(path.join(resolved, entry.name));
    entries.push({
      name: entry.name,
      type: entry.isSymbolicLink() ? "symlink" : entry.isDirectory() ? "directory" : entry.isFile() ? "file" : "other",
      mode: modeOctal(metadata),
      sizeBytes: metadata.isFile() ? metadata.size : null,
      modifiedAt: metadata.mtime.toISOString(),
    });
  }
  const report = {
    type: "talons.workspace-directory-inventory.v1",
    capabilityId: "workspace_directory_inventory",
    relativeRoot: relativeRoot || ".",
    entries,
    truncated: entries.length >= maxEntries,
    limits: { maxEntries },
  };
  return { ...report, reportDigest: digestJson(report) };
}

async function runFixedCommand(pairing, executable, args) {
  const injected = pairing?.testHooks?.runFixedCommand;
  if (injected) return String(await injected({ executable, args: [...args] }));
  const result = await execFileAsync(executable, args, { timeout: 10_000, maxBuffer: 512 * 1024, encoding: "utf8" });
  return String(result.stdout || result.stderr || "").trim();
}

async function fixedProbe(pairing, executable, args) {
  try {
    return { available: true, output: (await runFixedCommand(pairing, executable, args)).slice(0, 2_000) };
  } catch (error) {
    return { available: false, error: String(error?.code || "probe_unavailable").slice(0, 80) };
  }
}

function controlState(probe, enabledPattern) {
  if (!probe.available) return "unknown";
  return enabledPattern.test(probe.output) ? "enabled" : "disabled";
}

async function macosSecurityPosture({ pairing, parameters }) {
  assertParameters(parameters, []);
  if (process.platform !== "darwin" && !pairing?.testHooks?.pretendDarwin) {
    const report = { type: "talons.macos-security-posture.v1", capabilityId: "macos_security_posture", supported: false, platform: process.platform, controls: {} };
    return { ...report, reportDigest: digestJson(report) };
  }
  const [version, fileVault, sip, gatekeeper, firewall] = await Promise.all([
    fixedProbe(pairing, "/usr/bin/sw_vers", ["-productVersion"]),
    fixedProbe(pairing, "/usr/bin/fdesetup", ["status"]),
    fixedProbe(pairing, "/usr/bin/csrutil", ["status"]),
    fixedProbe(pairing, "/usr/sbin/spctl", ["--status"]),
    fixedProbe(pairing, "/usr/libexec/ApplicationFirewall/socketfilterfw", ["--getglobalstate"]),
  ]);
  const report = {
    type: "talons.macos-security-posture.v1",
    capabilityId: "macos_security_posture",
    supported: true,
    platform: "darwin",
    osVersion: version.available ? version.output : null,
    controls: {
      fileVault: { state: controlState(fileVault, /FileVault is On\./iu), probe: fileVault },
      systemIntegrityProtection: { state: controlState(sip, /enabled/iu), probe: sip },
      gatekeeper: { state: controlState(gatekeeper, /assessments enabled/iu), probe: gatekeeper },
      applicationFirewall: { state: controlState(firewall, /enabled|State\s*=\s*1/iu), probe: firewall },
    },
  };
  return { ...report, reportDigest: digestJson(report) };
}

function parseLsofListeners(output) {
  const listeners = [];
  for (const line of String(output || "").split("\n").slice(1)) {
    const pieces = line.trim().split(/\s+/u);
    if (pieces.length < 9 || !/^\d+$/u.test(pieces[1])) continue;
    listeners.push({ command: pieces[0].slice(0, 120), pid: Number(pieces[1]), endpoint: pieces.slice(8).join(" ").replace(/\s+\(LISTEN\)$/u, "").slice(0, 300) });
    if (listeners.length >= 256) break;
  }
  return listeners;
}

async function macosNetworkListeners({ pairing, parameters }) {
  assertParameters(parameters, []);
  if (process.platform !== "darwin" && !pairing?.testHooks?.pretendDarwin) {
    const report = { type: "talons.macos-network-listeners.v1", capabilityId: "macos_network_listeners", supported: false, listeners: [] };
    return { ...report, reportDigest: digestJson(report) };
  }
  const probe = await fixedProbe(pairing, "/usr/sbin/lsof", ["-nP", "-iTCP", "-sTCP:LISTEN"]);
  const listeners = probe.available ? parseLsofListeners(probe.output) : [];
  const report = { type: "talons.macos-network-listeners.v1", capabilityId: "macos_network_listeners", supported: true, listeners, truncated: listeners.length >= 256, probeAvailable: probe.available };
  return { ...report, reportDigest: digestJson(report) };
}

async function macosPersistenceInventory({ pairing, parameters }) {
  assertParameters(parameters, []);
  const home = await regularDirectory(pairing?.homeRoot, "pairing.homeRoot");
  const systemRoot = pairing?.testHooks?.systemRoot ? path.resolve(pairing.testHooks.systemRoot) : "/";
  const locations = [
    { scope: "user", directory: path.join(home, "Library", "LaunchAgents") },
    { scope: "system-agents", directory: path.join(systemRoot, "Library", "LaunchAgents") },
    { scope: "system-daemons", directory: path.join(systemRoot, "Library", "LaunchDaemons") },
  ];
  const items = [];
  const unavailable = [];
  for (const location of locations) {
    try {
      for (const entry of (await readdir(location.directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
        if (items.length >= 500) break;
        if (entry.isFile() && entry.name.endsWith(".plist")) items.push({ scope: location.scope, name: entry.name });
      }
    } catch (error) { unavailable.push({ scope: location.scope, error: String(error?.code || "unavailable").slice(0, 80) }); }
  }
  const report = { type: "talons.macos-persistence-inventory.v1", capabilityId: "macos_persistence_inventory", items, unavailable, truncated: items.length >= 500 };
  return { ...report, reportDigest: digestJson(report) };
}

function assertRemediationConsent(pairing, capabilityId) {
  if (pairing?.consents?.[capabilityId] !== true) {
    throw new Error(`${capabilityId} requires explicit local pairing consent.`);
  }
}

async function fileModeOwnerOnly({ pairing, parameters }) {
  assertParameters(parameters, ["relativePath"]);
  assertRemediationConsent(pairing, "file_mode_owner_only");
  const relativePath = exactRelativePath(parameters.relativePath);
  const file = await resolveRegularWorkspaceFile(pairing?.workspaceRoot, relativePath);

  // Tests use this injected seam to force the exact ancestor-replacement race
  // we must fence. The production runner never populates testHooks.
  await pairing?.testHooks?.afterPathValidationBeforeOpen?.();

  // O_NOFOLLOW protects the final component. Re-resolving the full path after
  // open and matching its device/inode to the descriptor also fences an
  // ancestor directory swapped to a symlink between validation and open.
  const handle = await open(file.requestedPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
  try {
    const beforeMetadata = await handle.stat();
    const rebound = await resolveRegularWorkspaceFile(pairing?.workspaceRoot, relativePath);
    if (!beforeMetadata.isFile() || beforeMetadata.nlink !== 1 || rebound.metadata.nlink !== 1) {
      throw new Error("Remediation requires one regular file with exactly one link.");
    }
    if (beforeMetadata.dev !== rebound.metadata.dev || beforeMetadata.ino !== rebound.metadata.ino) {
      throw new Error("The selected file changed during remediation admission.");
    }
    await handle.chmod(OWNER_ONLY_MODE);
    const afterMetadata = await handle.stat();
    const before = modeAssessment(file.relativePath, beforeMetadata);
    const after = modeAssessment(file.relativePath, afterMetadata);
    const receipt = {
      type: "talons.file-mode-owner-only-receipt.v1",
      capabilityId: "file_mode_owner_only",
      mode: "remediation",
      before,
      after,
      rollback: {
        action: "chmod",
        relativePath: file.relativePath,
        restoreMode: before.mode,
        instruction: `Restore ${file.relativePath} to mode ${before.mode} from the paired local device.`,
      },
    };
    return { ...receipt, receiptDigest: digestJson(receipt) };
  } finally {
    await handle.close();
  }
}

export async function executeCapability({ capabilityId, parameters = {}, pairing, signal } = {}) {
  if (!Object.hasOwn(CAPABILITY_REGISTRY, capabilityId)) {
    throw new Error(`Unknown capability: ${String(capabilityId || "")}.`);
  }
  assertSecureDeviceProfile(CAPABILITY_REGISTRY[capabilityId], pairing);
  assertNotAborted(signal);
  if (capabilityId === "npm_supply_chain_assessment") {
    return npmSupplyChainAssessment({ pairing, parameters, signal });
  }
  if (capabilityId === "sensitive_file_mode_assessment") {
    return sensitiveFileModeAssessment({ pairing, parameters, signal });
  }
  if (capabilityId === "workspace_file_inspection") {
    return workspaceFileInspection({ pairing, parameters, signal });
  }
  if (capabilityId === "workspace_text_search") {
    return workspaceTextSearch({ pairing, parameters, signal });
  }
  if (capabilityId === "workspace_directory_inventory") {
    return workspaceDirectoryInventory({ pairing, parameters });
  }
  if (capabilityId === "macos_security_posture") {
    return macosSecurityPosture({ pairing, parameters });
  }
  if (capabilityId === "macos_network_listeners") {
    return macosNetworkListeners({ pairing, parameters });
  }
  if (capabilityId === "macos_persistence_inventory") {
    return macosPersistenceInventory({ pairing, parameters });
  }
  return fileModeOwnerOnly({ pairing, parameters, signal });
}
