{"version":3,"sources":["../src/project-resolve.ts","../src/project-identity.ts","../src/registry.ts","../src/profiles.ts"],"sourcesContent":["import path from 'node:path'\nimport {\n  bindingLine,\n  findProjectRootSync,\n  readBindingSync,\n  readProjectIdentitySync,\n  ProjectIdentityError,\n  type BindingKind,\n  type ResolvedIdentity,\n} from './project-identity.js'\nimport { discoverDaemonsSync, findProjectByPathSync, readRegistrySync, type DiscoveredDaemon } from './registry.js'\nimport { getActiveProfileSync, resolveProfileSync, type Profile } from './profiles.js'\n\n// Which project a command means, and where its daemon is (ADR-273,\n// docs/contracts/project-identity.md §3–§4). One resolution for the CLI and the\n// MCP server; neither re-implements a step (#1373). The logic is synchronous: it\n// reads a few small local files, and the MCP server resolves at module load. The\n// async exports are thin wrappers for the CLI.\n//\n//   1. --profile / NEAT_PROFILE, or the env pin NEAT_CORE_URL / NEAT_API_URL\n//   2. --project <projectId | name> / NEAT_PROJECT\n//   3. the nearest .neat/project.json at or above the cwd\n//   4. a registration from before ADR-273 covering the cwd (notice, no write)\n//   5. an error — no default project, no sole-daemon guess\n//\n// Then by the project's binding: local → this machine's daemon for the project;\n// hosted → the account's endpoint and bearer. The global active profile never\n// routes a local project.\n\nexport type TargetSource = 'profile' | 'env' | 'project' | 'cwd' | 'legacy'\n\nexport interface ResolvedProject {\n  name: string\n  projectId?: string\n  // The directory holding .neat/project.json (or the legacy registration's path).\n  root?: string\n  binding: BindingKind\n  org?: string\n  // True when the project has no .neat/project.json yet (level 4).\n  legacy: boolean\n  // The binding.json was absent and the project is read as local.\n  bindingAbsent?: boolean\n  source: 'project' | 'cwd' | 'legacy'\n}\n\nexport interface ProjectTarget {\n  endpoint: string\n  authToken?: string\n  source: TargetSource\n  // Absent for an explicit pin that named no project.\n  project?: ResolvedProject\n  // The line every answer carries (project-identity.md §6).\n  line: string\n  // Something to tell the user on stderr (a legacy project, an absent binding).\n  notices: string[]\n  // The project name the answering local daemon serves under, for a verb's\n  // `/projects/<name>` segment. Absent for a pin or a hosted daemon.\n  daemonProject?: string\n}\n\nexport class TargetResolutionError extends Error {\n  // §6 binding line for a project that resolved but is unreachable (its daemon\n  // is down, or it is hosted and this machine is not logged in). Absent when\n  // nothing resolved — the client then falls back to UNRESOLVED_LINE. So an\n  // agent still sees which project and binding the error is about, instead of\n  // `project=(none)` while the message names the project.\n  line?: string\n  constructor(message: string) {\n    super(message)\n    this.name = 'TargetResolutionError'\n  }\n}\n\n// An explicitly named profile the store doesn't have: reported, never swapped for\n// another endpoint (client-profiles.md §3 level 1).\nexport class UnknownProfileError extends TargetResolutionError {\n  constructor(name: string) {\n    super(`no profile named \"${name}\" in ~/.neat/profiles.json — run \\`neat login\\` first, or drop --profile / NEAT_PROFILE`)\n    this.name = 'UnknownProfileError'\n  }\n}\n\nexport interface ResolveOptions {\n  project?: string\n  profile?: string\n  cwd?: string\n  env?: NodeJS.ProcessEnv\n}\n\nfunction runningList(live: DiscoveredDaemon[]): string {\n  return live.map((d) => `  ${d.record.project} → http://localhost:${d.record.ports.rest}  (${d.record.projectPath})`).join('\\n')\n}\n\nfunction fromRoot(root: string, source: 'project' | 'cwd'): ResolvedProject {\n  const identity = readProjectIdentitySync(root)\n  if (!identity) throw new TargetResolutionError(`${root} has no .neat/project.json`)\n  const b = readBindingSync(root)\n  return {\n    name: identity.name,\n    projectId: identity.projectId,\n    root,\n    binding: b.binding,\n    ...(b.org ? { org: b.org } : {}),\n    legacy: false,\n    ...(b.absent ? { bindingAbsent: true } : {}),\n    source,\n  }\n}\n\n/**\n * Levels 2–5: which project the command means. Never consults a profile.\n */\nexport async function resolveProject(opts: ResolveOptions = {}): Promise<ResolvedProject> {\n  return resolveProjectSync(opts)\n}\n\nexport function resolveProjectSync(opts: ResolveOptions = {}): ResolvedProject {\n  const env = opts.env ?? process.env\n  const cwd = path.resolve(opts.cwd ?? process.cwd())\n  const wanted = opts.project ?? env.NEAT_PROJECT\n\n  // Level 2 — a named project, by id or by name.\n  if (wanted && wanted.length > 0) {\n    let rows: Array<{ name: string; path: string }> = []\n    try {\n      rows = readRegistrySync().projects\n    } catch {\n      rows = []\n    }\n    const matches: ResolvedProject[] = []\n    for (const row of rows) {\n      let identity: ReturnType<typeof readProjectIdentitySync>\n      try {\n        identity = readProjectIdentitySync(row.path)\n      } catch {\n        identity = undefined\n      }\n      if (identity && (identity.projectId === wanted || identity.name === wanted)) {\n        matches.push(fromRoot(row.path, 'project'))\n      } else if (!identity && row.name === wanted) {\n        matches.push({ name: row.name, root: row.path, binding: 'local', legacy: true, source: 'project' })\n      }\n    }\n    if (matches.length === 1) return matches[0]!\n    if (matches.length > 1) {\n      const list = matches.map((m) => `  ${m.projectId ?? '(no id yet)'}  ${m.root}`).join('\\n')\n      throw new TargetResolutionError(`\"${wanted}\" names ${matches.length} projects on this machine; pass the projectId instead:\\n${list}`)\n    }\n    throw new TargetResolutionError(`no project \"${wanted}\" is registered on this machine — run \\`neat init\\` in it, or check \\`neat list\\``)\n  }\n\n  // Level 3 — the nearest .neat/project.json.\n  const root = findProjectRootSync(cwd)\n  if (root) return fromRoot(root, 'cwd')\n\n  // Level 4 — a registration from before ADR-273.\n  let legacy: ReturnType<typeof findProjectByPathSync>\n  try {\n    legacy = findProjectByPathSync(cwd)\n  } catch {\n    legacy = undefined\n  }\n  if (legacy) return { name: legacy.name, root: legacy.path, binding: 'local', legacy: true, source: 'legacy' }\n\n  // Level 5 — nothing here.\n  const live = liveDaemons()\n  const running = live.length > 0 ? `\\nRunning NEAT daemons:\\n${runningList(live)}` : ''\n  throw new TargetResolutionError(`no NEAT project here — run \\`neat init\\`, or pass --project <name>.${running}`)\n}\n\nfunction liveDaemons(): DiscoveredDaemon[] {\n  try {\n    return discoverDaemonsSync().filter((d) => d.live)\n  } catch {\n    return []\n  }\n}\n\nfunction localDaemonFor(p: ResolvedProject): DiscoveredDaemon | undefined {\n  const live = liveDaemons()\n  return (\n    (p.projectId ? live.find((d) => d.record.projectId === p.projectId) : undefined) ??\n    live.find((d) => p.root !== undefined && path.resolve(d.record.projectPath) === path.resolve(p.root)) ??\n    (p.legacy ? live.find((d) => d.record.project === p.name) : undefined)\n  )\n}\n\nfunction hostedProfileFor(p: ResolvedProject): Profile | undefined {\n  try {\n    return (p.org ? resolveProfileSync(p.org) : undefined) ?? getActiveProfileSync()\n  } catch {\n    return undefined\n  }\n}\n\n/**\n * The whole resolution: the project and the endpoint to reach it, as one\n * decision, with the binding line to print.\n */\nexport async function resolveProjectTarget(opts: ResolveOptions = {}): Promise<ProjectTarget> {\n  return resolveProjectTargetSync(opts)\n}\n\nexport function resolveProjectTargetSync(opts: ResolveOptions = {}): ProjectTarget {\n  const env = opts.env ?? process.env\n\n  // Level 1 — an explicit profile or env pin is used as given.\n  const named = opts.profile ?? env.NEAT_PROFILE\n  if (named && named.length > 0) {\n    const profile = resolveProfileSync(named)\n    if (!profile) throw new UnknownProfileError(named)\n    const id: ResolvedIdentity = { name: profile.name, binding: 'pinned', daemon: profile.endpoint }\n    return { endpoint: profile.endpoint, ...(profile.authToken ? { authToken: profile.authToken } : {}), source: 'profile', line: bindingLine(id), notices: [] }\n  }\n  const pin = env.NEAT_API_URL ?? env.NEAT_CORE_URL\n  if (pin && pin.length > 0) {\n    const token = env.NEAT_AUTH_TOKEN\n    const id: ResolvedIdentity = { name: env.NEAT_PROJECT ?? 'pinned', binding: 'pinned', daemon: pin }\n    return { endpoint: pin, ...(token ? { authToken: token } : {}), source: 'env', line: bindingLine(id), notices: [] }\n  }\n\n  const project = resolveProjectSync(opts)\n  const notices: string[] = []\n  if (project.legacy) {\n    notices.push(`${project.name} has no .neat/project.json yet — run \\`neat init\\` in ${project.root ?? 'it'} to give it a project identity`)\n  } else if (project.bindingAbsent) {\n    notices.push(`no .neat/binding.json — treating ${project.name} as local`)\n  }\n\n  // A resolution that fails after the project is known still owes its notices\n  // (a legacy project whose daemon is down is told about `neat init` too) AND\n  // its §6 line: the project resolved, only the endpoint is unreachable, so the\n  // error carries `project=<name> · binding=<…> · daemon=<why it is absent>`\n  // rather than dropping to `project=(none)`.\n  const failure = (message: string, daemonLabel: string): TargetResolutionError => {\n    const error = new TargetResolutionError([message, ...notices].join('\\n'))\n    error.line = bindingLine({\n      name: project.name,\n      ...(project.projectId ? { projectId: project.projectId } : {}),\n      binding: project.binding,\n      ...(project.org ? { org: project.org } : {}),\n      daemon: daemonLabel,\n    })\n    return error\n  }\n\n  if (project.binding === 'hosted') {\n    const profile = hostedProfileFor(project)\n    if (!profile) {\n      throw failure(`${project.name} is hosted (in ${project.org}); log in with \\`neat login\\` to reach it, or \\`neat project set-local\\` to make it local here`, '(your hosted login)')\n    }\n    const id: ResolvedIdentity = { name: project.name, ...(project.projectId ? { projectId: project.projectId } : {}), binding: 'hosted', ...(project.org ? { org: project.org } : {}), daemon: profile.endpoint }\n    return {\n      endpoint: profile.endpoint,\n      ...(profile.authToken ? { authToken: profile.authToken } : {}),\n      source: project.source,\n      project,\n      line: bindingLine(id),\n      notices,\n    }\n  }\n\n  const daemon = localDaemonFor(project)\n  if (!daemon) {\n    throw failure(`${project.name}'s daemon isn't running — start it with \\`neat up\\` in ${project.root ?? 'the project'}`, '(not running)')\n  }\n  const endpoint = `http://localhost:${daemon.record.ports.rest}`\n  const id: ResolvedIdentity = { name: project.name, ...(project.projectId ? { projectId: project.projectId } : {}), binding: 'local', daemon: endpoint }\n  return { endpoint, source: project.source, project, line: bindingLine(id), notices, daemonProject: daemon.record.project }\n}\n\n/** NEAT_LEGACY_ROUTING=1 restores the pre-ADR-273 resolution (project-identity.md §7). */\nexport function legacyRoutingEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n  return env.NEAT_LEGACY_ROUTING === '1'\n}\n\nexport const LEGACY_ROUTING_NOTICE =\n  'NEAT_LEGACY_ROUTING=1: using the pre-ADR-273 resolution (the logged-in profile routes every bare command). This switch is temporary and will be removed.'\n\n/** The line a client prints when no project resolved (project-identity.md §6). */\nexport const UNRESOLVED_LINE = 'project=(none) · binding=(unresolved) · daemon=(none)'\n\n// ── honest routing (project-identity.md §5) ──────────────────────────────────\n\n/** A command that acts on this machine was run on a hosted-bound project. */\nexport class HostedBindingError extends TargetResolutionError {\n  constructor(name: string, org: string | undefined) {\n    super(\n      `${name} is hosted (runs in ${org ?? 'its org'}); it isn't yours to start here. ` +\n        'Use `neat open` to connect to it, or `neat project set-local` to make it local on this machine.',\n    )\n    this.name = 'HostedBindingError'\n  }\n}\n\n/**\n * For a command that acts on this machine (`up`, `watch`, the bare orchestrator):\n * throws HostedBindingError when the project at or above `dir` is bound to hosted,\n * so the command stops before it writes, starts or prints anything that reads as\n * ready (§5). A directory with no project, or an identity file that can't be read,\n * is left to the command's own handling.\n */\nexport function assertLocalBinding(dir: string): void {\n  let root: string | undefined\n  let name: string | undefined\n  let binding: ReturnType<typeof readBindingSync>\n  try {\n    root = findProjectRootSync(dir)\n    if (!root) return\n    name = readProjectIdentitySync(root)?.name\n    binding = readBindingSync(root)\n  } catch (err) {\n    // An identity file that can't be read is the command's own to report; any\n    // other failure is a bug and surfaces.\n    if (err instanceof ProjectIdentityError) return\n    throw err\n  }\n  if (binding.binding === 'hosted') throw new HostedBindingError(name ?? path.basename(root), binding.org)\n}\n","import { existsSync, promises as fs, readFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { randomBytes } from 'node:crypto'\n\n// A project's identity and this machine's binding to it (ADR-273,\n// docs/contracts/project-identity.md).\n//\n//   <repo>/.neat/project.json   committed: { schemaVersion, projectId, name }\n//   <repo>/.neat/binding.json   gitignored: { schemaVersion, binding, org? }\n//   <repo>/.neat/.gitignore     keeps binding.json and connectors.json out of commits\n//\n// projectId is `prj_` + a ULID, minted once and never changed by NEAT; name is for\n// people and may repeat. This module is the one place those files are read and\n// written; the CLI, the MCP server and the registry call into it.\n\nexport const NEAT_DIR = '.neat'\nexport const PROJECT_FILE = 'project.json'\nexport const BINDING_FILE = 'binding.json'\nexport const PROJECT_SCHEMA_VERSION = 1\nexport const BINDING_SCHEMA_VERSION = 1\n// What .neat/.gitignore keeps out of commits: this machine's binding and the\n// project's connector references.\nexport const NEAT_DIR_IGNORES = ['binding.json', 'connectors.json']\n\nexport interface ProjectIdentity {\n  schemaVersion: 1\n  projectId: string\n  name: string\n}\n\nexport type BindingKind = 'local' | 'hosted'\n\nexport interface ProjectBinding {\n  schemaVersion: 1\n  binding: BindingKind\n  org?: string\n  daemonHint?: { port: number }\n}\n\nexport class ProjectIdentityError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = 'ProjectIdentityError'\n  }\n}\n\n// ── ids ──────────────────────────────────────────────────────────────────────\n\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\nexport const PROJECT_ID_RE = /^prj_[0-9A-HJKMNP-TV-Z]{26}$/\n\n/**\n * `prj_` + a ULID: 48 bits of millisecond time then 80 random bits, in\n * Crockford base32 (26 characters). Time-ordered, collision-free in practice,\n * and readable. No dependency: the encoding is a few lines.\n */\nexport function mintProjectId(now: number = Date.now(), rand: Buffer = randomBytes(10)): string {\n  let time = ''\n  let t = now\n  for (let i = 0; i < 10; i++) {\n    time = CROCKFORD[t % 32] + time\n    t = Math.floor(t / 32)\n  }\n  let bits = 0n\n  for (const b of rand.subarray(0, 10)) bits = (bits << 8n) | BigInt(b)\n  let random = ''\n  for (let i = 0; i < 16; i++) {\n    random = CROCKFORD[Number(bits & 31n)] + random\n    bits >>= 5n\n  }\n  return `prj_${time}${random}`\n}\n\n// ── paths ────────────────────────────────────────────────────────────────────\n\nexport function neatDir(root: string): string {\n  return path.join(root, NEAT_DIR)\n}\nexport function projectFilePath(root: string): string {\n  return path.join(root, NEAT_DIR, PROJECT_FILE)\n}\nexport function bindingFilePath(root: string): string {\n  return path.join(root, NEAT_DIR, BINDING_FILE)\n}\n\n// ── reading ──────────────────────────────────────────────────────────────────\n\nasync function readJson(file: string): Promise<unknown | undefined> {\n  let raw: string\n  try {\n    raw = await fs.readFile(file, 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n    throw err\n  }\n  try {\n    return JSON.parse(raw)\n  } catch {\n    throw new ProjectIdentityError(`${file} is not valid JSON`)\n  }\n}\n\nfunction isObj(v: unknown): v is Record<string, unknown> {\n  return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\n// One validator per file, shared by the async and sync readers.\nfunction parseIdentity(v: unknown, file: string): ProjectIdentity {\n  if (!isObj(v)) throw new ProjectIdentityError(`${file} must be a JSON object`)\n  if (v['schemaVersion'] !== PROJECT_SCHEMA_VERSION) {\n    throw new ProjectIdentityError(\n      `${file} has schemaVersion ${JSON.stringify(v['schemaVersion'])}; this NEAT reads version ${PROJECT_SCHEMA_VERSION}`,\n    )\n  }\n  const projectId = v['projectId']\n  if (typeof projectId !== 'string' || !PROJECT_ID_RE.test(projectId)) {\n    throw new ProjectIdentityError(`${file} has no valid projectId (expected prj_ followed by a 26-character ULID)`)\n  }\n  const name = v['name']\n  if (typeof name !== 'string' || name.trim().length === 0) {\n    throw new ProjectIdentityError(`${file} has no name`)\n  }\n  return { schemaVersion: 1, projectId, name }\n}\n\nconst ABSENT_BINDING: ProjectBinding & { absent: boolean } = { schemaVersion: 1, binding: 'local', absent: true }\n\nfunction parseBinding(v: unknown, file: string): ProjectBinding & { absent: boolean } {\n  if (!isObj(v)) throw new ProjectIdentityError(`${file} must be a JSON object`)\n  if (v['schemaVersion'] !== BINDING_SCHEMA_VERSION) {\n    throw new ProjectIdentityError(\n      `${file} has schemaVersion ${JSON.stringify(v['schemaVersion'])}; this NEAT reads version ${BINDING_SCHEMA_VERSION}`,\n    )\n  }\n  const binding = v['binding']\n  if (binding !== 'local' && binding !== 'hosted') {\n    throw new ProjectIdentityError(`${file}: binding must be \"local\" or \"hosted\"`)\n  }\n  const org = typeof v['org'] === 'string' && v['org'].length > 0 ? v['org'] : undefined\n  if (binding === 'hosted' && !org) throw new ProjectIdentityError(`${file}: a hosted binding needs an org`)\n  const hint = v['daemonHint']\n  const port = isObj(hint) && typeof hint['port'] === 'number' ? hint['port'] : undefined\n  return {\n    schemaVersion: 1,\n    binding,\n    ...(org ? { org } : {}),\n    ...(port !== undefined ? { daemonHint: { port } } : {}),\n    absent: false,\n  }\n}\n\n/** The project's identity at `root`, or undefined when it has none. */\nexport async function readProjectIdentity(root: string): Promise<ProjectIdentity | undefined> {\n  const file = projectFilePath(root)\n  const v = await readJson(file)\n  return v === undefined ? undefined : parseIdentity(v, file)\n}\n\n/**\n * How this machine reaches the project at `root`. A missing binding.json is\n * `local`, and `absent` says so, so a caller can tell the user instead of\n * assuming silently.\n */\nexport async function readProjectBinding(root: string): Promise<ProjectBinding & { absent: boolean }> {\n  const file = bindingFilePath(root)\n  const v = await readJson(file)\n  return v === undefined ? { ...ABSENT_BINDING } : parseBinding(v, file)\n}\n\n// ── synchronous twins (the MCP server resolves at module load) ───────────────\n\nfunction readJsonSync(file: string): unknown | undefined {\n  let raw: string\n  try {\n    raw = readFileSync(file, 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n    throw err\n  }\n  try {\n    return JSON.parse(raw)\n  } catch {\n    throw new ProjectIdentityError(`${file} is not valid JSON`)\n  }\n}\n\nexport function readProjectIdentitySync(root: string): ProjectIdentity | undefined {\n  const file = projectFilePath(root)\n  const v = readJsonSync(file)\n  return v === undefined ? undefined : parseIdentity(v, file)\n}\n\nexport function readBindingSync(root: string): ProjectBinding & { absent: boolean } {\n  const file = bindingFilePath(root)\n  const v = readJsonSync(file)\n  return v === undefined ? { ...ABSENT_BINDING } : parseBinding(v, file)\n}\n\nexport function findProjectRootSync(start: string): string | undefined {\n  let dir = path.resolve(start)\n  for (;;) {\n    if (existsSync(projectFilePath(dir))) return dir\n    const parent = path.dirname(dir)\n    if (parent === dir) return undefined\n    dir = parent\n  }\n}\n\n/** `readProjectBinding` under the name the other Phase 0 work orders use. */\nexport const readBinding = readProjectBinding\n\n/**\n * The nearest directory at or above `start` that holds a `.neat/project.json`,\n * or undefined. Stops at the filesystem root.\n */\nexport async function findProjectRoot(start: string): Promise<string | undefined> {\n  let dir = path.resolve(start)\n  for (;;) {\n    try {\n      await fs.access(projectFilePath(dir))\n      return dir\n    } catch {\n      // keep walking\n    }\n    const parent = path.dirname(dir)\n    if (parent === dir) return undefined\n    dir = parent\n  }\n}\n\n// ── writing ──────────────────────────────────────────────────────────────────\n\nasync function writeAtomic(file: string, contents: string): Promise<void> {\n  await fs.mkdir(path.dirname(file), { recursive: true })\n  const tmp = `${file}.${process.pid}.${Date.now()}.tmp`\n  await fs.writeFile(tmp, contents, 'utf8')\n  await fs.rename(tmp, file)\n}\n\n// .neat/.gitignore lists binding.json and connectors.json; an existing file keeps\n// its own lines and gains only what is missing.\nasync function ensureNeatDirIgnores(root: string): Promise<boolean> {\n  const file = path.join(neatDir(root), '.gitignore')\n  let current = ''\n  try {\n    current = await fs.readFile(file, 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n  }\n  const have = new Set(current.split(/\\r?\\n/).map((l) => l.trim()))\n  const missing = NEAT_DIR_IGNORES.filter((l) => !have.has(l))\n  if (missing.length === 0) return false\n  const prefix = current.length === 0 ? '# Per-machine NEAT state (ADR-273): never committed.\\n' : current.endsWith('\\n') ? current : `${current}\\n`\n  await writeAtomic(file, `${prefix}${missing.join('\\n')}\\n`)\n  return true\n}\n\nexport interface EnsureIdentityResult {\n  identity: ProjectIdentity\n  binding: ProjectBinding\n  // What this call created, for the caller's report.\n  createdIdentity: boolean\n  createdBinding: boolean\n  renamed: boolean\n  writtenFiles: string[]\n}\n\n/**\n * Give the project at `root` its identity, or keep the one it has (ADR-273).\n * Mints a projectId only when no .neat/project.json exists; a re-run keeps the id.\n * `name` sets the display name on first mint; on a re-run it renames only when\n * `rename` is set (an explicit --project). Writes a local binding.json only when\n * none exists, and makes sure .neat/.gitignore keeps the per-machine files out of\n * commits. Idempotent.\n */\nexport async function ensureProjectIdentity(\n  root: string,\n  opts: { name: string; rename?: boolean; now?: number },\n): Promise<EnsureIdentityResult> {\n  const writtenFiles: string[] = []\n  const name = opts.name.trim()\n  if (name.length === 0) throw new ProjectIdentityError('a project needs a name')\n\n  let identity = await readProjectIdentity(root)\n  let createdIdentity = false\n  let renamed = false\n  if (!identity) {\n    identity = { schemaVersion: 1, projectId: mintProjectId(opts.now), name }\n    createdIdentity = true\n  } else if (opts.rename && identity.name !== name) {\n    identity = { ...identity, name }\n    renamed = true\n  }\n  if (createdIdentity || renamed) {\n    await writeAtomic(projectFilePath(root), `${JSON.stringify(identity, null, 2)}\\n`)\n    writtenFiles.push(projectFilePath(root))\n  }\n\n  const current = await readProjectBinding(root)\n  let createdBinding = false\n  if (current.absent) {\n    await writeAtomic(bindingFilePath(root), `${JSON.stringify({ schemaVersion: 1, binding: 'local' }, null, 2)}\\n`)\n    writtenFiles.push(bindingFilePath(root))\n    createdBinding = true\n  }\n  const { absent: _absent, ...binding } = current.absent ? { ...current, absent: false } : current\n\n  if (await ensureNeatDirIgnores(root)) writtenFiles.push(path.join(neatDir(root), '.gitignore'))\n\n  return { identity, binding, createdIdentity, createdBinding, renamed, writtenFiles }\n}\n\n/**\n * Write .neat/project.json with an identity that already exists elsewhere — a\n * hosted project being cloned to this machine (Phase 1). The id is validated and\n * kept as given, never re-minted; `ensureProjectIdentity` is the minting path.\n * A directory that already holds this id is left as it is; one holding a\n * different id is refused, so a caller never has to read-compare-write.\n */\nexport async function writeProjectIdentity(root: string, id: { projectId: string; name: string }): Promise<ProjectIdentity> {\n  if (!PROJECT_ID_RE.test(id.projectId)) {\n    throw new ProjectIdentityError(`${id.projectId} is not a project id (expected prj_ followed by a 26-character ULID)`)\n  }\n  const name = id.name.trim()\n  if (name.length === 0) throw new ProjectIdentityError('a project needs a name')\n  const existing = await readProjectIdentity(root)\n  if (existing) {\n    if (existing.projectId === id.projectId) return existing\n    throw new ProjectIdentityError(`${root} is already project ${existing.name} (${existing.projectId}); refusing to replace it with ${id.projectId}`)\n  }\n  const identity: ProjectIdentity = { schemaVersion: 1, projectId: id.projectId, name }\n  await writeAtomic(projectFilePath(root), `${JSON.stringify(identity, null, 2)}\\n`)\n  await ensureNeatDirIgnores(root)\n  return identity\n}\n\n/**\n * Set how this machine reaches the project at `root` (project-identity.md §2):\n * `local`, or `hosted` in `org`. The one writer of binding.json besides `init`.\n */\nexport async function writeProjectBinding(root: string, b: { binding: BindingKind; org?: string }): Promise<ProjectBinding> {\n  if (b.binding === 'hosted' && (!b.org || b.org.trim().length === 0)) {\n    throw new ProjectIdentityError('a hosted binding needs an org')\n  }\n  const value: ProjectBinding = { schemaVersion: 1, binding: b.binding, ...(b.binding === 'hosted' ? { org: b.org!.trim() } : {}) }\n  await writeAtomic(bindingFilePath(root), `${JSON.stringify(value, null, 2)}\\n`)\n  await ensureNeatDirIgnores(root)\n  return value\n}\n\n/** One line for a run's report: what `ensureProjectIdentity` did. */\nexport function identityReportLine(r: EnsureIdentityResult): string {\n  const id = `${r.identity.name} (${r.identity.projectId})`\n  if (r.createdIdentity) return `project identity: minted ${id} in ${NEAT_DIR}/${PROJECT_FILE}, binding ${r.binding.binding}`\n  if (r.renamed) return `project identity: renamed to ${id}`\n  return `project identity: ${id}, binding ${r.binding.binding}`\n}\n\n// ── the binding line (project-identity.md §6) ────────────────────────────────\n\n/**\n * What a client is talking to: the resolved project, how it was reached, and the\n * daemon that answered. `projectId` is absent only for a legacy project that has\n * no .neat/project.json yet (§3 level 4).\n */\nexport interface ResolvedIdentity {\n  name: string\n  projectId?: string\n  binding: BindingKind | 'pinned'\n  org?: string\n  // The endpoint URL, or `pid:<pid>:<port>` for a local daemon reported by process.\n  daemon: string\n}\n\n/**\n * The one line every daemon response, MCP result and error, `neat://status` and\n * CLI read verb carries:\n * `project=<name> (<projectId>) · binding=<local | hosted@<org> | pinned> · daemon=<daemon>`.\n * One renderer, so every surface prints it the same way (#1373).\n */\nexport function bindingLine(id: ResolvedIdentity): string {\n  const binding = id.binding === 'hosted' ? `hosted@${id.org ?? '?'}` : id.binding\n  return `project=${id.name} (${id.projectId ?? 'no id yet'}) · binding=${binding} · daemon=${id.daemon}`\n}\n","/**\n * Machine-level project registry + machine-wide daemon discovery.\n *\n * This module owns two surfaces under `~/.neat/`:\n *\n *  1. The legacy project registry at `~/.neat/projects.json` (ADR-048). One\n *     file, per-user, machine-local, not synced. Under the project-daemon\n *     contract (ADR-096) it is no longer the coordination point — it is read\n *     once for migration and otherwise left to the additive writes the daemon\n *     and orchestrator still perform. The read-modify-write helpers below keep\n *     their atomic-write + exclusive-lock machinery for that legacy surface.\n *\n *  2. The machine-wide daemon discovery directory at `~/.neat/daemons/`\n *     (ADR-096 §6). One file per running daemon — `<project>.json` — each owned\n *     solely by the daemon that wrote it (on start) and removes it (on graceful\n *     stop). Discovery is **append-only and lock-free**: a reader scans the\n *     directory and reconciles liveness; it never acquires a shared lock, so it\n *     can never deadlock against a daemon (#506). Losing or rebuilding the\n *     directory costs discovery convenience, not correctness — each project's\n *     own `neat-out/daemon.json` stays authoritative.\n *\n * `neat ps` / `neat list` and the per-daemon `pause` / `resume` / `uninstall`\n * verbs read discovery, falling back to the legacy registry where no daemon\n * file is present yet (the migration window before every daemon self-describes).\n *\n * The legacy lock is a file we exclusively-create (`O_EXCL`), hold while we\n * mutate, and unlink on the way out. Crude but cross-platform; matches what\n * `proper-lockfile` does internally without pulling the dep in. It never sits\n * on the discovery path.\n */\n\nimport { promises as fs, readFileSync, readdirSync, realpathSync } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport {\n  RegistryFileSchema,\n  type RegistryEntry,\n  type RegistryFile,\n  type RegistryStatus,\n} from '@neat.is/types'\n\nconst LOCK_TIMEOUT_MS = 5_000\nconst LOCK_RETRY_MS = 50\n\n// Resolve `~/.neat/` per call so tests can override `HOME` / `NEAT_HOME`\n// before each run without module-load order mattering.\nfunction neatHome(): string {\n  const override = process.env.NEAT_HOME\n  if (override && override.length > 0) return path.resolve(override)\n  return path.join(os.homedir(), '.neat')\n}\n\nexport function registryPath(): string {\n  return path.join(neatHome(), 'projects.json')\n}\n\nexport function registryLockPath(): string {\n  return path.join(neatHome(), 'projects.json.lock')\n}\n\n// The daemon writes its PID here on startup (daemon.ts). It's the authoritative\n// \"is a neat daemon running\" signal — more reliable than matching the lock's\n// own PID, since the daemon holds the registry lock only for brief read-modify-\n// write windows and an init that contends usually catches an orphaned lock\n// rather than the daemon mid-write.\nfunction daemonPidPath(): string {\n  return path.join(neatHome(), 'neatd.pid')\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// #366 / ADR-096 §6 — machine-wide daemon discovery, lock-free.\n//\n// Each running daemon drops a `<project>.json` file into `~/.neat/daemons/`\n// on start and removes it on graceful stop. The file is a copy of that\n// project's authoritative `neat-out/daemon.json` record. A daemon owns only\n// its own file — there is no shared file and no shared lock. Discovery reads\n// the directory and reconciles liveness; it never acquires a lock, so it can\n// never deadlock against a daemon mid-write the way the registry lock did\n// (#506). The shape mirrors what the daemon writes (keystone #508); we read it\n// as plain JSON rather than importing the daemon's writer so the two stay\n// decoupled, and validate defensively so a malformed file is skipped, not\n// fatal.\n// ─────────────────────────────────────────────────────────────────────────\n\nexport interface DaemonPorts {\n  rest: number\n  otlp: number\n  web: number\n}\n\nexport interface DaemonRecord {\n  project: string\n  // The project's id from .neat/project.json (ADR-273); absent for a project that\n  // has none yet. The discovery copy is filed under it when present.\n  projectId?: string\n  // Project root whose `neat-out/` holds the authoritative record.\n  projectPath: string\n  pid: number\n  status: 'running' | 'stopped'\n  ports: DaemonPorts\n  // ISO8601.\n  startedAt: string\n  neatVersion: string\n}\n\n// A discovered daemon plus the liveness verdict the reader reconciled. `live`\n// is true only when the record claims `running` AND its pid is actually alive\n// — a daemon that crashed without clearing its file reads as `running` but\n// `live: false`, so `neat ps` never reports a ghost as up.\nexport interface DiscoveredDaemon {\n  record: DaemonRecord\n  live: boolean\n  // Where the discovery copy was read from. Useful for diagnostics and for the\n  // per-daemon verbs that clean a stale file.\n  source: string\n}\n\nexport function daemonsDir(): string {\n  return path.join(neatHome(), 'daemons')\n}\n\nfunction isFiniteInt(v: unknown): v is number {\n  return typeof v === 'number' && Number.isFinite(v)\n}\n\n// Parse one discovery file's contents into a DaemonRecord, or undefined when\n// the shape doesn't hold. Defensive on purpose: discovery is convenience, so a\n// half-written or hand-edited file is skipped rather than crashing `neat ps`.\nfunction parseDaemonRecord(raw: string): DaemonRecord | undefined {\n  let obj: unknown\n  try {\n    obj = JSON.parse(raw)\n  } catch {\n    return undefined\n  }\n  if (typeof obj !== 'object' || obj === null) return undefined\n  const r = obj as Record<string, unknown>\n  const ports = r.ports as Record<string, unknown> | undefined\n  if (\n    typeof r.project !== 'string' ||\n    typeof r.projectPath !== 'string' ||\n    !isFiniteInt(r.pid) ||\n    (r.status !== 'running' && r.status !== 'stopped') ||\n    typeof r.startedAt !== 'string' ||\n    typeof r.neatVersion !== 'string' ||\n    !ports ||\n    !isFiniteInt(ports.rest) ||\n    !isFiniteInt(ports.otlp) ||\n    !isFiniteInt(ports.web)\n  ) {\n    return undefined\n  }\n  return {\n    project: r.project,\n    ...(typeof r.projectId === 'string' && r.projectId.length > 0 ? { projectId: r.projectId } : {}),\n    projectPath: r.projectPath,\n    pid: r.pid,\n    status: r.status,\n    ports: { rest: ports.rest, otlp: ports.otlp, web: ports.web },\n    startedAt: r.startedAt,\n    neatVersion: r.neatVersion,\n  }\n}\n\n// Liveness for a discovered daemon. Exported (via the default probe) so the\n// verbs and tests reconcile the same way: `running` claim AND pid alive.\nexport function isPidAlive(pid: number): boolean {\n  return isPidAliveDefault(pid)\n}\n\nexport interface DiscoveryProbe {\n  isPidAlive(pid: number): boolean\n}\n\nconst defaultDiscoveryProbe: DiscoveryProbe = { isPidAlive: isPidAliveDefault }\n\n/**\n * Scan `~/.neat/daemons/` and return every well-formed discovery record with\n * its reconciled liveness. Lock-free: a plain directory read, no rendezvous.\n *\n * A missing directory (no daemon has ever started under this model) yields an\n * empty list — first run, nothing to discover. Malformed or unreadable files\n * are skipped silently; discovery degrades to \"fewer entries,\" never an error.\n */\nexport async function discoverDaemons(\n  probe: DiscoveryProbe = defaultDiscoveryProbe,\n): Promise<DiscoveredDaemon[]> {\n  const dir = daemonsDir()\n  let names: string[]\n  try {\n    names = await fs.readdir(dir)\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n    throw err\n  }\n  const out: DiscoveredDaemon[] = []\n  for (const name of names) {\n    if (!name.endsWith('.json')) continue\n    const file = path.join(dir, name)\n    let raw: string\n    try {\n      raw = await fs.readFile(file, 'utf8')\n    } catch {\n      continue\n    }\n    const record = parseDaemonRecord(raw)\n    if (!record) continue\n    const live = record.status === 'running' && probe.isPidAlive(record.pid)\n    out.push({ record, live, source: file })\n  }\n  out.sort((a, b) => a.record.project.localeCompare(b.record.project))\n  return out\n}\n\n/**\n * `discoverDaemons`, synchronously, for a caller that resolves its target before\n * it can await anything: the MCP server picks its daemon at module load\n * (ADR-259). Same directory, parser, liveness rule and never-throws degrading.\n */\nexport function discoverDaemonsSync(probe: DiscoveryProbe = defaultDiscoveryProbe): DiscoveredDaemon[] {\n  const dir = daemonsDir()\n  let names: string[]\n  try {\n    names = readdirSync(dir)\n  } catch {\n    return []\n  }\n  const out: DiscoveredDaemon[] = []\n  for (const name of names) {\n    if (!name.endsWith('.json')) continue\n    const file = path.join(dir, name)\n    let raw: string\n    try {\n      raw = readFileSync(file, 'utf8')\n    } catch {\n      continue\n    }\n    const record = parseDaemonRecord(raw)\n    if (!record) continue\n    const live = record.status === 'running' && probe.isPidAlive(record.pid)\n    out.push({ record, live, source: file })\n  }\n  out.sort((a, b) => a.record.project.localeCompare(b.record.project))\n  return out\n}\n\n/**\n * Remove a daemon's discovery file. A daemon owns its own file, so this is for\n * the per-daemon verbs reconciling a record whose daemon is gone (a crashed\n * daemon that never cleared its own file) — never a rendezvous another process\n * coordinates through. Best-effort: an already-absent file is success.\n */\nexport async function removeDaemonRecord(source: string): Promise<void> {\n  await fs.unlink(source).catch(() => {})\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// #366 / ADR-096 §8 — migration off the global registry.\n//\n// Installs carrying `~/.neat/projects.json` map their registered projects onto\n// per-project daemons on first run under this model. The discovery directory is\n// authoritative for \"what's running\"; the registry is read once to surface\n// projects that were registered before any daemon self-described, so the\n// machine-wide verbs still see them during the migration window. The registry\n// is no longer the coordination surface — nothing here writes it back.\n// ─────────────────────────────────────────────────────────────────────────\n\n// A unified view for the machine-wide verbs: a discovered daemon when one is\n// present, otherwise a legacy registry entry projected into the same shape so\n// `neat ps` / `neat list` render one table regardless of which surface the\n// project lives on yet.\nexport interface MachineProject {\n  project: string\n  projectPath: string\n  // 'running' / 'stopped' come from a live discovery record; 'registered'\n  // marks a legacy registry entry with no daemon file yet (migration window).\n  state: 'running' | 'stopped' | 'registered'\n  // Present only when a discovery record backs this row.\n  ports?: DaemonPorts\n  // Legacy registry status when the row came from the registry; undefined for\n  // a discovery-backed row.\n  registryStatus?: RegistryStatus\n  pid?: number\n}\n\n/**\n * The machine-wide project view the CLI verbs render. Discovery wins: every\n * `~/.neat/daemons/` record becomes a row (running or stopped per liveness).\n * Legacy registry entries whose path isn't already covered by a discovery\n * record are folded in as `registered` rows so a pre-#508 install still lists\n * its projects. Keyed on resolved path so a registry entry and its daemon\n * record collapse to one row.\n *\n * Read-only on both surfaces. The registry is read once for migration; nothing\n * here writes it back, in keeping with ADR-096 §8.\n */\nexport async function listMachineProjects(\n  probe: DiscoveryProbe = defaultDiscoveryProbe,\n): Promise<MachineProject[]> {\n  const discovered = await discoverDaemons(probe)\n  const byPath = new Map<string, MachineProject>()\n  for (const d of discovered) {\n    const key = await normalizeProjectPath(d.record.projectPath)\n    byPath.set(key, {\n      project: d.record.project,\n      projectPath: d.record.projectPath,\n      state: d.live ? 'running' : 'stopped',\n      ports: d.record.ports,\n      pid: d.record.pid,\n    })\n  }\n\n  // Migration read: legacy registry entries not already covered by a daemon\n  // record. Read once, never written back.\n  let legacy: RegistryEntry[] = []\n  try {\n    legacy = (await readRegistry()).projects\n  } catch {\n    // A corrupt legacy file shouldn't sink discovery — the daemons we found are\n    // still valid. Skip the legacy fold.\n    legacy = []\n  }\n  for (const entry of legacy) {\n    const key = await normalizeProjectPath(entry.path)\n    if (byPath.has(key)) continue\n    byPath.set(key, {\n      project: entry.name,\n      projectPath: entry.path,\n      state: 'registered',\n      registryStatus: entry.status,\n    })\n  }\n\n  return [...byPath.values()].sort((a, b) => a.project.localeCompare(b.project))\n}\n\n// Find a discovery record by project name, with its reconciled liveness. The\n// per-daemon verbs key on the project name the operator types; discovery is the\n// source of truth for whether a daemon is running and which pid to signal.\nexport async function findDaemonByProject(\n  name: string,\n  probe: DiscoveryProbe = defaultDiscoveryProbe,\n): Promise<DiscoveredDaemon | undefined> {\n  const discovered = await discoverDaemons(probe)\n  return discovered.find((d) => d.record.project === name)\n}\n\n// Signal a running daemon to shut down via its discovery-recorded pid. SIGTERM\n// is the graceful-stop signal every daemon already wires (neatd.ts) — the\n// daemon clears its own discovery file on the way out. Returns true when the\n// signal was delivered, false when the pid was already gone (nothing to stop).\nexport function signalDaemonStop(pid: number): boolean {\n  try {\n    process.kill(pid, 'SIGTERM')\n    return true\n  } catch (err) {\n    // ESRCH → already gone; treat as a no-op success of intent. EPERM and the\n    // rest surface as \"couldn't signal\" so the verb can report honestly.\n    if ((err as NodeJS.ErrnoException).code === 'ESRCH') return false\n    throw err\n  }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// #432 — distinguish a live daemon from a genuinely stale lock.\n//\n// `neat init` used to hang the full timeout on any contended lock and then\n// print one remediation: \"remove the file by hand.\" That advice is actively\n// dangerous when a neat daemon is alive — the daemon grabs the lock for its\n// own registry writes, so hand-removing it races the daemon and corrupts the\n// registry for the live process. The lock now carries the holder PID, and the\n// timeout (or first contention with a live daemon) resolves to a message that\n// names who holds it and what's safe to do.\n// ─────────────────────────────────────────────────────────────────────────\n\nexport type LockHolder =\n  | { kind: 'daemon'; pid: number }\n  | { kind: 'command'; pid: number }\n  | { kind: 'stale' }\n\n// Probes the holder-resolution logic depends on, broken out so tests can drive\n// each branch without a real daemon or live PIDs.\nexport interface LockHolderProbe {\n  // POSIX liveness via `process.kill(pid, 0)`: true if the process exists\n  // (including EPERM — alive but owned by another user), false if it's gone.\n  isPidAlive(pid: number): boolean\n  // PID recorded in `~/.neat/neatd.pid`, or undefined if there's no pidfile.\n  daemonPidFromFile(): Promise<number | undefined>\n  // Whether the daemon's always-open `/health` endpoint answers. Confirms a\n  // live neatd.pid is actually our daemon and not a reused PID.\n  daemonResponds(): Promise<boolean>\n}\n\nfunction isPidAliveDefault(pid: number): boolean {\n  try {\n    process.kill(pid, 0)\n    return true\n  } catch (err) {\n    // ESRCH → no such process (dead). EPERM → exists but owned by another user\n    // (alive). Treat anything else as not-alive: we'd rather under-claim a live\n    // holder than wrongly block on a lock we can't verify.\n    return (err as NodeJS.ErrnoException).code === 'EPERM'\n  }\n}\n\nasync function readPidFile(file: string): Promise<number | undefined> {\n  try {\n    const raw = await fs.readFile(file, 'utf8')\n    const pid = Number.parseInt(raw.trim(), 10)\n    return Number.isInteger(pid) && pid > 0 ? pid : undefined\n  } catch {\n    return undefined\n  }\n}\n\nconst defaultLockHolderProbe: LockHolderProbe = {\n  isPidAlive: isPidAliveDefault,\n  daemonPidFromFile: () => readPidFile(daemonPidPath()),\n  async daemonResponds(): Promise<boolean> {\n    const base = process.env.NEAT_API_URL ?? 'http://localhost:8080'\n    try {\n      // `/health` stays unauthenticated in every mode (auth.ts), so a reachable\n      // daemon answers it even with a bearer token set. Any HTTP response — not\n      // just 2xx — means a daemon owns the port. A short timeout keeps the\n      // fail-fast path well under a second.\n      await fetch(`${base}/health`, { signal: AbortSignal.timeout(750) })\n      return true\n    } catch {\n      return false\n    }\n  },\n}\n\n// Read the PID a lock holder recorded when it created the lock. Undefined for a\n// legacy empty lock, an unreadable file, or a lock unlinked out from under us.\nasync function readLockPid(lockPath: string): Promise<number | undefined> {\n  return readPidFile(lockPath)\n}\n\n// Decide who holds (or orphaned) the lock.\n//\n// The lock's own PID is the evidence, so it is read first: a live process named\n// in the lock is the holder, and it is \"the daemon\" only when the daemon pidfile\n// names that same process. Each project runs its own daemon, so a live pidfile\n// and an answering port say a daemon exists somewhere on the machine — not that\n// it is the one holding this lock (#1268).\n//\n// A lock with no live PID in it can't name anyone. There a live daemon still\n// dominates: while neatd is alive, hand-removing the lock is never safe, so we\n// surface the daemon message even when the lock itself is an empty orphan. We\n// never classify our own process as the blocker — a daemon serializing two of\n// its own registry writes contends with itself briefly and should just retry.\nexport async function classifyLockHolder(\n  lockPath: string,\n  probe: LockHolderProbe = defaultLockHolderProbe,\n): Promise<LockHolder> {\n  const lockPid = await readLockPid(lockPath)\n  const daemonPid = await probe.daemonPidFromFile()\n  if (lockPid !== undefined && lockPid !== process.pid && probe.isPidAlive(lockPid)) {\n    return { kind: lockPid === daemonPid ? 'daemon' : 'command', pid: lockPid }\n  }\n  if (\n    daemonPid !== undefined &&\n    daemonPid !== process.pid &&\n    probe.isPidAlive(daemonPid) &&\n    // Guards against a stale pidfile whose PID got reused.\n    (await probe.daemonResponds())\n  ) {\n    return { kind: 'daemon', pid: daemonPid }\n  }\n  return { kind: 'stale' }\n}\n\nexport function lockHolderMessage(holder: LockHolder, lockPath: string, timeoutMs: number): string {\n  switch (holder.kind) {\n    case 'daemon':\n      return (\n        `The neat daemon (pid ${holder.pid}) is holding the registry lock. ` +\n        'Register this project through the daemon, or stop neatd and re-run `neat init`.'\n      )\n    case 'command':\n      return (\n        `Another neat command (pid ${holder.pid}) is holding the registry lock. ` +\n        \"Wait for it to finish, or check `ps` if you're not sure what's running.\"\n      )\n    case 'stale':\n      return (\n        `timed out after ${timeoutMs}ms waiting for ${lockPath}. ` +\n        'Another neat process is holding the lock; if no such process exists, remove the file by hand.'\n      )\n  }\n}\n\n/**\n * Path normalisation per ADR-048 #7. Two `init` calls from different relative\n * paths to the same dir must collapse to one entry. `path.resolve` handles\n * relative-to-cwd; we pass it through `fs.realpath` when the dir exists so\n * symlinked paths land on the same canonical entry too.\n */\nexport async function normalizeProjectPath(input: string): Promise<string> {\n  const resolved = path.resolve(input)\n  try {\n    return await fs.realpath(resolved)\n  } catch {\n    return resolved\n  }\n}\n\n/**\n * tmp + fsync + rename. The fsync on the data fd guarantees the bytes are on\n * disk before rename swaps the inode; rename itself is atomic on POSIX.\n *\n * Exported so the init flow and test harnesses can use the same helper.\n */\nexport async function writeAtomically(target: string, contents: string): Promise<void> {\n  await fs.mkdir(path.dirname(target), { recursive: true })\n  const tmp = `${target}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`\n  const fd = await fs.open(tmp, 'w')\n  try {\n    await fd.writeFile(contents, 'utf8')\n    await fd.sync()\n  } finally {\n    await fd.close()\n  }\n  await fs.rename(tmp, target)\n}\n\nasync function acquireLock(\n  lockPath: string,\n  timeoutMs: number = LOCK_TIMEOUT_MS,\n  probe: LockHolderProbe = defaultLockHolderProbe,\n): Promise<void> {\n  const deadline = Date.now() + timeoutMs\n  await fs.mkdir(path.dirname(lockPath), { recursive: true })\n  let probedHolder = false\n  while (true) {\n    try {\n      const fd = await fs.open(lockPath, 'wx')\n      try {\n        // Stamp the lock with our PID so a contender can name who holds it and\n        // tell a live holder apart from a stale file. Best-effort: an empty\n        // lock still excludes correctly, it just can't be diagnosed.\n        await fd.writeFile(`${process.pid}\\n`, 'utf8')\n      } finally {\n        await fd.close()\n      }\n      return\n    } catch (err) {\n      const code = (err as NodeJS.ErrnoException).code\n      if (code !== 'EEXIST') throw err\n      // A live daemon holds the registry continuously enough that spinning the\n      // full timeout is pointless — surface the routed remediation on the first\n      // contention. A peer command clears on its own, so that one falls through\n      // to the retry.\n      if (!probedHolder) {\n        probedHolder = true\n        const holder = await classifyLockHolder(lockPath, probe)\n        if (holder.kind === 'daemon') {\n          throw new RegistryLockError(lockHolderMessage(holder, lockPath, timeoutMs))\n        }\n        // Nobody holds this one. A run killed mid-registration leaves the file\n        // behind, and it then blocked every project on the machine until someone\n        // deleted a file they had never heard of (#1241). Reclaim it instead.\n        //\n        // The race is benign: two contenders may both judge it stale and both\n        // unlink, but only one can win the exclusive create that follows and the\n        // loser sees EEXIST and retries. A lock carrying no readable PID waits\n        // out the write window first, so one being stamped right now is never\n        // taken from a live holder.\n        if (holder.kind === 'stale' && (await isReclaimableLock(lockPath))) {\n          await fs.unlink(lockPath).catch(() => {})\n          continue\n        }\n      }\n      if (Date.now() >= deadline) {\n        const holder = await classifyLockHolder(lockPath, probe)\n        throw new RegistryLockError(lockHolderMessage(holder, lockPath, timeoutMs))\n      }\n      await new Promise((r) => setTimeout(r, LOCK_RETRY_MS))\n    }\n  }\n}\n\n// How long a lock with no readable PID has to sit before it counts as\n// abandoned. The PID stamp is best-effort — a holder is briefly EEXIST-visible\n// before it has written — so a pid-less lock is only reclaimed once it has\n// outlived any plausible window between create and stamp.\nconst LOCK_UNSTAMPED_GRACE_MS = 5_000\n\n/**\n * Is this lock safe to take? Only called once the holder has been classified\n * stale — a dead PID, or none at all.\n *\n * A dead PID is unambiguous and reclaims immediately. No PID is not: it might be\n * a holder that has created the file and not yet stamped it, so that case waits\n * out the grace window and reclaims only if the file is genuinely old.\n */\nasync function isReclaimableLock(lockPath: string): Promise<boolean> {\n  const pid = await readLockPid(lockPath)\n  if (pid !== undefined) return true // classified stale with a PID = that PID is dead\n  try {\n    const stat = await fs.stat(lockPath)\n    return Date.now() - stat.mtimeMs > LOCK_UNSTAMPED_GRACE_MS\n  } catch {\n    // Gone between the EEXIST and here — the retry will simply take it.\n    return false\n  }\n}\n\nasync function releaseLock(lockPath: string): Promise<void> {\n  await fs.unlink(lockPath).catch(() => {})\n}\n\n/** The registry lock, for the machine index (registry-index.ts) to share. */\nexport function withRegistryLock<T>(fn: () => Promise<T>): Promise<T> {\n  return withLock(fn)\n}\n\nasync function withLock<T>(fn: () => Promise<T>): Promise<T> {\n  const lock = registryLockPath()\n  await acquireLock(lock)\n  try {\n    return await fn()\n  } finally {\n    await releaseLock(lock)\n  }\n}\n\n/**\n * Read the registry from disk. Returns an empty registry if the file does\n * not exist yet — first run, never registered anything.\n *\n * Throws on parse / schema errors. The contract is single-source-of-truth;\n * a corrupt file is louder than a silent reset.\n */\nexport async function readRegistry(): Promise<RegistryFile> {\n  const file = registryPath()\n  let raw: string\n  try {\n    raw = await fs.readFile(file, 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n      return { version: 1, projects: [] }\n    }\n    throw err\n  }\n  const parsed = JSON.parse(raw)\n  return RegistryFileSchema.parse(parsed)\n}\n\n/** `readRegistry` without awaiting, for a reader that resolves at module load. */\nexport function readRegistrySync(): RegistryFile {\n  let raw: string\n  try {\n    raw = readFileSync(registryPath(), 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { version: 1, projects: [] }\n    throw err\n  }\n  return RegistryFileSchema.parse(JSON.parse(raw))\n}\n\nasync function writeRegistry(reg: RegistryFile): Promise<void> {\n  // Re-parse before writing to surface schema drift introduced by callers\n  // mutating the in-memory object directly.\n  const validated = RegistryFileSchema.parse(reg)\n  await writeAtomically(registryPath(), JSON.stringify(validated, null, 2) + '\\n')\n}\n\nexport interface AddProjectOptions {\n  name: string\n  path: string\n  languages?: string[]\n  status?: RegistryStatus\n}\n\n/**\n * Anything the registry refuses to do.\n *\n * The identity lives on the class, not in the message text. Every caller that\n * prints one already prefixes its own name — the CLI writes `neat: ` — so a\n * message carrying `neat registry:` came out as `neat: neat registry: …`\n * (#1240). A non-CLI caller that wants to know where an error came from reads\n * `err.name`, which is more reliable than a string prefix anyway.\n */\nexport class RegistryError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = 'RegistryError'\n  }\n}\n\n/** The registry lock could not be taken, and says who holds it. */\nexport class RegistryLockError extends RegistryError {\n  constructor(message: string) {\n    super(message)\n    this.name = 'RegistryLockError'\n  }\n}\n\nexport class ProjectNameCollisionError extends RegistryError {\n  readonly projectName: string\n  constructor(name: string) {\n    super(`a project named \"${name}\" is already registered`)\n    this.name = 'ProjectNameCollisionError'\n    this.projectName = name\n  }\n}\n\n/**\n * Register a project, or update its `lastSeenAt` if the same path is already\n * registered under the same name (idempotent re-init).\n *\n * Hard error on name collision against a different path — ADR-046 #7. The\n * caller can recover by passing `--project <new-name>`.\n */\nexport async function addProject(opts: AddProjectOptions): Promise<RegistryEntry> {\n  const resolvedPath = await normalizeProjectPath(opts.path)\n  return withLock(async () => {\n    const reg = await readRegistry()\n    const byName = reg.projects.find((p) => p.name === opts.name)\n    const byPath = reg.projects.find((p) => p.path === resolvedPath)\n\n    if (byName && byName.path !== resolvedPath) {\n      throw new ProjectNameCollisionError(opts.name)\n    }\n\n    const now = new Date().toISOString()\n\n    if (byName && byName.path === resolvedPath) {\n      // Idempotent re-register: same name, same path. Refresh languages /\n      // status if the caller passed new ones.\n      byName.lastSeenAt = now\n      if (opts.languages) byName.languages = opts.languages\n      if (opts.status) byName.status = opts.status\n      await writeRegistry(reg)\n      return byName\n    }\n\n    if (byPath && byPath.name !== opts.name) {\n      // Same dir already registered under a different name. Treat as a\n      // collision so the user is forced to decide which name wins.\n      throw new ProjectNameCollisionError(byPath.name)\n    }\n\n    const entry: RegistryEntry = {\n      name: opts.name,\n      path: resolvedPath,\n      registeredAt: now,\n      languages: opts.languages ?? [],\n      status: opts.status ?? 'active',\n    }\n    reg.projects.push(entry)\n    await writeRegistry(reg)\n    return entry\n  })\n}\n\nexport async function getProject(name: string): Promise<RegistryEntry | undefined> {\n  const reg = await readRegistry()\n  return reg.projects.find((p) => p.name === name)\n}\n\n/**\n * The registered project a directory belongs to: the entry whose path is `dir` itself,\n * or failing that its nearest registered ancestor — so a verb run from `services/api`\n * inside a registered repo still finds the repo. Paths are compared after the same\n * normalisation registration applies (`normalizeProjectPath`), so a symlinked spelling\n * of the directory matches the realpath the registry stored.\n */\nexport async function findProjectByPath(dir: string): Promise<RegistryEntry | undefined> {\n  const here = await normalizeProjectPath(dir)\n  const { projects } = await readRegistry()\n  let best: RegistryEntry | undefined\n  for (const entry of projects) {\n    const inside = here === entry.path || here.startsWith(entry.path + path.sep)\n    if (inside && (!best || entry.path.length > best.path.length)) best = entry\n  }\n  return best\n}\n\n/** `findProjectByPath` without awaiting: the nearest registered project at or above `dir`. */\nexport function findProjectByPathSync(dir: string): RegistryEntry | undefined {\n  const normalize = (input: string): string => {\n    const resolved = path.resolve(input)\n    try {\n      return realpathSync(resolved)\n    } catch {\n      return resolved\n    }\n  }\n  const here = normalize(dir)\n  let best: RegistryEntry | undefined\n  for (const entry of readRegistrySync().projects) {\n    const p = normalize(entry.path)\n    if ((here === p || here.startsWith(p + path.sep)) && (!best || p.length > normalize(best.path).length)) best = entry\n  }\n  return best\n}\n\n/**\n * Synchronous startup lookup for stdio clients such as MCP. This keeps the\n * registry file owned by this module while applying the same nearest-ancestor\n * rule as findProjectByPath and the same discovery parser as the CLI.\n */\nexport function registeredDaemonForPathSync(dir: string): {\n  registered: boolean\n  restPort?: number\n} {\n  const normalize = (input: string): string => {\n    const resolved = path.resolve(input)\n    try {\n      return realpathSync(resolved)\n    } catch {\n      return resolved\n    }\n  }\n  let raw: string\n  try {\n    raw = readFileSync(registryPath(), 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { registered: false }\n    throw err\n  }\n  const projects = RegistryFileSchema.parse(JSON.parse(raw)).projects\n  const here = normalize(dir)\n  let best: RegistryEntry | undefined\n  for (const entry of projects) {\n    const entryPath = normalize(entry.path)\n    if (\n      (here === entryPath || here.startsWith(entryPath + path.sep)) &&\n      (!best || entryPath.length > normalize(best.path).length)\n    )\n      best = entry\n  }\n  if (!best) return { registered: false }\n  let files: string[]\n  try {\n    files = readdirSync(daemonsDir())\n  } catch {\n    return { registered: true }\n  }\n  for (const file of files) {\n    if (!file.endsWith('.json')) continue\n    try {\n      const record = parseDaemonRecord(readFileSync(path.join(daemonsDir(), file), 'utf8'))\n      if (record?.project === best.name && record.status !== 'stopped') {\n        return { registered: true, restPort: record.ports.rest }\n      }\n    } catch {\n      /* skip an unreadable discovery copy */\n    }\n  }\n  return { registered: true }\n}\n\nexport async function listProjects(): Promise<RegistryEntry[]> {\n  const reg = await readRegistry()\n  return reg.projects\n}\n\nexport async function setStatus(name: string, status: RegistryStatus): Promise<RegistryEntry> {\n  return withLock(async () => {\n    const reg = await readRegistry()\n    const entry = reg.projects.find((p) => p.name === name)\n    if (!entry) throw new RegistryError(`no project named \"${name}\"`)\n    entry.status = status\n    await writeRegistry(reg)\n    return entry\n  })\n}\n\nexport async function touchLastSeen(\n  name: string,\n  at: string = new Date().toISOString(),\n): Promise<void> {\n  await withLock(async () => {\n    const reg = await readRegistry()\n    const entry = reg.projects.find((p) => p.name === name)\n    if (!entry) return\n    entry.lastSeenAt = at\n    await writeRegistry(reg)\n  })\n}\n\n/**\n * Remove the registry entry for `name`. Per ADR-048 #6: this only removes the\n * registry row. It does **not** touch `neat-out/`, `policy.json`, or any user\n * file in the project directory. SDK-install rollback is a separate flow\n * (`neat-rollback.patch`) that the caller opts in to.\n */\nexport async function removeProject(name: string): Promise<RegistryEntry | undefined> {\n  return withLock(async () => {\n    const reg = await readRegistry()\n    const idx = reg.projects.findIndex((p) => p.name === name)\n    if (idx < 0) return undefined\n    const [removed] = reg.projects.splice(idx, 1)\n    await writeRegistry(reg)\n    return removed\n  })\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// #463 — prune dead-path entries so the registry doesn't accumulate zombies.\n//\n// Ephemeral tmp-dir projects (smoke runs, throwaway demos) leave entries whose\n// `path` is gone from disk. Without pruning the daemon logs an ENOENT warning\n// for each on every startup forever and `/api/health` lists them as permanent\n// `broken` rows. Pruning removes user-facing state, so it's deliberately\n// conservative: we only ever drop an entry on a *definite* ENOENT (the path is\n// genuinely gone). A transient stat failure — EACCES, EBUSY, an unmounted\n// drive — leaves the entry untouched; it isn't dead, just unreachable.\n//\n// Two modes:\n//  - Auto-prune (daemon bootstrap / reload) gates removal on a staleness TTL.\n//    An ENOENT entry is only dropped if its `lastSeenAt` is older than the TTL,\n//    so a recently-active project whose path is temporarily unavailable stays.\n//  - `neat prune` is explicit user intent, so it drops any ENOENT entry\n//    immediately regardless of age.\n// ─────────────────────────────────────────────────────────────────────────\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n// Default 7 days, mirroring NEAT_STALE_THRESHOLDS' env-override shape.\nexport const DEFAULT_PRUNE_TTL_MS = 7 * DAY_MS\n\nexport function pruneTtlMs(): number {\n  const raw = process.env.NEAT_REGISTRY_PRUNE_TTL_MS\n  if (!raw) return DEFAULT_PRUNE_TTL_MS\n  const n = Number.parseInt(raw, 10)\n  if (Number.isFinite(n) && n >= 0) return n\n  console.warn(\n    `[neat] NEAT_REGISTRY_PRUNE_TTL_MS could not be parsed (${raw}); using default ${DEFAULT_PRUNE_TTL_MS}ms`,\n  )\n  return DEFAULT_PRUNE_TTL_MS\n}\n\n// Classify a single path: 'gone' (definite ENOENT), 'present' (stat succeeded,\n// directory exists), or 'unknown' (a transient/ambiguous error — never prune).\n// Exported so the daemon and tests can probe the same logic.\nexport type PathStatus = 'gone' | 'present' | 'unknown'\n\nasync function statPathStatus(p: string): Promise<PathStatus> {\n  try {\n    const stat = await fs.stat(p)\n    return stat.isDirectory() ? 'present' : 'unknown'\n  } catch (err) {\n    return (err as NodeJS.ErrnoException).code === 'ENOENT' ? 'gone' : 'unknown'\n  }\n}\n\nexport interface PruneOptions {\n  // Override the staleness gate. Auto-prune passes a TTL; `neat prune` passes\n  // `ttlMs: 0` to drop any ENOENT entry immediately. Default is the env-driven\n  // TTL.\n  ttlMs?: number\n  // Override the path probe (tests drive ENOENT / EACCES / present branches\n  // without a real filesystem). Defaults to a real stat.\n  statPath?: (p: string) => Promise<PathStatus>\n  // Clock injection for the staleness comparison; defaults to Date.now().\n  now?: () => number\n}\n\n/**\n * Remove registry entries whose `path` is definitely gone (ENOENT). Goes\n * through the same lock + atomic-write path as every other mutation — never a\n * raw rewrite — so the contract's atomicity invariant holds.\n *\n * Staleness gate: an ENOENT entry is dropped only when `ttlMs` is 0 (explicit\n * `neat prune`) or its `lastSeenAt` (falling back to `registeredAt`) is older\n * than `ttlMs`. A fresh ENOENT entry under a non-zero TTL is left in place — the\n * daemon still marks it `broken`, the TTL is the safety margin before removal.\n *\n * Returns the entries that were removed.\n */\nexport async function pruneRegistry(opts: PruneOptions = {}): Promise<RegistryEntry[]> {\n  const ttlMs = opts.ttlMs ?? pruneTtlMs()\n  const statPath = opts.statPath ?? statPathStatus\n  const now = opts.now ?? Date.now\n\n  return withLock(async () => {\n    const reg = await readRegistry()\n    const removed: RegistryEntry[] = []\n    const kept: RegistryEntry[] = []\n    for (const entry of reg.projects) {\n      const status = await statPath(entry.path)\n      if (status !== 'gone') {\n        // Present, or a transient/ambiguous error — keep it. We only prune on a\n        // definite ENOENT.\n        kept.push(entry)\n        continue\n      }\n      // Path is gone. Drop it immediately when there's no TTL gate, otherwise\n      // only once it's been quiet longer than the TTL.\n      if (ttlMs <= 0) {\n        removed.push(entry)\n        continue\n      }\n      const lastSeen = Date.parse(entry.lastSeenAt ?? entry.registeredAt)\n      const age = now() - (Number.isFinite(lastSeen) ? lastSeen : 0)\n      if (age > ttlMs) {\n        removed.push(entry)\n      } else {\n        kept.push(entry)\n      }\n    }\n    if (removed.length === 0) return []\n    reg.projects = kept\n    await writeRegistry(reg)\n    return removed\n  })\n}\n","// The client profile store — `~/.neat/profiles.json`, the per-user address book\n// of the remote NEATs this machine talks to (client-profiles.md §4, ADR-102).\n//\n// A profile is exactly `{ name, endpoint, authToken? }`: the daemon's REST root\n// and an optional bearer. It is how every NEAT client — the `neat` CLI, the\n// `neat-mcp` server — answers \"which NEAT am I talking to,\" the same code path\n// whether the daemon is a local loopback one (endpoint, no token) or a hosted\n// one (endpoint + token). This module owns the file; resolution precedence\n// (§3) lives in the clients that consume it.\n//\n// This is a CLIENT config, not a daemon registry (§4): daemons never read it,\n// never coordinate through it, and losing it costs convenience, not\n// correctness. It is a per-user `~/.neat` store, sibling to the others, and\n// follows the same discipline — atomic tmp+fsync+rename writes under an\n// exclusive-create lock, mode 0600 because `authToken` is a secret at rest.\n//\n// The `authToken` a hosted profile carries is the per-project daemon token\n// (what the control plane's provision/rotate return): long-lived until rotated\n// and accepted as `Authorization: Bearer <token>` on the daemon's REST root.\n// The short-lived control-plane session token used during login is never\n// persisted here — it authenticates the user just long enough to fetch the\n// daemon token, then is discarded.\n\nimport { promises as fs, readFileSync } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nexport const PROFILES_CONFIG_VERSION = 1\n\n// One remote NEAT this machine talks to. `endpoint` is a daemon REST root\n// (ADR-096 — the project is the daemon; the name is only this profile's label).\nexport interface Profile {\n  name: string\n  endpoint: string\n  authToken?: string\n}\n\n// The file shape. `active` names the profile a client uses when nothing more\n// explicit is selected — the persisted counterpart of `--profile` / NEAT_PROFILE\n// (§3 level 1). It is a pointer by name, so removing a profile clears it.\nexport interface ProfilesConfig {\n  version: number\n  active?: string\n  profiles: Profile[]\n}\n\n// Resolve `~/.neat/` the same way the sibling stores do — per call, honoring a\n// NEAT_HOME override — so a test setting NEAT_HOME (or HOME) before a run lands\n// here too, and module-load order never matters.\nfunction neatHome(): string {\n  const override = process.env.NEAT_HOME\n  if (override && override.length > 0) return path.resolve(override)\n  return path.join(os.homedir(), '.neat')\n}\n\nexport function profilesConfigPath(home: string = neatHome()): string {\n  return path.join(home, 'profiles.json')\n}\n\nexport function profilesConfigLockPath(home: string = neatHome()): string {\n  return path.join(home, 'profiles.json.lock')\n}\n\n// Owner-read/write only. A file with group or other bits set is looser than the\n// 0600 an at-rest bearer calls for — warn, but read it anyway: a\n// mis-permissioned file is a hygiene problem, not a reason to lock a user out\n// of their own hosted graph.\nconst MODE_MASK_LOOSER_THAN_0600 = 0o077\n\nasync function warnIfModeLooserThan0600(file: string): Promise<void> {\n  // The POSIX bits are meaningless on Windows; skip rather than warn on reads.\n  if (process.platform === 'win32') return\n  try {\n    const stat = await fs.stat(file)\n    if ((stat.mode & MODE_MASK_LOOSER_THAN_0600) !== 0) {\n      const mode = (stat.mode & 0o777).toString(8).padStart(3, '0')\n      console.warn(\n        `[neat] ${file} is mode 0${mode}, looser than the 0600 this file's token calls for — run \\`chmod 600 ${file}\\``,\n      )\n    }\n  } catch {\n    // Racing a delete between read and stat is harmless — the read already\n    // succeeded; skip the warning rather than crash on it.\n  }\n}\n\n/**\n * Read and validate `~/.neat/profiles.json`.\n *\n * - A missing file is the common, un-configured case → an empty profile list,\n *   never an error. A machine that has never logged into a hosted NEAT simply\n *   has no named profiles and falls through to local daemon discovery.\n * - A malformed file throws a clear error naming what's wrong, so a hand-edit\n *   typo is legible rather than a silent empty list.\n * - A file looser than 0600 is read but warns.\n */\nexport async function readProfilesConfig(home: string = neatHome()): Promise<ProfilesConfig> {\n  const file = profilesConfigPath(home)\n  let raw: string\n  try {\n    raw = await fs.readFile(file, 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n      return { version: PROFILES_CONFIG_VERSION, profiles: [] }\n    }\n    throw err\n  }\n  await warnIfModeLooserThan0600(file)\n\n  let parsed: unknown\n  try {\n    parsed = JSON.parse(raw)\n  } catch (err) {\n    throw new Error(`${file} is not valid JSON: ${(err as Error).message}`)\n  }\n  return validateConfig(parsed, file)\n}\n\n/**\n * `readProfilesConfig` without awaiting, for a reader that resolves at module\n * load (the MCP server). Same file, same validation; the mode warning is the\n * async reader's.\n */\nexport function readProfilesConfigSync(home: string = neatHome()): ProfilesConfig {\n  const file = profilesConfigPath(home)\n  let raw: string\n  try {\n    raw = readFileSync(file, 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n      return { version: PROFILES_CONFIG_VERSION, profiles: [] }\n    }\n    throw err\n  }\n  let parsed: unknown\n  try {\n    parsed = JSON.parse(raw)\n  } catch (err) {\n    throw new Error(`${file} is not valid JSON: ${(err as Error).message}`)\n  }\n  return validateConfig(parsed, file)\n}\n\nexport function resolveProfileSync(name: string, home: string = neatHome()): Profile | undefined {\n  return readProfilesConfigSync(home).profiles.find((p) => p.name === name)\n}\n\nexport function getActiveProfileSync(home: string = neatHome()): Profile | undefined {\n  const { active, profiles } = readProfilesConfigSync(home)\n  return active ? profiles.find((p) => p.name === active) : undefined\n}\n\nfunction validateConfig(parsed: unknown, file: string): ProfilesConfig {\n  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n    throw new Error(`${file} must be a JSON object with a \"profiles\" array`)\n  }\n  const obj = parsed as Record<string, unknown>\n\n  const version = obj.version === undefined ? PROFILES_CONFIG_VERSION : obj.version\n  if (typeof version !== 'number' || !Number.isInteger(version)) {\n    throw new Error(`${file}: \"version\" must be an integer`)\n  }\n\n  const rawProfiles = obj.profiles\n  if (!Array.isArray(rawProfiles)) {\n    throw new Error(`${file}: \"profiles\" must be an array`)\n  }\n  const profiles = rawProfiles.map((entry, i) => validateEntry(entry, i, file))\n\n  // Reject a duplicate name up front: names are the address a client selects by,\n  // so two entries sharing one make selection ambiguous.\n  const seen = new Set<string>()\n  for (const p of profiles) {\n    if (seen.has(p.name)) throw new Error(`${file}: duplicate profile name \"${p.name}\"`)\n    seen.add(p.name)\n  }\n\n  let active: string | undefined\n  if (obj.active !== undefined) {\n    if (typeof obj.active !== 'string' || obj.active.length === 0) {\n      throw new Error(`${file}: \"active\" must be a non-empty string when present`)\n    }\n    // A dangling `active` (points at a profile that isn't there) is treated as\n    // unset rather than an error — the same graceful-skip the sibling stores use.\n    active = seen.has(obj.active) ? obj.active : undefined\n  }\n\n  return { version, ...(active ? { active } : {}), profiles }\n}\n\nfunction validateEntry(entry: unknown, index: number, file: string): Profile {\n  const where = `${file}: profiles[${index}]`\n  if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {\n    throw new Error(`${where} must be an object`)\n  }\n  const e = entry as Record<string, unknown>\n\n  const name = e.name\n  if (typeof name !== 'string' || name.length === 0) {\n    throw new Error(`${where}.name must be a non-empty string`)\n  }\n\n  const endpoint = e.endpoint\n  if (typeof endpoint !== 'string' || endpoint.length === 0) {\n    throw new Error(`${where}.endpoint must be a non-empty string`)\n  }\n  // A profile endpoint is a daemon REST root — a real absolute URL. Catch the\n  // common paste-mistakes (a bare host, a trailing path) at write/read time\n  // rather than as an opaque fetch failure later.\n  let parsedUrl: URL\n  try {\n    parsedUrl = new URL(endpoint)\n  } catch {\n    throw new Error(`${where}.endpoint must be an absolute URL (got \"${endpoint}\")`)\n  }\n  if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {\n    throw new Error(`${where}.endpoint must be an http(s) URL (got \"${parsedUrl.protocol}\")`)\n  }\n\n  if (e.authToken !== undefined && (typeof e.authToken !== 'string' || e.authToken.length === 0)) {\n    throw new Error(`${where}.authToken must be a non-empty string when present`)\n  }\n\n  return {\n    name,\n    endpoint,\n    ...(typeof e.authToken === 'string' ? { authToken: e.authToken } : {}),\n  }\n}\n\n/**\n * The named profile, or undefined if there is none by that name. This is the\n * primitive the client precedence chain (§3 level 1) calls once it has a name\n * from `--profile` / NEAT_PROFILE / the persisted `active` pointer.\n */\nexport async function resolveProfile(\n  name: string,\n  home: string = neatHome(),\n): Promise<Profile | undefined> {\n  const { profiles } = await readProfilesConfig(home)\n  return profiles.find((p) => p.name === name)\n}\n\n/**\n * The active profile — the persisted default a bare client uses when nothing\n * more explicit is selected — or undefined when none is set. Returns undefined\n * (never throws) on a missing file so a client falls cleanly through to local\n * daemon discovery.\n */\nexport async function getActiveProfile(home: string = neatHome()): Promise<Profile | undefined> {\n  const { active, profiles } = await readProfilesConfig(home)\n  if (!active) return undefined\n  return profiles.find((p) => p.name === active)\n}\n\n// Serialize a config to the on-disk shape, dropping an `active` that no longer\n// points at a real profile so the file never carries a dangling pointer.\nfunction serialize(config: ProfilesConfig): string {\n  const names = new Set(config.profiles.map((p) => p.name))\n  const active = config.active && names.has(config.active) ? config.active : undefined\n  const out: ProfilesConfig = {\n    version: config.version ?? PROFILES_CONFIG_VERSION,\n    ...(active ? { active } : {}),\n    profiles: config.profiles,\n  }\n  return `${JSON.stringify(out, null, 2)}\\n`\n}\n\n/**\n * Write `~/.neat/profiles.json` atomically: a tmp file created mode 0600 (so the\n * token bytes are never briefly world-readable), fsync'd, then renamed over the\n * target — atomic on POSIX, and the rename carries the tmp inode's mode with it.\n * Callers should hold the lock (see `withProfilesLock`) so a read-modify-write\n * can't race another client.\n */\nasync function writeConfigAtomic(config: ProfilesConfig, home: string): Promise<void> {\n  const file = profilesConfigPath(home)\n  await fs.mkdir(path.dirname(file), { recursive: true })\n  const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`\n  const fd = await fs.open(tmp, 'w', 0o600)\n  try {\n    await fd.writeFile(serialize(config), 'utf8')\n    await fd.sync()\n  } finally {\n    await fd.close()\n  }\n  await fs.rename(tmp, file)\n}\n\n// Exclusive-create lock — the same cross-platform flock stand-in the sibling\n// stores use. `wx` fails if the lock file already exists; we retry briefly, then\n// give up rather than hang a CLI forever behind a stale lock.\nconst LOCK_RETRY_MS = 50\nconst LOCK_TIMEOUT_MS = 5_000\n\nasync function acquireLock(lockPath: string): Promise<void> {\n  await fs.mkdir(path.dirname(lockPath), { recursive: true })\n  const deadline = Date.now() + LOCK_TIMEOUT_MS\n  for (;;) {\n    try {\n      const fd = await fs.open(lockPath, 'wx')\n      await fd.writeFile(`${process.pid}\\n`, 'utf8')\n      await fd.close()\n      return\n    } catch (err) {\n      if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err\n      if (Date.now() >= deadline) {\n        throw new Error(\n          `timed out acquiring ${lockPath} after ${LOCK_TIMEOUT_MS}ms — ` +\n            `if no other neat process is running, remove the stale lock file`,\n        )\n      }\n      await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS))\n    }\n  }\n}\n\nasync function releaseLock(lockPath: string): Promise<void> {\n  await fs.rm(lockPath, { force: true })\n}\n\nasync function withProfilesLock<T>(home: string, fn: () => Promise<T>): Promise<T> {\n  const lockPath = profilesConfigLockPath(home)\n  await acquireLock(lockPath)\n  try {\n    return await fn()\n  } finally {\n    await releaseLock(lockPath)\n  }\n}\n\n/**\n * Add or replace a profile by name, under the lock. When `makeActive` is set (or\n * this is the first profile written), the new profile also becomes active — the\n * common case for `neat login`, where connecting a machine to a hosted NEAT\n * should also point the local clients at it.\n */\nexport async function upsertProfile(\n  profile: Profile,\n  opts: { makeActive?: boolean; home?: string } = {},\n): Promise<void> {\n  const home = opts.home ?? neatHome()\n  // Validate the caller's profile through the same gate a hand-edited file goes\n  // through, so a bad endpoint is rejected before it reaches disk.\n  const validated = validateEntry(profile, 0, profilesConfigPath(home))\n  await withProfilesLock(home, async () => {\n    const config = await readProfilesConfig(home)\n    const others = config.profiles.filter((p) => p.name !== validated.name)\n    const profiles = [...others, validated]\n    const makeActive = opts.makeActive ?? config.profiles.length === 0\n    const active = makeActive ? validated.name : config.active\n    await writeConfigAtomic({ version: config.version, ...(active ? { active } : {}), profiles }, home)\n  })\n}\n\n/**\n * Remove a profile by name, under the lock. Returns whether one was removed. A\n * removed profile that was active clears the active pointer (serialize drops a\n * dangling one) — a client then falls back to local discovery, never to a\n * silently different endpoint.\n */\nexport async function removeProfile(name: string, home: string = neatHome()): Promise<boolean> {\n  return withProfilesLock(home, async () => {\n    const config = await readProfilesConfig(home)\n    const profiles = config.profiles.filter((p) => p.name !== name)\n    if (profiles.length === config.profiles.length) return false\n    const active = config.active === name ? undefined : config.active\n    await writeConfigAtomic({ version: config.version, ...(active ? { active } : {}), profiles }, home)\n    return true\n  })\n}\n\n/**\n * Clear the active pointer, leaving the profiles in place, under the lock —\n * a client then falls back to local discovery (`neat logout`). Returns whether\n * an active pointer was actually cleared, so the caller can tell \"logged out\"\n * from \"wasn't logged in\".\n */\nexport async function clearActiveProfile(home: string = neatHome()): Promise<boolean> {\n  return withProfilesLock(home, async () => {\n    const config = await readProfilesConfig(home)\n    if (!config.active) return false\n    await writeConfigAtomic({ version: config.version, profiles: config.profiles }, home)\n    return true\n  })\n}\n\n/**\n * Point the active pointer at an existing profile, under the lock. Throws if no\n * profile by that name exists — selecting a non-existent endpoint should fail\n * loudly, not silently set a dangling pointer.\n */\nexport async function setActiveProfile(name: string, home: string = neatHome()): Promise<void> {\n  await withProfilesLock(home, async () => {\n    const config = await readProfilesConfig(home)\n    if (!config.profiles.some((p) => p.name === name)) {\n      throw new Error(`no profile named \"${name}\" — run \\`neat login\\` or add it first`)\n    }\n    await writeConfigAtomic({ version: config.version, active: name, profiles: config.profiles }, home)\n  })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,oBAAiB;;;ACAjB,qBAAyD;AACzD,uBAAiB;AACjB,yBAA4B;AAarB,IAAM,WAAW;AACjB,IAAM,eAAe;AACrB,IAAM,eAAe;AACrB,IAAM,yBAAyB;AAC/B,IAAM,yBAAyB;AAoB/B,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,gBAAgB;AA6BtB,SAAS,gBAAgB,MAAsB;AACpD,SAAO,iBAAAC,QAAK,KAAK,MAAM,UAAU,YAAY;AAC/C;AACO,SAAS,gBAAgB,MAAsB;AACpD,SAAO,iBAAAA,QAAK,KAAK,MAAM,UAAU,YAAY;AAC/C;AAmBA,SAAS,MAAM,GAA0C;AACvD,SAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAChE;AAGA,SAAS,cAAc,GAAY,MAA+B;AAChE,MAAI,CAAC,MAAM,CAAC,EAAG,OAAM,IAAI,qBAAqB,GAAG,IAAI,wBAAwB;AAC7E,MAAI,EAAE,eAAe,MAAM,wBAAwB;AACjD,UAAM,IAAI;AAAA,MACR,GAAG,I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AAI,GAAG;AACtC,cAAU,gBAAgB,IAAI;AAAA,EAChC,SAAS,KAAK;AAGZ,QAAI,eAAe,qBAAsB;AACzC,UAAM;AAAA,EACR;AACA,MAAI,QAAQ,YAAY,SAAU,OAAM,IAAI,mBAAmB,QAAQ,kBAAAD,QAAK,SAAS,IAAI,GAAG,QAAQ,GAAG;AACzG;","names":["import_node_path","path","path","import_node_fs","import_node_path","path","os","path","path","path","import_node_fs","import_node_os","import_node_path","neatHome","path","os","neatHome","path","id"]}