{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "hooks",
  "type": "registry:item",
  "description": "Session-start Baseline check and edited-file format/lint hooks, registered for Claude, Codex, Cursor, and OpenCode.",
  "title": "Harness hooks",
  "files": [
    {
      "path": "hooks/scaffold-update-check.mjs",
      "content": "#!/usr/bin/env node\n\n// Session-start Baseline check (ARC-009, FLOW-004). Keys only on `hi check --json` `status`\n// and never claims drift is absent: `hi check` compares versions, it does not run the Drift Check.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\n\nconst installedRecordPath = \".devpunks/installed.json\";\n// Below the 60 s harness timeout so the hook reports instead of being killed.\nconst checkTimeoutMs = 45_000;\nconst notInstalledMessage =\n  \"Harness Baseline not installed in this worktree; run hi update (or hi init).\";\nconst noStatusMessage = \"hi check did not return a status. Drift was not checked.\";\n\nconst statusMessages = {\n  current: ({ installed }) => `Harness Baseline ${installed} is current.`,\n  \"not-installed\": () => notInstalledMessage,\n  unavailable: ({ installed }) =>\n    `Harness Registry unavailable. Installed Baseline: ${installed}. Drift was not checked.`,\n  \"update-available\": ({ installed, latest }) =>\n    `Harness Baseline update available: ${installed} -> ${latest}. Run hi update.`,\n};\n\nfunction readStdinJson() {\n  try {\n    return JSON.parse(readFileSync(0, \"utf-8\"));\n  } catch {\n    return {};\n  }\n}\n\nfunction repoRoot(cwd) {\n  const result = spawnSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], {\n    cwd,\n    encoding: \"utf-8\",\n    stdio: [\"ignore\", \"pipe\", \"ignore\"],\n  });\n  return (result.status === 0 && result.stdout.trim()) || cwd;\n}\n\nfunction runCheckCommand(root) {\n  for (const command of [\"hi\", \"hint\"]) {\n    const result = spawnSync(command, [\"check\", \"--json\"], {\n      cwd: root,\n      encoding: \"utf-8\",\n      env: { ...process.env, CI: \"1\", NO_COLOR: \"1\" },\n      stdio: [\"ignore\", \"pipe\", \"ignore\"],\n      timeout: checkTimeoutMs,\n    });\n    if (result.error?.code !== \"ENOENT\") {\n      return result.stdout ?? \"\";\n    }\n  }\n  return \"\";\n}\n\nfunction parseCheckResult(stdout) {\n  try {\n    const result = JSON.parse(stdout);\n    return result !== null && typeof result === \"object\" && Object.hasOwn(statusMessages, result.status)\n      ? result\n      : null;\n  } catch {\n    return null;\n  }\n}\n\nfunction checkBaseline(root) {\n  if (!existsSync(path.join(root, installedRecordPath))) {\n    return { message: notInstalledMessage, status: \"not-installed\" };\n  }\n\n  const result = parseCheckResult(runCheckCommand(root));\n  if (result === null) {\n    return { message: noStatusMessage, status: \"no-status\" };\n  }\n\n  const version = (value) => (typeof value === \"string\" && value.length > 0 ? value : \"unknown\");\n  return {\n    message: statusMessages[result.status]({\n      installed: version(result.installed),\n      latest: version(result.latest),\n    }),\n    status: result.status,\n  };\n}\n\nfunction formatForHarness(message, harness) {\n  if (harness === \"cursor\") {\n    return JSON.stringify({\n      additional_context: message,\n      agent_message: message,\n      continue: true,\n      user_message: message,\n    });\n  }\n  return message;\n}\n\nfunction rootFromInput(input) {\n  const candidates = [\n    input.cwd,\n    input.workspace_root,\n    process.env.CLAUDE_PROJECT_DIR,\n    process.env.PWD,\n    process.cwd(),\n  ].filter((value) => typeof value === \"string\" && value.length > 0);\n\n  return repoRoot(candidates[0]);\n}\n\nfunction main() {\n  const harness = process.argv[2] ?? \"plain\";\n  const { message } = checkBaseline(rootFromInput(readStdinJson()));\n  process.stdout.write(`${formatForHarness(message, harness)}\\n`);\n}\n\n// OpenCode loads every export of a plugin module as a plugin function; export nothing else.\nexport const ScaffoldUpdateCheckPlugin = async ({ client, directory, worktree }) => ({\n  event: async ({ event }) => {\n    if (event.type !== \"session.created\") {\n      return;\n    }\n\n    const result = checkBaseline(repoRoot(worktree || directory || process.cwd()));\n    await client.app.log({\n      body: {\n        level: result.status === \"current\" ? \"info\" : \"warn\",\n        message: result.message,\n        service: \"scaffold-update-check\",\n      },\n    });\n  },\n});\n\nconst invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : \"\";\nconst modulePath = import.meta.filename;\n\nif (invokedPath && path.basename(invokedPath) === path.basename(modulePath)) {\n  main();\n}\n",
      "type": "registry:file",
      "target": "~/.agents/hooks/scaffold-update-check.mjs"
    },
    {
      "path": "hooks/format-edited-file.mjs",
      "content": "#!/usr/bin/env node\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n  mkdtempSync,\n  closeSync,\n  constants,\n  existsSync,\n  fstatSync,\n  lstatSync,\n  openSync,\n  readSync,\n  readFileSync,\n  realpathSync,\n  rmSync,\n  writeFileSync,\n} from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { pathToFileURL, fileURLToPath } from \"node:url\";\n// Helpers live in a sibling module: OpenCode loads every export of this plugin module as a plugin.\nimport {\n  codexStateFilePath,\n  contentHash,\n  copyLintMirror,\n  providerFeedbackMessage,\n  renderProviderFeedback,\n} from \"./format-edited-file-core.mjs\";\n\nconst javascriptFormattableSuffixes = new Set([\n  \".ts\",\n  \".tsx\",\n  \".js\",\n  \".jsx\",\n  \".mjs\",\n  \".cjs\",\n  \".json\",\n]);\nconst javascriptLintableSuffixes = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\nconst pythonFormattableSuffixes = new Set([\".py\"]);\nconst formattableSuffixes = new Set([\n  ...javascriptFormattableSuffixes,\n  ...pythonFormattableSuffixes,\n]);\nconst ignoredParts = new Set([\".git\", \"node_modules\", \".next\", \"dist\"]);\nconst installedRecordPath = \".devpunks/installed.json\";\n// Copied and Built Artifacts are Baseline-owned; Authored Artifacts belong to the repository.\nconst protectedArtifacts = new Set([\"copied\", \"built\"]);\nconst productRoots = new Set([\"apps\", \"packages\"]);\nconst backendWorkspaceSegments = new Set([\"api\", \"backend\", \"server\", \"services\"]);\n\nfunction readStdinJson() {\n  try {\n    return JSON.parse(readFileSync(0, \"utf8\"));\n  } catch {\n    return {};\n  }\n}\n\nfunction runGit(args, cwd) {\n  const result = spawnSync(\"git\", [\"-C\", cwd, ...args], {\n    encoding: \"utf8\",\n    stdio: [\"ignore\", \"pipe\", \"ignore\"],\n  });\n\n  return result.status === 0 ? result.stdout : null;\n}\n\nfunction repoRoot(cwd) {\n  return runGit([\"rev-parse\", \"--show-toplevel\"], cwd)?.trim() ?? \"\";\n}\n\nfunction normalizeRelativePath(root, filePath, managedPaths, caseInsensitivePaths) {\n  if (!filePath) {\n    return null;\n  }\n\n  const absolutePath = path.isAbsolute(filePath) ? filePath : path.join(root, filePath);\n  const relativePath = path.relative(root, absolutePath);\n\n  if (!relativePath || relativePath.startsWith(\"..\") || path.isAbsolute(relativePath)) {\n    return null;\n  }\n\n  let canonicalRelativePath;\n  try {\n    canonicalRelativePath = path.relative(\n      realpathSync.native(root),\n      realpathSync.native(absolutePath),\n    );\n    if (\n      !canonicalRelativePath ||\n      canonicalRelativePath.startsWith(\"..\") ||\n      path.isAbsolute(canonicalRelativePath)\n    ) {\n      return null;\n    }\n  } catch {\n    return null;\n  }\n\n  const normalizedPath = relativePath.split(path.sep).join(\"/\");\n  const canonicalNormalizedPath = canonicalRelativePath.split(path.sep).join(\"/\");\n  if (\n    managedPathKey(normalizedPath, caseInsensitivePaths) !==\n    managedPathKey(canonicalNormalizedPath, caseInsensitivePaths)\n  ) {\n    return null;\n  }\n  const extension = path.extname(normalizedPath);\n\n  if (!formattableSuffixes.has(extension)) {\n    return null;\n  }\n\n  if (normalizedPath.split(\"/\").some((part) => ignoredParts.has(part))) {\n    return null;\n  }\n\n  const normalizedPathKey = managedPathKey(normalizedPath, caseInsensitivePaths);\n  if (\n    normalizedPathKey === managedPathKey(installedRecordPath, caseInsensitivePaths) ||\n    managedPaths.has(normalizedPathKey)\n  ) {\n    return null;\n  }\n\n  if (!existsSync(path.join(root, normalizedPath))) {\n    return null;\n  }\n\n  return normalizedPath;\n}\n\nfunction alternateCasePath(filePath) {\n  const basename = path.basename(filePath);\n  const alternateBasename =\n    basename === basename.toUpperCase() ? basename.toLowerCase() : basename.toUpperCase();\n  return path.join(path.dirname(filePath), alternateBasename);\n}\n\nfunction pathCaseSemantics(root) {\n  const canonicalProbe = path.join(root, path.dirname(installedRecordPath));\n  const alternateProbe = alternateCasePath(canonicalProbe);\n  try {\n    return realpathSync.native(alternateProbe) === realpathSync.native(canonicalProbe)\n      ? \"case-insensitive\"\n      : \"case-sensitive\";\n  } catch (error) {\n    return error && typeof error === \"object\" && error.code === \"ENOENT\"\n      ? \"case-sensitive\"\n      : \"unknown\";\n  }\n}\n\nfunction managedPathKey(filePath, caseInsensitivePaths) {\n  return caseInsensitivePaths ? filePath.toLowerCase() : filePath;\n}\n\nfunction isLintablePath(relativePath) {\n  const parts = relativePath.split(\"/\");\n  return (\n    parts.length > 0 &&\n    productRoots.has(parts[0]) &&\n    javascriptLintableSuffixes.has(path.extname(relativePath))\n  );\n}\n\nfunction isPythonPath(relativePath) {\n  return pythonFormattableSuffixes.has(path.extname(relativePath));\n}\n\nfunction runCommand(root, args, stdio = [\"ignore\", \"pipe\", \"pipe\"]) {\n  const result = spawnSync(args[0], args.slice(1), {\n    cwd: root,\n    stdio,\n    encoding: \"utf8\",\n    maxBuffer: 16 * 1024 * 1024,\n  });\n\n  return {\n    ok: result.status === 0,\n    status: result.status,\n    error: result.error,\n    stdout: result.stdout ?? \"\",\n    stderr: result.stderr ?? \"\",\n  };\n}\n\nfunction workspaceRelativePath(workspace, root, relativePath) {\n  const workspacePath = path.relative(workspace, path.join(root, relativePath));\n  return workspacePath.split(path.sep).join(\"/\");\n}\n\nfunction toolCommand(directory, tool, args) {\n  const root = repoRoot(directory);\n  let current = directory;\n  while (true) {\n    const manifest = path.join(current, \"node_modules\", tool, \"package.json\");\n    if (existsSync(manifest)) {\n      const value = JSON.parse(readFileSync(manifest, \"utf8\"));\n      const bin = typeof value.bin === \"string\" ? value.bin : value.bin?.[tool];\n      if (value.name !== tool || typeof bin !== \"string\" || path.isAbsolute(bin) || bin.split(/[\\\\/]/u).includes(\"..\")) throw new Error(`Invalid repository-local ${tool} executable`);\n      return [path.resolve(path.dirname(manifest), bin), ...args];\n    }\n    if (current === root || path.dirname(current) === current) break;\n    current = path.dirname(current);\n  }\n  // An intentionally missing local path becomes a normal operational failure in runCommand.\n  return [path.join(root || directory, \"node_modules/.bin\", tool), ...args];\n}\n\nfunction nearestPythonProject(root, relativePath) {\n  const parts = relativePath.split(\"/\");\n\n  for (let index = parts.length - 1; index > 0; index -= 1) {\n    const projectPath = parts.slice(0, index).join(\"/\");\n    if (existsSync(path.join(root, projectPath, \"pyproject.toml\"))) {\n      return projectPath;\n    }\n  }\n\n  if (parts.length >= 2 && productRoots.has(parts[0]) && backendWorkspaceSegments.has(parts[1])) {\n    return `${parts[0]}/${parts[1]}`;\n  }\n\n  return \".\";\n}\n\nfunction formatCommandForPath(root, relativePath) {\n  if (isPythonPath(relativePath)) {\n    return [\n      \"uv\",\n      \"run\",\n      \"--project\",\n      nearestPythonProject(root, relativePath),\n      \"ruff\",\n      \"format\",\n      \"--stdin-filename\",\n      relativePath,\n      \"-\",\n    ];\n  }\n\n  return toolCommand(root, \"oxfmt\", [\"--stdin-filepath\", relativePath]);\n}\n\nfunction lintCommandForPath(root, relativePath, workspaceRelative = false) {\n  if (isPythonPath(relativePath)) {\n    return [\n      \"uv\",\n      \"run\",\n      \"--project\",\n      nearestPythonProject(root, relativePath),\n      \"ruff\",\n      \"check\",\n      \"--fix\",\n      \"--stdin-filename\",\n      relativePath,\n      \"-\",\n    ];\n  }\n\n  if (!workspaceRelative && !isLintablePath(relativePath)) {\n    return null;\n  }\n  if (workspaceRelative && !javascriptLintableSuffixes.has(path.extname(relativePath))) {\n    return null;\n  }\n\n  return toolCommand(root, \"oxlint\", [relativePath]);\n}\n\nfunction normalizeManagedPath(filePath) {\n  if (typeof filePath !== \"string\" || filePath.length === 0 || filePath.includes(\"\\0\")) {\n    return null;\n  }\n\n  const posixPath = filePath.replaceAll(\"\\\\\", \"/\");\n  if (path.posix.isAbsolute(posixPath) || path.win32.parse(filePath).root !== \"\") {\n    return null;\n  }\n\n  const normalizedPath = path.posix.normalize(posixPath);\n  if (normalizedPath === \".\" || normalizedPath === \"..\" || normalizedPath.startsWith(\"../\")) {\n    return null;\n  }\n\n  return normalizedPath;\n}\n\n// A missing or invalid Installed Record means nothing is managed; it never blocks an edit.\nfunction loadManagedPaths(root, caseInsensitivePaths) {\n  const record = loadJson(path.join(root, installedRecordPath));\n  const paths = record?.paths;\n  if (!paths || typeof paths !== \"object\" || Array.isArray(paths)) {\n    return new Set();\n  }\n\n  const managedPaths = new Set();\n  for (const [filePath, entry] of Object.entries(paths)) {\n    const normalizedPath = normalizeManagedPath(filePath);\n    if (!normalizedPath || typeof entry?.artifact !== \"string\") {\n      return new Set();\n    }\n    if (protectedArtifacts.has(entry.artifact)) {\n      managedPaths.add(managedPathKey(normalizedPath, caseInsensitivePaths));\n    }\n  }\n\n  return managedPaths;\n}\n\nfunction readDescriptor(descriptor) {\n  const size = fstatSync(descriptor).size;\n  const content = Buffer.alloc(size);\n  let offset = 0;\n\n  while (offset < size) {\n    const bytesRead = readSync(descriptor, content, offset, size - offset, offset);\n    if (bytesRead === 0) {\n      throw new Error(\"Edited file changed while reading\");\n    }\n    offset += bytesRead;\n  }\n\n  return content;\n}\n\nfunction sameRegularFile(filePath, opened) {\n  try {\n    const current = lstatSync(filePath);\n    return (\n      current.isFile() &&\n      current.nlink === 1 &&\n      current.dev === opened.dev &&\n      current.ino === opened.ino\n    );\n  } catch {\n    return false;\n  }\n}\n\nfunction openFormattingTarget(filePath, expectedFingerprint) {\n  let descriptor;\n  try {\n    const before = lstatSync(filePath);\n    if (!before.isFile() || before.nlink !== 1) {\n      return null;\n    }\n\n    descriptor = openSync(filePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n    const opened = fstatSync(descriptor);\n    if (!opened.isFile() || opened.nlink !== 1 || !sameRegularFile(filePath, opened)) {\n      closeSync(descriptor);\n      return null;\n    }\n\n    const content = readDescriptor(descriptor);\n    const fingerprint = contentHash(content);\n    if (typeof expectedFingerprint === \"string\" && fingerprint !== expectedFingerprint) {\n      closeSync(descriptor);\n      return null;\n    }\n\n    return { content, descriptor, fingerprint, opened };\n  } catch {\n    if (descriptor !== undefined) {\n      closeSync(descriptor);\n    }\n    return null;\n  }\n}\n\nfunction runTransformCommand(root, command, content) {\n  const [executable, ...args] = command;\n  const result = spawnSync(executable, args, {\n    cwd: root,\n    input: content,\n    maxBuffer: Math.max(16 * 1024 * 1024, content.length * 4),\n    stdio: [\"pipe\", \"pipe\", \"pipe\"],\n    encoding: \"buffer\",\n  });\n\n  return {\n    ok: result.status === 0,\n    status: result.status,\n    error: result.error,\n    stderr: result.stderr?.toString() ?? \"\",\n    output: result.error === undefined && Buffer.isBuffer(result.stdout) ? result.stdout : content,\n  };\n}\n\nfunction lintDiagnosticRule(code) {\n  if (typeof code !== \"string\") {\n    return \"\";\n  }\n\n  const match = code.match(/\\(([^()]+)\\)$/);\n  return match?.[1] ?? code;\n}\n\nfunction normalizeDiagnostic(diagnostic, root, fallbackPath, temporaryPath = null) {\n  if (!diagnostic || typeof diagnostic !== \"object\") {\n    return null;\n  }\n\n  let file = typeof diagnostic.filename === \"string\" ? diagnostic.filename : fallbackPath;\n  if (temporaryPath && file === temporaryPath) {\n    file = fallbackPath;\n  }\n  const normalizedFile = normalizeEditedPath(file, root) ?? fallbackPath;\n  const label = Array.isArray(diagnostic.labels) ? diagnostic.labels[0] : null;\n  const span = label?.span && typeof label.span === \"object\" ? label.span : {};\n  const normalized = {\n    file: normalizedFile,\n    rule: lintDiagnosticRule(diagnostic.code),\n    severity: typeof diagnostic.severity === \"string\" ? diagnostic.severity : \"error\",\n    line: Number.isInteger(span.line) ? span.line : null,\n    column: Number.isInteger(span.column) ? span.column : null,\n    message: typeof diagnostic.message === \"string\" ? diagnostic.message : \"Lint finding\",\n  };\n\n  if (typeof diagnostic.help === \"string\" && diagnostic.help.length > 0) {\n    normalized.help = diagnostic.help;\n  }\n  if (typeof diagnostic.url === \"string\" && diagnostic.url.length > 0) {\n    normalized.documentation = diagnostic.url;\n  }\n  if (Number.isInteger(span.offset)) normalized.offset = span.offset;\n  if (Number.isInteger(span.length)) normalized.length = span.length;\n  return normalized;\n}\n\nfunction normalizeManagedDiagnostics(report, root, scope, fallbackPath) {\n  if (!Array.isArray(report)) return {ok: false, error: \"Oxlint did not return validated diagnostics\"};\n  const diagnostics = [];\n  for (const diagnostic of report) {\n    let filename = fallbackPath;\n    if (typeof diagnostic.filename === \"string\" && diagnostic.filename.length > 0) {\n      filename = path.relative(root, path.resolve(root, scope, diagnostic.filename)).split(path.sep).join(\"/\");\n      if (filename === \"..\" || filename.startsWith(\"../\") || path.isAbsolute(filename)) return {ok: false, error: \"Oxlint diagnostic escaped the managed repository\"};\n    }\n    diagnostics.push(normalizeDiagnostic({...diagnostic, filename}, root, fallbackPath));\n  }\n  return {ok: true, diagnostics};\n}\n\nasync function lintRuntime(root) {\n  const canonical = path.join(root, \".agents/scripts/managed-lint-runner.mjs\");\n  const local = new URL(\"../scripts/managed-lint-runner.mjs\", import.meta.url);\n  const runner = await import(existsSync(canonical) ? pathToFileURL(canonical).href : local.href);\n  const resolver = await import(existsSync(canonical) ? pathToFileURL(path.join(root, \".agents/scripts/managed-lint.mjs\")).href : new URL(\"../scripts/managed-lint.mjs\", import.meta.url).href);\n  return { ...runner, ...resolver };\n}\n\nasync function selectedLint(root, filePaths) {\n  try {\n    const runtime = await lintRuntime(root);\n    const paths = filePaths.map((file) => path.relative(root, path.resolve(root, file)).split(path.sep).join(\"/\"));\n    const resolution = await runtime.loadManagedLint(root, paths);\n    if (resolution.status === \"disabled\") return { runtime, routes: [] };\n    if (resolution.status !== \"ready\") throw new Error(resolution.diagnostics.join(\"\\n\"));\n    return { runtime, routes: resolution.routes };\n  } catch (error) {\n    return { failure: emptyLintSummary(\"operational_failure\", [{ stage: \"config-load\", command: \"managed lint selection\", message: error.message }]) };\n  }\n}\n\n// Python shares quality exclusions, but does not require JavaScript owner selection.\nfunction qualityExclusions(root) {\n  let settings;\n  try {\n    settings = JSON.parse(readFileSync(path.join(root, \".devpunks/settings.json\"), \"utf8\"));\n  } catch (error) {\n    if (error?.code === \"ENOENT\") return [];\n    throw error;\n  }\n  const record = (value) => value !== null && typeof value === \"object\" && !Array.isArray(value);\n  if (!record(settings) || (settings.lint !== undefined && !record(settings.lint))) {\n    throw new TypeError(\"Managed quality settings and lint must be objects\");\n  }\n  const exclude = settings.lint?.exclude;\n  if (exclude === undefined) return [];\n  if (!Array.isArray(exclude) || !exclude.every((pattern) =>\n    typeof pattern === \"string\" && pattern.length > 0 && !pattern.startsWith(\"!\") &&\n    !pattern.includes(\"\\\\\") && !path.posix.isAbsolute(pattern) &&\n    pattern.split(\"/\").every((part) => part !== \"..\" && part !== \"\") &&\n    path.posix.normalize(pattern) === pattern\n  )) throw new TypeError(\"lint.exclude must be a list of repository-relative patterns.\");\n  return exclude;\n}\n\nasync function selectedQuality(root, filePaths) {\n  const caseSemantics = pathCaseSemantics(root);\n  if (caseSemantics === \"unknown\") {\n    return {failure: emptyLintSummary(\"operational_failure\", [\n      {\n        stage: \"config-load\",\n        command: \"path case semantics\",\n        message: \"Unable to determine path case semantics\",\n      },\n    ])};\n  }\n\n  const caseInsensitivePaths = caseSemantics === \"case-insensitive\";\n  const managedPaths = loadManagedPaths(root, caseInsensitivePaths);\n\n  try {\n    const runtime = await lintRuntime(root);\n    const exclude = qualityExclusions(root);\n    const eligible = [...new Set(filePaths.map((file) =>\n      normalizeRelativePath(root, file, managedPaths, caseInsensitivePaths)\n    ).filter((file) => file !== null && !runtime.isManagedQualityPathExcluded({path: file, exclude})))];\n    const nonPythonPaths = filePaths.filter((file) => !isPythonPath(file));\n    const selection = nonPythonPaths.length > 0\n      ? await selectedLint(root, nonPythonPaths)\n      : {runtime, routes: []};\n    // Keep raw resolver-owned dependency triggers, including scaffold metadata.\n    // The resolver handles excluded-only source; unrelated non-JS files stay independent.\n    const requiresSelection = nonPythonPaths.some((file) =>\n      javascriptFormattableSuffixes.has(path.extname(file))\n    );\n    const javascriptPaths = selection.failure && !requiresSelection\n      ? [] : nonPythonPaths;\n    const routes = selection.routes ?? [];\n    const selectedFiles = new Set(routes.flatMap((route) => route.files));\n    return {\n      runtime, routes, javascriptPaths,\n      files: eligible.filter((file) => isPythonPath(file) || selectedFiles.has(file)),\n      failures: javascriptPaths.length > 0 ? selection.failure?.failures ?? [] : [],\n    };\n  } catch (error) {\n    return {failure: emptyLintSummary(\"operational_failure\", [{stage: \"config-load\", command: \"managed quality exclusions\", message: error.message}])};\n  }\n}\n\nasync function runSafeJavascriptLint(workspace, root, relativePath, content, route, runtime) {\n  const mirror = mkdtempSync(path.join(os.tmpdir(), \"hi-lint-mirror-\"));\n  let command;\n  try {\n    copyLintMirror(root, mirror, [relativePath, route.config, ...route.inputs]);\n    for (const input of [route.config, ...route.inputs]) {\n      if (existsSync(path.join(root, input)) && !existsSync(path.join(mirror, input))) throw new Error(`Required lint input is excluded from safe mirror: ${input}`);\n    }\n    const target = path.join(mirror, relativePath);\n    if (!lstatSync(target).isFile()) throw new Error(\"Temporary lint target must be a copied regular file\");\n    writeFileSync(target, content);\n    command = await runtime.buildManagedLintCommand({root: mirror, route, output: \"json\", logicalSourcePath: relativePath, physicalInputPath: target});\n    if (command.status !== \"ready\") throw new Error(command.diagnostics.join(\"\\n\"));\n    const fixed = runtime.executeManagedLintCommand({root: mirror, command: {...command, args: [\"--fix\", ...command.args]}});\n    if (fixed.code === 2) throw new Error([\"Oxlint fix failed\", fixed.stdout, fixed.stderr].filter(Boolean).join(\"\\n\"));\n    const fixedDiagnostics = normalizeManagedDiagnostics(fixed.diagnostics, mirror, route.scope, relativePath);\n    if (!fixedDiagnostics.ok) throw new Error(fixedDiagnostics.error);\n    const result = runtime.executeManagedLintCommand({root: mirror, command});\n    if (result.code === 2) throw new Error([\"Oxlint verification failed\", result.stdout, result.stderr].filter(Boolean).join(\"\\n\"));\n    const parsed = normalizeManagedDiagnostics(result.diagnostics, mirror, route.scope, relativePath);\n    if (!parsed.ok) throw new Error(parsed.error);\n    return {ok: true, content: readFileSync(target), diagnostics: parsed.diagnostics};\n  } catch (error) {\n    return {ok: false, stage: \"lint-verify\", command: command ? commandText([command.executable, ...command.args]) : \"managed lint mirror\", error: error.message};\n  } finally { rmSync(mirror, {force: true, recursive: true}); }\n}\n\nconst publicationWorkerScript = `\nimport { createHash } from \"node:crypto\";\nimport {\n  closeSync,\n  constants,\n  fchmodSync,\n  fstatSync,\n  fsyncSync,\n  linkSync,\n  lstatSync,\n  openSync,\n  readFileSync,\n  readSync,\n  renameSync,\n  statSync,\n  unlinkSync,\n  writeSync,\n} from \"node:fs\";\n\nconst request = JSON.parse(process.argv[1]);\nconst content = readFileSync(0);\nlet claimIdentity;\nlet claimPath = request.claim;\nlet originalDescriptor;\nlet publishedDescriptor;\nlet publishedIdentity;\nlet stageDescriptor;\nlet stageIdentity;\nlet stagePath = request.stage;\n\nconst assertParentIdentity = () => {\n  const current = statSync(\".\");\n  if (current.dev !== request.parent.device || current.ino !== request.parent.inode) {\n    throw new Error(\"Formatting parent identity changed\");\n  }\n};\nconst sameRegularFile = (filePath, expected) => {\n  const current = lstatSync(filePath, { throwIfNoEntry: false });\n  return (\n    current !== undefined &&\n    current.isFile() &&\n    current.nlink === 1 &&\n    current.dev === expected.device &&\n    current.ino === expected.inode\n  );\n};\nconst descriptorHash = (descriptor) => {\n  const size = fstatSync(descriptor).size;\n  const buffer = Buffer.alloc(size);\n  let offset = 0;\n  while (offset < size) {\n    const bytesRead = readSync(descriptor, buffer, offset, size - offset, offset);\n    if (bytesRead === 0) throw new Error(\"Formatting target changed while reading\");\n    offset += bytesRead;\n  }\n  return createHash(\"sha256\").update(buffer).digest(\"hex\");\n};\nconst closeDescriptors = () => {\n  if (publishedDescriptor !== undefined) closeSync(publishedDescriptor);\n  if (originalDescriptor !== undefined) closeSync(originalDescriptor);\n  if (stageDescriptor !== undefined) closeSync(stageDescriptor);\n  publishedDescriptor = undefined;\n  originalDescriptor = undefined;\n  stageDescriptor = undefined;\n};\n\ntry {\n  assertParentIdentity();\n  stageDescriptor = openSync(\n    stagePath,\n    constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0),\n    request.targetIdentity.mode,\n  );\n  const staged = fstatSync(stageDescriptor);\n  if (!staged.isFile() || staged.nlink !== 1) throw new Error(\"Formatting stage is unsafe\");\n  stageIdentity = { device: staged.dev, inode: staged.ino };\n  let offset = 0;\n  while (offset < content.length) {\n    offset += writeSync(stageDescriptor, content, offset, content.length - offset, offset);\n  }\n  fchmodSync(stageDescriptor, request.targetIdentity.mode & 0o7777);\n  fsyncSync(stageDescriptor);\n  closeSync(stageDescriptor);\n  stageDescriptor = undefined;\n  assertParentIdentity();\n\n  originalDescriptor = openSync(\n    request.target,\n    constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),\n  );\n  const original = fstatSync(originalDescriptor);\n  if (\n    !original.isFile() ||\n    original.nlink !== 1 ||\n    original.dev !== request.targetIdentity.device ||\n    original.ino !== request.targetIdentity.inode ||\n    descriptorHash(originalDescriptor) !== request.fingerprint ||\n    !sameRegularFile(request.target, request.targetIdentity)\n  ) {\n    throw new Error(\"Formatting target changed before publication\");\n  }\n\n  if (lstatSync(claimPath, { throwIfNoEntry: false }) !== undefined) {\n    throw new Error(\"Formatting claim path already exists\");\n  }\n  claimIdentity = request.targetIdentity;\n  renameSync(request.target, claimPath);\n  const claimed = lstatSync(claimPath);\n  claimIdentity = { device: claimed.dev, inode: claimed.ino };\n  if (\n    !sameRegularFile(claimPath, request.targetIdentity) ||\n    descriptorHash(originalDescriptor) !== request.fingerprint ||\n    lstatSync(request.target, { throwIfNoEntry: false }) !== undefined\n  ) {\n    throw new Error(\"Formatting target changed while being claimed\");\n  }\n  assertParentIdentity();\n\n  linkSync(stagePath, request.target);\n  publishedIdentity = stageIdentity;\n  unlinkSync(stagePath);\n  stagePath = undefined;\n  stageIdentity = undefined;\n  publishedDescriptor = openSync(\n    request.target,\n    constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),\n  );\n  const published = fstatSync(publishedDescriptor);\n  if (\n    !sameRegularFile(claimPath, request.targetIdentity) ||\n    descriptorHash(originalDescriptor) !== request.fingerprint ||\n    !published.isFile() ||\n    published.nlink !== 1 ||\n    published.dev !== publishedIdentity.device ||\n    published.ino !== publishedIdentity.inode ||\n    descriptorHash(publishedDescriptor) !== request.outputFingerprint ||\n    !sameRegularFile(request.target, publishedIdentity)\n  ) {\n    throw new Error(\"Formatting target changed across publication\");\n  }\n  assertParentIdentity();\n\n  closeDescriptors();\n  unlinkSync(claimPath);\n  claimPath = undefined;\n  claimIdentity = undefined;\n  publishedIdentity = undefined;\n} catch (error) {\n  closeDescriptors();\n  if (claimIdentity !== undefined && claimPath !== undefined) {\n    try {\n      const claim = lstatSync(claimPath, { throwIfNoEntry: false });\n      if (\n        claim !== undefined &&\n        claim.dev === claimIdentity.device &&\n        claim.ino === claimIdentity.inode &&\n        claim.isFile() &&\n        lstatSync(request.target, { throwIfNoEntry: false }) === undefined\n      ) {\n        linkSync(claimPath, request.target);\n        unlinkSync(claimPath);\n        claimPath = undefined;\n      }\n    } catch {\n      // Retain the exact claim when it cannot be restored without replacement.\n    }\n  }\n  if (stageIdentity !== undefined && stagePath !== undefined) {\n    try {\n      const stage = lstatSync(stagePath, { throwIfNoEntry: false });\n      if (\n        stage !== undefined &&\n        stage.dev === stageIdentity.device &&\n        stage.ino === stageIdentity.inode\n      ) {\n        unlinkSync(stagePath);\n        stagePath = undefined;\n      }\n    } catch {\n      // A private-path collision is not producer-owned.\n    }\n  }\n  process.exitCode = 1;\n}\n`;\n\nfunction publishFormattedContent(filePath, target, content) {\n  const directory = path.dirname(filePath);\n  const parent = lstatSync(directory);\n  if (!parent.isDirectory()) return false;\n  const suffix = randomUUID();\n  const request = {\n    claim: `.hi-format-claim-${suffix}.tmp`,\n    fingerprint: target.fingerprint,\n    outputFingerprint: contentHash(content),\n    parent: { device: parent.dev, inode: parent.ino },\n    stage: `.hi-format-stage-${suffix}.tmp`,\n    target: path.basename(filePath),\n    targetIdentity: {\n      device: target.opened.dev,\n      inode: target.opened.ino,\n      mode: target.opened.mode,\n    },\n  };\n  const result = spawnSync(\n    process.execPath,\n    [\"--input-type=module\", \"--eval\", publicationWorkerScript, JSON.stringify(request)],\n    { cwd: directory, input: content, stdio: [\"pipe\", \"ignore\", \"ignore\"] },\n  );\n  return result.error === undefined && result.status === 0;\n}\n\nfunction emptyLintSummary(result = \"clean\", failures = []) {\n  const summary = {\n    format_failed: [],\n    formatted: [],\n    lint_failed: [],\n    diagnostics: [],\n    failures,\n    result,\n    exhausted: false,\n    status: result === \"operational_failure\" ? \"operational-failure\" : result,\n    files: [],\n  };\n  if (result === \"operational_failure\" && failures[0]) {\n    summary.stage = failures[0].stage ?? \"lint-verify\";\n    summary.command = failures[0].command ?? \"\";\n    if (Number.isInteger(failures[0].exitCode)) summary.exitCode = failures[0].exitCode;\n    summary.message = failures[0].message ?? \"Lint operation failed\";\n  }\n  return summary;\n}\n\nfunction commandText(command) {\n  return Array.isArray(command) ? command.join(\" \") : String(command ?? \"\");\n}\n\nasync function formatAndLintFiles(root, filePaths, expectedFingerprints = null) {\n  const selection = await selectedQuality(root, filePaths);\n  if (selection.failure) return selection.failure;\n  const normalizedFiles = selection.files;\n\n  const formatted = [];\n  const formatFailed = [];\n  const lintFailed = [];\n  const diagnostics = [];\n  const failures = [...selection.failures];\n\n  for (const relativePath of normalizedFiles) {\n    const expectedFingerprint = expectedFingerprints?.[relativePath];\n    if (expectedFingerprints !== null && typeof expectedFingerprint !== \"string\") {\n      continue;\n    }\n\n    const absolutePath = path.join(root, relativePath);\n    const target = openFormattingTarget(absolutePath, expectedFingerprint);\n    if (target === null) {\n      failures.push({\n        kind: \"race\",\n        stage: \"lint-verify\",\n        file: relativePath,\n        command: \"open edited file\",\n        message: \"Edited file changed before formatting\",\n      });\n      continue;\n    }\n\n    const route = selection.routes.find((item) => item.files.includes(relativePath));\n    const workspace = isPythonPath(relativePath) ? root : path.resolve(root, route.scope);\n    const workspacePath = workspaceRelativePath(workspace, root, relativePath);\n    let formatCommand;\n    try { formatCommand = formatCommandForPath(workspace, workspacePath); }\n    catch (error) {\n      closeSync(target.descriptor);\n      failures.push({kind: \"format\", stage: \"format\", file: relativePath, command: \"local formatter\", message: error.message});\n      continue;\n    }\n\n    // Keep mutating tools off the live path; stage output before claiming the validated target.\n    const formatResult = runTransformCommand(\n      workspace,\n      formatCommand,\n      target.content,\n    );\n\n    if (!formatResult.ok) {\n      closeSync(target.descriptor);\n      formatFailed.push(relativePath);\n      failures.push({\n        kind: \"format\",\n        stage: \"format\",\n        file: relativePath,\n        command: commandText(formatCommand),\n        exitCode: formatResult.status,\n        message: formatResult.error?.message ?? (formatResult.stderr || \"Oxfmt failed\"),\n      });\n      continue;\n    }\n\n    const lintCommand = isPythonPath(relativePath) ? lintCommandForPath(workspace, workspacePath, true) : javascriptLintableSuffixes.has(path.extname(relativePath)) ? [\"managed lint\"] : null;\n    let formattedContent = formatResult.output;\n    let lintResult = null;\n    if (lintCommand !== null && isPythonPath(relativePath)) {\n      lintResult = runTransformCommand(workspace, lintCommand, formattedContent);\n      if (lintResult.ok) {\n        formattedContent = lintResult.output;\n      }\n    } else if (lintCommand !== null) {\n      lintResult = await runSafeJavascriptLint(workspace, root, relativePath, formattedContent, route, selection.runtime);\n      if (lintResult.ok) {\n        formattedContent = lintResult.content;\n        diagnostics.push(...lintResult.diagnostics);\n      }\n    }\n\n    if (lintResult !== null && !lintResult.ok) {\n      closeSync(target.descriptor);\n      failures.push({\n        kind: \"lint\",\n        stage: lintResult.stage ?? \"lint-verify\",\n        file: relativePath,\n        command: lintResult.command ?? commandText(lintCommand),\n        ...(Number.isInteger(lintResult.exitCode) ? { exitCode: lintResult.exitCode } : {}),\n        message: lintResult.error ?? lintResult.error?.message ?? (lintResult.stderr || \"Oxlint failed\"),\n      });\n      continue;\n    }\n\n    const published = publishFormattedContent(absolutePath, target, formattedContent);\n    closeSync(target.descriptor);\n    if (!published) {\n      failures.push({\n        kind: \"publication\",\n        stage: \"lint-verify\",\n        file: relativePath,\n        command: \"atomic publication\",\n        message: \"Atomic publication failed\",\n      });\n      continue;\n    }\n\n    formatted.push(relativePath);\n\n    if (lintResult !== null && lintResult.diagnostics?.length > 0) {\n      lintFailed.push(relativePath);\n    }\n  }\n\n  if (selection.routes.some((route) => route.triggered)) {\n    const verified = await verifyLintFiles(root, filePaths);\n    const known = new Set(diagnostics.map((diagnostic) => JSON.stringify(diagnostic)));\n    for (const diagnostic of verified.diagnostics) {\n      if (!known.has(JSON.stringify(diagnostic))) diagnostics.push(diagnostic);\n    }\n    failures.push(...verified.failures);\n    for (const file of verified.lint_failed) if (!lintFailed.includes(file)) lintFailed.push(file);\n  }\n\n  const result =\n    failures.length > 0 ? \"operational_failure\" : diagnostics.length > 0 ? \"findings\" : \"clean\";\n  return {\n    format_failed: formatFailed,\n    formatted,\n    lint_failed: lintFailed,\n    diagnostics,\n    failures,\n    result,\n    exhausted: false,\n    status: result === \"operational_failure\" ? \"operational-failure\" : result,\n    files: result === \"findings\" ? [...new Set(diagnostics.map((diagnostic) => diagnostic.file))] : formatted,\n    ...(diagnostics.length > 0 ? { fingerprint: contentHash(JSON.stringify(diagnostics)), attempt: 1 } : {}),\n    ...(failures.length > 0\n      ? {\n          stage: failures[0].stage ?? \"lint-verify\",\n          command: failures[0].command ?? \"\",\n          ...(Number.isInteger(failures[0].exitCode) ? { exitCode: failures[0].exitCode } : {}),\n          message: failures[0].message ?? \"Lint operation failed\",\n        }\n      : {}),\n  };\n}\n\nfunction verifyPythonFile(root, relativePath) {\n  const command = [\"uv\", \"run\", \"--project\", nearestPythonProject(root, relativePath), \"ruff\", \"check\", \"--output-format\", \"json\", \"--stdin-filename\", relativePath, \"-\"];\n  const target = openFormattingTarget(path.join(root, relativePath));\n  if (target === null) return {failure: {stage: \"lint-verify\", file: relativePath, command: commandText(command), message: \"Edited file changed before verification\"}};\n  try {\n    const result = runTransformCommand(root, command, target.content);\n    if (result.error || ![0, 1].includes(result.status)) throw new Error(result.error?.message ?? (result.stderr || \"Ruff verification failed\"));\n    const report = JSON.parse(result.output.toString());\n    if (!Array.isArray(report) || report.some((item) => !item || typeof item.message !== \"string\" || typeof item.code !== \"string\" || !Number.isInteger(item.location?.row) || !Number.isInteger(item.location?.column))) throw new Error(\"Ruff returned invalid diagnostics\");\n    if (result.status !== 0 && report.length === 0) throw new Error(result.stderr || \"Ruff failed without diagnostics\");\n    return {diagnostics: report.map((item) => ({file: relativePath, rule: item.code, severity: \"error\", line: item.location.row, column: item.location.column, message: item.message, ...(typeof item.url === \"string\" ? {documentation: item.url} : {})}))};\n  } catch (error) {\n    return {failure: {stage: \"lint-verify\", file: relativePath, command: commandText(command), message: error.message}};\n  } finally { closeSync(target.descriptor); }\n}\n\nasync function verifyLintFiles(root, filePaths) {\n  const selection = await selectedQuality(root, filePaths);\n  if (selection.failure) return selection.failure;\n  const diagnostics = [];\n  const failures = [...selection.failures];\n  for (const file of selection.files.filter(isPythonPath)) {\n    const verified = verifyPythonFile(root, file);\n    if (verified.failure) failures.push(verified.failure);\n    else diagnostics.push(...verified.diagnostics);\n  }\n  if (selection.javascriptPaths.length > 0 && selection.failures.length === 0) {\n    const result = await selection.runtime.runManagedLint({root, paths: selection.javascriptPaths.map((file) => path.relative(root, path.resolve(root, file)).split(path.sep).join(\"/\")), output: \"json\"});\n    for (const owner of result.results ?? []) {\n      const parsed = normalizeManagedDiagnostics(owner.diagnostics, root, owner.scope, \"\");\n      if (parsed.ok) diagnostics.push(...parsed.diagnostics);\n      else failures.push({stage: \"lint-verify\", command: \"managed lint\", message: parsed.error});\n    }\n    if (result.code === 2) failures.push({stage: \"lint-verify\", command: \"managed lint\", message: result.diagnostics?.join(\"\\n\") || result.results?.map((owner) => `${owner.stdout}\\n${owner.stderr}`).join(\"\\n\") || \"Lint verification failed without diagnostics\"});\n  }\n  return {...emptyLintSummary(failures.length ? \"operational_failure\" : diagnostics.length ? \"findings\" : \"clean\", failures), diagnostics, lint_failed: [...new Set(diagnostics.map((diagnostic) => diagnostic.file))]};\n}\n\nfunction extractSingleFilePath(payload) {\n  return (\n    payload.filePath ??\n    payload.file_path ??\n    payload.tool_input?.filePath ??\n    payload.tool_input?.file_path ??\n    payload.tool_response?.filePath ??\n    payload.tool_response?.file_path ??\n    \"\"\n  );\n}\n\nfunction emitProviderFeedback(provider, summary) {\n  const feedback = renderProviderFeedback(provider, summary);\n  if (feedback !== null) {\n    process.stdout.write(JSON.stringify(feedback));\n  }\n}\n\nasync function runSingleFileMode(style) {\n  const payload = readStdinJson();\n  const root = repoRoot(process.cwd());\n\n  if (!root) {\n    return;\n  }\n\n  const filePath = extractSingleFilePath(payload);\n  if (!filePath) {\n    return;\n  }\n\n  const summary = await formatAndLintFiles(root, [filePath]);\n  emitProviderFeedback(style, summary);\n}\n\nfunction dirtyFiles(root) {\n  const output = runGit([\"ls-files\", \"-m\", \"-o\", \"--exclude-standard\"], root);\n  if (!output) {\n    return [];\n  }\n\n  return [\n    ...new Set(\n      output\n        .split(\"\\n\")\n        .map((line) => line.trim())\n        .filter(Boolean)\n        .filter((filePath) => !filePath.split(\"/\").some((part) => ignoredParts.has(part))),\n    ),\n  ].sort();\n}\n\nfunction fileHash(filePath) {\n  return contentHash(readFileSync(filePath));\n}\n\nfunction fingerprintPath(root, relativePath) {\n  const normalizedPath = normalizeManagedPath(relativePath);\n  if (!normalizedPath) {\n    return null;\n  }\n\n  const absolutePath = path.join(root, normalizedPath);\n  let rootRealPath;\n  let fileRealPath;\n  try {\n    const stats = lstatSync(absolutePath);\n    if (!stats.isFile()) {\n      return null;\n    }\n    rootRealPath = realpathSync.native(root);\n    fileRealPath = realpathSync.native(absolutePath);\n  } catch {\n    return null;\n  }\n\n  const relativeRealPath = path.relative(rootRealPath, fileRealPath);\n  if (\n    relativeRealPath === \"\" ||\n    relativeRealPath.startsWith(\"..\") ||\n    path.isAbsolute(relativeRealPath)\n  ) {\n    return null;\n  }\n\n  return absolutePath;\n}\n\nfunction fingerprints(root) {\n  const entries = {};\n\n  for (const relativePath of dirtyFiles(root)) {\n    const absolutePath = fingerprintPath(root, relativePath);\n    if (absolutePath !== null) {\n      entries[relativePath] = fileHash(absolutePath);\n    }\n  }\n\n  return entries;\n}\n\nfunction loadJson(filePath) {\n  if (!existsSync(filePath)) {\n    return null;\n  }\n\n  try {\n    return JSON.parse(readFileSync(filePath, \"utf8\"));\n  } catch {\n    return null;\n  }\n}\n\nfunction isFingerprintRecord(value) {\n  return value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction readFingerprintRecord(value) {\n  if (!isFingerprintRecord(value)) {\n    return {};\n  }\n\n  return Object.fromEntries(\n    Object.entries(value).filter(\n      ([filePath, hash]) => typeof filePath === \"string\" && typeof hash === \"string\",\n    ),\n  );\n}\n\nfunction loadCodexState(filePath) {\n  const raw = loadJson(filePath);\n  return {\n    baseline: readFingerprintRecord(raw?.baseline),\n    diagnosticAttempts: isFingerprintRecord(raw?.diagnosticAttempts)\n      ? raw.diagnosticAttempts\n      : {},\n    lastToolUseId: typeof raw?.lastToolUseId === \"string\" ? raw.lastToolUseId : \"\",\n    processed: readFingerprintRecord(raw?.processed),\n  };\n}\n\nfunction saveCodexState(filePath, state) {\n  writeFileSync(\n    filePath,\n    JSON.stringify({\n      baseline: state.baseline,\n      diagnosticAttempts: state.diagnosticAttempts,\n      lastToolUseId: state.lastToolUseId,\n      processed: state.processed,\n    }),\n  );\n}\n\nfunction applyDiagnosticRetryLimit(state, summary) {\n  const byFile = new Map();\n  for (const diagnostic of summary.diagnostics) {\n    const existing = byFile.get(diagnostic.file) ?? [];\n    existing.push(diagnostic);\n    byFile.set(diagnostic.file, existing);\n  }\n\n  let exhausted = false;\n  let maximumAttempt = 0;\n  for (const [relativePath, diagnostics] of byFile) {\n    const fingerprint = contentHash(JSON.stringify(diagnostics));\n    const previous = state.diagnosticAttempts[relativePath];\n    const attempts =\n      previous?.fingerprint === fingerprint && Number.isInteger(previous.attempts)\n        ? Math.min(previous.attempts + 1, 3)\n        : 1;\n    state.diagnosticAttempts[relativePath] = { fingerprint, attempts };\n    maximumAttempt = Math.max(maximumAttempt, attempts);\n    if (attempts >= 3) {\n      exhausted = true;\n    }\n  }\n\n  for (const relativePath of Object.keys(state.diagnosticAttempts)) {\n    if (!byFile.has(relativePath)) {\n      delete state.diagnosticAttempts[relativePath];\n    }\n  }\n\n  if (exhausted) {\n    summary.exhausted = true;\n    summary.result = \"exhausted\";\n  }\n  summary.status = \"findings\";\n  summary.fingerprint = contentHash(JSON.stringify(summary.diagnostics));\n  summary.attempt = maximumAttempt;\n}\n\nfunction updateProcessedFingerprints(root, state, filePaths) {\n  for (const relativePath of filePaths) {\n    const absolutePath = path.join(root, relativePath);\n\n    if (existsSync(absolutePath)) {\n      state.processed[relativePath] = fileHash(absolutePath);\n      continue;\n    }\n\n    delete state.processed[relativePath];\n  }\n}\n\nfunction pendingCodexFiles(state, current) {\n  return Object.entries(current)\n    .filter(\n      ([relativePath, digest]) =>\n        state.baseline[relativePath] !== digest && state.processed[relativePath] !== digest,\n    )\n    .map(([relativePath]) => relativePath);\n}\n\nfunction pruneProcessedFingerprints(state, current) {\n  for (const relativePath of Object.keys(state.processed)) {\n    if (current[relativePath] !== state.processed[relativePath]) {\n      delete state.processed[relativePath];\n    }\n  }\n}\n\nasync function runCodexSnapshotMode(mode) {\n  const payload = readStdinJson();\n  const cwd = String(payload.cwd ?? process.cwd());\n  const sessionId = String(payload.session_id ?? \"\");\n  const root = repoRoot(cwd);\n\n  if (!root || !sessionId) {\n    return;\n  }\n\n  const stateFile = codexStateFilePath(root, sessionId);\n\n  if (mode === \"session-start\") {\n    saveCodexState(stateFile, {\n      baseline: fingerprints(root),\n      diagnosticAttempts: {},\n      lastToolUseId: \"\",\n      processed: {},\n    });\n    return;\n  }\n\n  if (mode !== \"post\") {\n    return;\n  }\n\n  const state = loadCodexState(stateFile);\n  const toolUseId = typeof payload.tool_use_id === \"string\" ? payload.tool_use_id : \"\";\n\n  if (toolUseId && state.lastToolUseId === toolUseId) {\n    return;\n  }\n\n  const current = fingerprints(root);\n  pruneProcessedFingerprints(state, current);\n  const hasPatchCommand =\n    payload.tool_name === \"apply_patch\" && typeof payload.tool_input?.command === \"string\";\n  const patchedPaths = hasPatchCommand ? extractPatchedPaths(payload.tool_input.command, root) : [];\n  const pending = pendingCodexFiles(state, current);\n  const caseInsensitivePaths = pathCaseSemantics(root) === \"case-insensitive\";\n  const pendingPaths = new Map(\n    pending.map((relativePath) => [\n      managedPathKey(relativePath, caseInsensitivePaths),\n      relativePath,\n    ]),\n  );\n  const touched = hasPatchCommand\n    ? [\n        ...new Set(\n          patchedPaths\n            .map((relativePath) =>\n              pendingPaths.get(managedPathKey(relativePath, caseInsensitivePaths)),\n            )\n            .filter(Boolean),\n        ),\n      ]\n    : pending;\n\n  if (toolUseId) {\n    state.lastToolUseId = toolUseId;\n  }\n\n  if (touched.length === 0) {\n    saveCodexState(stateFile, state);\n    return;\n  }\n\n  const summary = await formatAndLintFiles(root, touched, current);\n  if (summary.diagnostics.length > 0) {\n    applyDiagnosticRetryLimit(state, summary);\n  } else {\n    for (const relativePath of touched) {\n      delete state.diagnosticAttempts[relativePath];\n    }\n  }\n  updateProcessedFingerprints(root, state, summary.formatted);\n  saveCodexState(stateFile, state);\n\n  if (\n    summary.diagnostics.length > 0 ||\n    summary.failures.length > 0 ||\n    summary.format_failed.length > 0\n  ) {\n    emitProviderFeedback(\"codex\", summary);\n  }\n}\n\nfunction toPosixPath(filePath) {\n  return filePath.split(path.sep).join(\"/\");\n}\n\nfunction normalizeEditedPath(filePath, worktree) {\n  if (!filePath) {\n    return null;\n  }\n\n  const absolutePath = path.isAbsolute(filePath) ? filePath : path.join(worktree, filePath);\n  const relativePath = path.relative(worktree, absolutePath);\n\n  if (!relativePath || relativePath.startsWith(\"..\") || path.isAbsolute(relativePath)) {\n    return null;\n  }\n\n  return toPosixPath(relativePath);\n}\n\nfunction extractPatchedPaths(patchText, worktree) {\n  if (!patchText) {\n    return [];\n  }\n\n  const paths = [];\n\n  for (const line of patchText.split(\"\\n\")) {\n    let relativePath = null;\n\n    if (line.startsWith(\"*** Add File: \")) {\n      relativePath = line.slice(\"*** Add File: \".length).trim();\n    } else if (line.startsWith(\"*** Update File: \")) {\n      relativePath = line.slice(\"*** Update File: \".length).trim();\n    } else if (line.startsWith(\"*** Move to: \")) {\n      relativePath = line.slice(\"*** Move to: \".length).trim();\n    }\n\n    const normalizedPath = normalizeEditedPath(relativePath, worktree);\n    if (normalizedPath) {\n      paths.push(normalizedPath);\n    }\n  }\n\n  return paths;\n}\n\nfunction editedPathsForTool(input, worktree) {\n  const toolName = input?.tool;\n  const args = input?.args ?? {};\n\n  if (toolName === \"apply_patch\") {\n    return extractPatchedPaths(args.patchText, worktree);\n  }\n\n  const filePath = args.filePath;\n  const normalizedPath = normalizeEditedPath(filePath, worktree);\n  return normalizedPath ? [normalizedPath] : [];\n}\n\nfunction parseSummary(stdout) {\n  try {\n    return JSON.parse(stdout || \"{}\");\n  } catch {\n    return {};\n  }\n}\n\nexport const FormatAndLintPlugin = async ({ client, worktree }) => {\n  return {\n    \"tool.execute.after\": async (input) => {\n      if (![\"edit\", \"write\", \"multiedit\", \"apply_patch\"].includes(input.tool)) {\n        return;\n      }\n\n      const editedPaths = [...new Set(editedPathsForTool(input, worktree))].filter(Boolean);\n\n      if (editedPaths.length === 0) {\n        return;\n      }\n\n      const result = runCommand(\n        worktree,\n        [\"node\", \".agents/hooks/format-edited-file.mjs\", \"files\", ...editedPaths],\n        [\"ignore\", \"pipe\", \"ignore\"],\n      );\n\n      const parsedSummary = result.ok ? parseSummary(result.stdout) : {};\n      const summary = {\n        ...parsedSummary,\n        status: typeof parsedSummary.status === \"string\" ? parsedSummary.status : \"operational-failure\",\n        diagnostics: Array.isArray(parsedSummary.diagnostics) ? parsedSummary.diagnostics : [],\n        failures: Array.isArray(parsedSummary.failures) ? parsedSummary.failures : [],\n        format_failed: Array.isArray(parsedSummary.format_failed) ? parsedSummary.format_failed : [],\n        exhausted: parsedSummary.exhausted === true,\n      };\n      if (\n        summary.diagnostics.length > 0 ||\n        summary.failures.length > 0 ||\n        summary.format_failed.length > 0\n      ) {\n        await client.app.log({\n          body: {\n            service: \"format-and-lint\",\n            level: \"warn\",\n            message: providerFeedbackMessage(summary),\n            extra: {\n              diagnostics: summary.diagnostics,\n              failures: summary.failures,\n              exhausted: summary.exhausted === true,\n              repairRequested: summary.exhausted !== true,\n            },\n          },\n        });\n      }\n    },\n  };\n};\n\nasync function main() {\n  const mode = process.argv[2] ?? \"\";\n\n  if (mode === \"session-start\" || mode === \"post\") {\n    await runCodexSnapshotMode(mode);\n    return;\n  }\n\n  if (mode === \"claude\" || mode === \"cursor\" || mode === \"opencode\") {\n    await runSingleFileMode(mode);\n    return;\n  }\n\n  if (mode === \"files\") {\n    const root = repoRoot(process.cwd());\n    const summary = root\n      ? await formatAndLintFiles(root, process.argv.slice(3))\n      : emptyLintSummary(\"operational_failure\", [\n          { stage: \"config-load\", command: \"git rev-parse --show-toplevel\", message: \"Not inside a Git repository\" },\n        ]);\n    process.stdout.write(JSON.stringify(summary));\n    return;\n  }\n\n  if (mode === \"preview\") {\n    const root = repoRoot(process.cwd());\n    const summary = root\n      ? await verifyLintFiles(root, process.argv.slice(3))\n      : emptyLintSummary(\"operational_failure\", [\n          { stage: \"config-load\", command: \"git rev-parse --show-toplevel\", message: \"Not inside a Git repository\" },\n        ]);\n    process.stdout.write(JSON.stringify(summary));\n  }\n}\n\nconst invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : \"\";\nconst modulePath = fileURLToPath(import.meta.url);\n\nif (invokedPath && path.basename(invokedPath) === path.basename(modulePath)) {\n  await main();\n}\n",
      "type": "registry:file",
      "target": "~/.agents/hooks/format-edited-file.mjs"
    },
    {
      "path": "hooks/format-edited-file-core.mjs",
      "content": "// Helpers of the edited-file hook, kept out of format-edited-file.mjs because OpenCode\n// loads every export of that plugin module as a plugin function.\n\nimport { createHash } from \"node:crypto\";\nimport {\n  cpSync,\n  existsSync,\n  mkdirSync,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  symlinkSync,\n} from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport function contentHash(content) {\n  return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nfunction formatLintFinding(diagnostic) {\n  const location =\n    Number.isInteger(diagnostic.line) && Number.isInteger(diagnostic.column)\n      ? `${diagnostic.file}:${diagnostic.line}:${diagnostic.column}`\n      : diagnostic.file;\n  const severity = diagnostic.severity ? ` (${diagnostic.severity})` : \"\";\n  const rule = diagnostic.rule ? ` [${diagnostic.rule}]` : \"\";\n  const help = diagnostic.help ? ` Help: ${diagnostic.help}` : \"\";\n  const documentation = diagnostic.documentation ? ` Docs: ${diagnostic.documentation}` : \"\";\n  return `${location}${severity}${rule} ${diagnostic.message}${help}${documentation}`;\n}\n\nexport function providerFeedbackMessage(summary) {\n  const findings = summary.diagnostics.map(formatLintFinding);\n  const failures = summary.failures.map(\n    (failure) => `${failure.file ? `${failure.file}: ` : \"\"}${failure.message}`,\n  );\n  const formatFailures = summary.format_failed.map((file) => `${file}: formatting failed`);\n  const lines = [...findings, ...formatFailures, ...failures];\n  if (summary.exhausted) {\n    return [\n      \"Lint repair exhausted after three unchanged attempts. Continue without another automatic repair request.\",\n      ...lines,\n    ].join(\"\\n\");\n  }\n  return [\"Lint feedback after edit. Fix these findings before continuing:\", ...lines].join(\"\\n\");\n}\n\nexport function renderProviderFeedback(provider, summary) {\n  const hasFeedback =\n    summary.diagnostics.length > 0 ||\n    summary.failures.length > 0 ||\n    summary.format_failed.length > 0;\n  if (!hasFeedback) {\n    return null;\n  }\n\n  const message = providerFeedbackMessage(summary);\n  switch (provider) {\n    case \"codex\":\n      return {\n        ...(summary.exhausted ? {} : { decision: \"block\" }),\n        hookSpecificOutput: {\n          hookEventName: \"PostToolUse\",\n          additionalContext: message,\n        },\n        systemMessage: message,\n      };\n    case \"claude\":\n      return {\n        hookSpecificOutput: {\n          hookEventName: \"PostToolUse\",\n          additionalContext: message,\n        },\n      };\n    case \"cursor\":\n      return { user_message: message };\n    case \"opencode\":\n      return {\n        event: \"lint-feedback\",\n        status: summary.exhausted ? \"exhausted\" : summary.status,\n        diagnostics: summary.diagnostics,\n        failures: summary.failures,\n        repairRequested: !summary.exhausted,\n      };\n    default:\n      throw new Error(`Unsupported lint feedback provider: ${provider}`);\n  }\n}\n\nexport function codexStateFilePath(root, sessionId) {\n  const repositoryIdentity = contentHash(realpathSync.native(root));\n  const safeSessionId = sessionId.replaceAll(\"/\", \"_\");\n  const stateDir = path.join(os.tmpdir(), \"codex-hooks\", repositoryIdentity, safeSessionId);\n  mkdirSync(stateDir, { recursive: true });\n  return path.join(stateDir, \"format-state.json\");\n}\n\nconst mirrorSkippedNames = new Set([\n  \".git\",\n  \".turbo\",\n  \".next\",\n  \"coverage\",\n  \"dist\",\n  \"build\",\n  \"__pycache__\",\n]);\nconst mirrorSkippedPaths =\n  /^(?:\\.devpunks\\/(?:delivery|cache|replaced-scaffold)|\\.devpunks-cache)(?:\\/|$)/u;\n\nfunction isOutside(relativeTarget) {\n  return (\n    relativeTarget === \"..\" ||\n    relativeTarget.startsWith(`..${path.sep}`) ||\n    path.isAbsolute(relativeTarget)\n  );\n}\n\n// Mirrors the repository for isolated lint parity. Required inputs must resolve inside the\n// physical root; unrelated external symlinks are skipped instead of failing the edit.\nexport function copyLintMirror(root, mirror, requiredInputs) {\n  const physicalRoot = realpathSync(root);\n  for (const input of requiredInputs) {\n    const source = path.join(root, input);\n    if (existsSync(source) && isOutside(path.relative(physicalRoot, realpathSync(source)))) {\n      throw new Error(`Cannot prove temporary lint parity for external repository input: ${input}`);\n    }\n  }\n  const visit = (source, destination) => {\n    mkdirSync(destination, { recursive: true });\n    for (const entry of readdirSync(source, { withFileTypes: true })) {\n      const relative = path.relative(root, path.join(source, entry.name)).split(path.sep).join(\"/\");\n      if (mirrorSkippedNames.has(entry.name) || mirrorSkippedPaths.test(relative)) {\n        continue;\n      }\n      const from = path.join(source, entry.name);\n      const to = path.join(destination, entry.name);\n      if (entry.name === \"node_modules\") {\n        symlinkSync(realpathSync(from), to, \"dir\");\n      } else if (entry.isSymbolicLink()) {\n        const relativeTarget = path.relative(physicalRoot, realpathSync(from));\n        if (!isOutside(relativeTarget)) {\n          const link = readlinkSync(from);\n          symlinkSync(path.isAbsolute(link) ? path.resolve(mirror, relativeTarget) : link, to);\n        }\n      } else if (entry.isDirectory()) {\n        visit(from, to);\n      } else if (entry.isFile()) {\n        cpSync(from, to);\n      } else {\n        throw new Error(`Cannot mirror non-regular repository input: ${path.relative(root, from)}`);\n      }\n    }\n  };\n  visit(root, mirror);\n}\n",
      "type": "registry:file",
      "target": "~/.agents/hooks/format-edited-file-core.mjs"
    },
    {
      "path": "hooks/codex-config.toml",
      "content": "[agents]\nmax_depth = 1\n\n[features]\nhooks = true\n\n[hooks]\nSessionStart = [\n  { matcher = \"startup|resume\", hooks = [\n    { type = \"command\", command = \"node \\\"$(git rev-parse --show-toplevel)/.codex/hooks/scaffold-update-check.mjs\\\" codex\", statusMessage = \"Checking Harness scaffold\", timeout = 60 },\n    { type = \"command\", command = \"node \\\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\\" session-start\", statusMessage = \"Capturing edited-file baseline\", timeout = 30 },\n  ] },\n]\nPostToolUse = [\n  { matcher = \"Bash|apply_patch|.*apply.?patch.*|edit|write|multiedit\", hooks = [\n    { type = \"command\", command = \"node \\\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\\" post\", statusMessage = \"Auto-formatting edited files\", timeout = 30 },\n  ] },\n]\n",
      "type": "registry:file",
      "target": "~/.codex/config.toml"
    }
  ],
  "meta": {
    "hi": {
      "files": {
        "hooks/codex-config.toml": {
          "artifact": "authored"
        },
        "hooks/format-edited-file-core.mjs": {
          "artifact": "copied"
        },
        "hooks/format-edited-file.mjs": {
          "artifact": "copied"
        },
        "hooks/scaffold-update-check.mjs": {
          "artifact": "copied"
        }
      },
      "kind": "hook",
      "merges": [
        {
          "target": ".claude/settings.json",
          "format": "json",
          "value": {
            "hooks": {
              "PostToolUse": [
                {
                  "hooks": [
                    {
                      "command": "node \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-edited-file.mjs claude",
                      "timeout": 30,
                      "type": "command"
                    }
                  ],
                  "matcher": "Edit|Write|MultiEdit"
                }
              ],
              "SessionStart": [
                {
                  "hooks": [
                    {
                      "command": "node \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/scaffold-update-check.mjs claude",
                      "timeout": 60,
                      "type": "command"
                    }
                  ]
                }
              ]
            }
          }
        },
        {
          "target": ".cursor/hooks.json",
          "format": "json",
          "value": {
            "hooks": {
              "afterFileEdit": [
                {
                  "command": "node .cursor/hooks/format-edited-file.mjs cursor"
                }
              ],
              "sessionStart": [
                {
                  "command": "node .cursor/hooks/scaffold-update-check.mjs cursor",
                  "timeout": 60000
                }
              ]
            },
            "version": 1
          }
        }
      ],
      "symlinks": [
        {
          "path": ".claude/hooks/scaffold-update-check.mjs",
          "target": "../../.agents/hooks/scaffold-update-check.mjs"
        },
        {
          "path": ".claude/hooks/format-edited-file.mjs",
          "target": "../../.agents/hooks/format-edited-file.mjs"
        },
        {
          "path": ".codex/hooks/scaffold-update-check.mjs",
          "target": "../../.agents/hooks/scaffold-update-check.mjs"
        },
        {
          "path": ".codex/hooks/format-edited-file.mjs",
          "target": "../../.agents/hooks/format-edited-file.mjs"
        },
        {
          "path": ".cursor/hooks/scaffold-update-check.mjs",
          "target": "../../.agents/hooks/scaffold-update-check.mjs"
        },
        {
          "path": ".cursor/hooks/format-edited-file.mjs",
          "target": "../../.agents/hooks/format-edited-file.mjs"
        },
        {
          "path": ".opencode/plugins/scaffold-update-check.js",
          "target": "../../.agents/hooks/scaffold-update-check.mjs"
        },
        {
          "path": ".opencode/plugins/format-edited-file.js",
          "target": "../../.agents/hooks/format-edited-file.mjs"
        }
      ]
    }
  }
}
